commit 1347b9ea1021842b2a3220497512037dca44583d Author: William Brawner Date: Wed Jan 1 14:21:33 2020 -0600 Implement working Pi-hole connections and management Signed-off-by: William Brawner diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..603b140 --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +*.iml +.gradle +/local.properties +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +.DS_Store +/build +/captures +.externalNativeBuild +.cxx diff --git a/.idea/.name b/.idea/.name new file mode 100644 index 0000000..db548ff --- /dev/null +++ b/.idea/.name @@ -0,0 +1 @@ +Pi-Helper \ No newline at end of file diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml new file mode 100644 index 0000000..6d29e86 --- /dev/null +++ b/.idea/codeStyles/Project.xml @@ -0,0 +1,126 @@ + + + + + + + + + + + +
+ + + + xmlns:android + + ^$ + + + +
+
+ + + + xmlns:.* + + ^$ + + + BY_NAME + +
+
+ + + + .*:id + + http://schemas.android.com/apk/res/android + + + +
+
+ + + + .*:name + + http://schemas.android.com/apk/res/android + + + +
+
+ + + + name + + ^$ + + + +
+
+ + + + style + + ^$ + + + +
+
+ + + + .* + + ^$ + + + BY_NAME + +
+
+ + + + .* + + http://schemas.android.com/apk/res/android + + + ANDROID_ATTRIBUTE_ORDER + +
+
+ + + + .* + + .* + + + BY_NAME + +
+
+
+
+ + +
+
\ No newline at end of file diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 0000000..79ee123 --- /dev/null +++ b/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..da811ea --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,20 @@ + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..703e5d4 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/runConfigurations.xml b/.idea/runConfigurations.xml new file mode 100644 index 0000000..7f68460 --- /dev/null +++ b/.idea/runConfigurations.xml @@ -0,0 +1,12 @@ + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/app/.gitignore @@ -0,0 +1 @@ +/build diff --git a/app/build.gradle b/app/build.gradle new file mode 100644 index 0000000..850bdaf --- /dev/null +++ b/app/build.gradle @@ -0,0 +1,53 @@ +apply plugin: 'com.android.application' +apply plugin: 'kotlin-android' +apply plugin: 'kotlin-android-extensions' + +android { + compileSdkVersion 29 + defaultConfig { + applicationId "com.wbrawner.pihelper" + minSdkVersion 23 + targetSdkVersion 29 + versionCode 1 + versionName "1.0" + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + signingConfig signingConfigs.debug + } + buildTypes { + release { + minifyEnabled true + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } +} + +dependencies { + implementation project(':piholeclient') + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" + implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version" + implementation "org.koin:koin-androidx-viewmodel:$koin_version" + implementation 'androidx.appcompat:appcompat:1.1.0' + implementation 'androidx.core:core-ktx:1.1.0' + implementation 'androidx.constraintlayout:constraintlayout:1.1.3' + implementation 'com.google.android.material:material:1.2.0-alpha02' + implementation 'androidx.legacy:legacy-support-v4:1.0.0' + implementation 'androidx.security:security-crypto:1.0.0-alpha02' + implementation 'androidx.preference:preference:1.1.0' + testImplementation 'junit:junit:4.12' + androidTestImplementation 'androidx.test.ext:junit:1.1.1' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' + def navigation_version = '2.1.0' + implementation "androidx.navigation:navigation-fragment-ktx:$navigation_version" + implementation "androidx.navigation:navigation-ui-ktx:$navigation_version" + def lifecycle_version = '2.1.0' + implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version" + implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version" + def acraVersion = '5.1.3' + implementation "ch.acra:acra-mail:$acraVersion" + implementation "ch.acra:acra-notification:$acraVersion" + implementation "ch.acra:acra-limiter:$acraVersion" +} diff --git a/app/google-services.json b/app/google-services.json new file mode 100644 index 0000000..2a61ab2 --- /dev/null +++ b/app/google-services.json @@ -0,0 +1,48 @@ +{ + "project_info": { + "project_number": "511023365625", + "firebase_url": "https://pi-helper-d3885.firebaseio.com", + "project_id": "pi-helper-d3885", + "storage_bucket": "pi-helper-d3885.appspot.com" + }, + "client": [ + { + "client_info": { + "mobilesdk_app_id": "1:511023365625:android:f8d76275e55f6db4efd128", + "android_client_info": { + "package_name": "com.wbrawner.pihelper" + } + }, + "oauth_client": [ + { + "client_id": "511023365625-d5fi76hu5mu838tblaahrfdudjdlels8.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "com.wbrawner.pihelper", + "certificate_hash": "e705f9dfdbd6ab7a79c902bc94c8448030f52c89" + } + }, + { + "client_id": "511023365625-k0t6fbagmsgdveg6e673detjf75fmi2l.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyDv9-WRa4xWFswXr5qBWVaAzA-UOraAsHc" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "511023365625-k0t6fbagmsgdveg6e673detjf75fmi2l.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + } + ], + "configuration_version": "1" +} \ No newline at end of file diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..462dd20 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/app/src/androidTest/java/com/wbrawner/pihelper/ExampleInstrumentedTest.kt b/app/src/androidTest/java/com/wbrawner/pihelper/ExampleInstrumentedTest.kt new file mode 100644 index 0000000..aea9a83 --- /dev/null +++ b/app/src/androidTest/java/com/wbrawner/pihelper/ExampleInstrumentedTest.kt @@ -0,0 +1,24 @@ +package com.wbrawner.pihelper + +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.ext.junit.runners.AndroidJUnit4 + +import org.junit.Test +import org.junit.runner.RunWith + +import org.junit.Assert.* + +/** + * Instrumented test, which will execute on an Android device. + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +@RunWith(AndroidJUnit4::class) +class ExampleInstrumentedTest { + @Test + fun useAppContext() { + // Context of the app under test. + val appContext = InstrumentationRegistry.getInstrumentation().targetContext + assertEquals("com.wbrawner.pihelper", appContext.packageName) + } +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..fb11a14 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/ic_launcher-web.png b/app/src/main/ic_launcher-web.png new file mode 100644 index 0000000..dc8c839 Binary files /dev/null and b/app/src/main/ic_launcher-web.png differ diff --git a/app/src/main/java/com/wbrawner/pihelper/AddPiHelperViewModel.kt b/app/src/main/java/com/wbrawner/pihelper/AddPiHelperViewModel.kt new file mode 100644 index 0000000..1bbf755 --- /dev/null +++ b/app/src/main/java/com/wbrawner/pihelper/AddPiHelperViewModel.kt @@ -0,0 +1,146 @@ +package com.wbrawner.pihelper + +import android.content.SharedPreferences +import android.util.Log +import androidx.core.content.edit +import androidx.lifecycle.MutableLiveData +import androidx.lifecycle.ViewModel +import com.wbrawner.piholeclient.PiHoleApiService +import com.wbrawner.piholeclient.Summary +import com.wbrawner.piholeclient.VersionResponse +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.withContext +import java.net.ConnectException +import java.net.SocketTimeoutException +import java.util.regex.Pattern +import java.util.regex.Pattern.DOTALL + +const val KEY_BASE_URL = "baseUrl" +const val KEY_API_KEY = "apiKey" +const val IP_MIN = 0 +const val IP_MAX = 255 + +class AddPiHelperViewModel( + private val sharedPreferences: SharedPreferences, + private val apiService: PiHoleApiService +) : ViewModel() { + + @Volatile + var baseUrl: String? = sharedPreferences.getString(KEY_BASE_URL, null) + set(value) { + sharedPreferences.edit { + putString(KEY_BASE_URL, value) + } + field = value + } + + @Volatile + var apiKey: String? = sharedPreferences.getString(KEY_API_KEY, null) + set(value) { + sharedPreferences.edit { + putString(KEY_API_KEY, value) + } + field = value + } + + init { + apiService.baseUrl = this.baseUrl + apiService.apiKey = this.apiKey + } + + val piHoleIpAddress = MutableLiveData() + val scanningIp = MutableLiveData() + val authenticated = MutableLiveData() + + suspend fun beginScanning(deviceIpAddress: String) { + val addressParts = deviceIpAddress.split(".").toMutableList() + var chunks = 1 + val ipAddresses = mutableListOf() + while (chunks <= IP_MAX) { + val chunkSize = (IP_MAX - IP_MIN + 1) / chunks + if (chunkSize == 1) { + return + } + for (chunk in 0 until chunks) { + val chunkStart = IP_MIN + (chunk * chunkSize) + val chunkEnd = IP_MIN + ((chunk + 1) * chunkSize) + addressParts[3] = (((chunkEnd - chunkStart) / 2) + chunkStart).toString() + ipAddresses.add(addressParts.joinToString(".")) + } + chunks *= 2 + } + scan(ipAddresses) + } + + private suspend fun scan(ipAddresses: MutableList) { + if (ipAddresses.isEmpty()) { + scanningIp.postValue(null) + piHoleIpAddress.postValue(null) + return + } + + val ipAddress = ipAddresses.removeAt(0) + scanningIp.postValue(ipAddress) + if (!connectToIpAddress(ipAddress)) { + scan(ipAddresses) + } + } + + suspend fun connectToIpAddress(ipAddress: String): Boolean { + val version: VersionResponse? = withContext(Dispatchers.IO) { + try { + apiService.baseUrl = ipAddress + apiService.getVersion() + } catch (ignored: ConnectException) { + null + } catch (ignored: SocketTimeoutException) { + null + } catch (e: Exception) { + Log.e("Pi-Helper", "Failed to load Pi-Hole version at $ipAddress", e) + null + } + } + return if (version == null) { + false + } else { + piHoleIpAddress.postValue(ipAddress) + baseUrl = ipAddress + true + } + } + + suspend fun authenticateWithPassword(password: String) { + // Perform the login to get the PHPSESSID cookie set + apiService.login(password) + val html = apiService.getApiToken() + val matcher = Pattern.compile(".*Raw API Token: ([a-z0-9]+).*", DOTALL) + .matcher(html) + if (!matcher.matches()) { + throw RuntimeException("Unable to retrieve API token from password") + } + val apiToken = matcher.group(1)!! + authenticateWithApiKey(apiToken) + } + + suspend fun authenticateWithApiKey(apiKey: String) { + // This uses the topItems endpoint to test that the API key is working since it requires + // authentication and is fairly simple to determine whether or not the request was + // successful + apiService.apiKey = apiKey + try { + apiService.getTopItems() + this.apiKey = apiKey + authenticated.postValue(true) + } catch (e: Exception) { + Log.e("Pi-Helper", "Unable to authenticate with API key", e) + authenticated.postValue(false) + throw e + } + } + + fun forgetPihole() { + baseUrl = null + apiKey = null + } +} \ No newline at end of file diff --git a/app/src/main/java/com/wbrawner/pihelper/AddPiHoleFragment.kt b/app/src/main/java/com/wbrawner/pihelper/AddPiHoleFragment.kt new file mode 100644 index 0000000..1c703c8 --- /dev/null +++ b/app/src/main/java/com/wbrawner/pihelper/AddPiHoleFragment.kt @@ -0,0 +1,65 @@ +package com.wbrawner.pihelper + + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.appcompat.app.AlertDialog +import androidx.fragment.app.Fragment +import androidx.navigation.NavOptionsBuilder +import androidx.navigation.fragment.FragmentNavigatorExtras +import androidx.navigation.fragment.findNavController +import kotlinx.android.synthetic.main.fragment_add_pi_hole.* +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.launch +import org.koin.android.ext.android.inject +import kotlin.coroutines.CoroutineContext + +class AddPiHoleFragment : Fragment(), CoroutineScope { + + override val coroutineContext: CoroutineContext = Dispatchers.Main + private val viewModel: AddPiHelperViewModel by inject() + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? = inflater.inflate(R.layout.fragment_add_pi_hole, container, false) + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + val navController = findNavController() + scanNetworkButton.setOnClickListener { + navController.navigate( + R.id.action_addPiHoleFragment_to_scanNetworkFragment, + null, + null, + FragmentNavigatorExtras(piHelperLogo to "piHelperLogo") + ) + } + connectButton.setOnClickListener { + launch { + if (viewModel.connectToIpAddress(ipAddress.text.toString())) { + navController.navigate( + R.id.action_addPiHoleFragment_to_retrieveApiKeyFragment, + null, + null, + FragmentNavigatorExtras(piHelperLogo to "piHelperLogo") + ) + } else { + AlertDialog.Builder(view.context) + .setTitle(R.string.connection_failed_title) + .setMessage(R.string.connection_failed) + .setPositiveButton(android.R.string.ok) { _, _ -> } + .show() + } + } + } + } + + override fun onDestroyView() { + coroutineContext[Job]?.cancel() + super.onDestroyView() + } +} diff --git a/app/src/main/java/com/wbrawner/pihelper/Extensions.kt b/app/src/main/java/com/wbrawner/pihelper/Extensions.kt new file mode 100644 index 0000000..ab54674 --- /dev/null +++ b/app/src/main/java/com/wbrawner/pihelper/Extensions.kt @@ -0,0 +1,3 @@ +package com.wbrawner.pihelper + +fun R.transform(block: (R) -> T): T = block(this) \ No newline at end of file diff --git a/app/src/main/java/com/wbrawner/pihelper/InfoFragment.kt b/app/src/main/java/com/wbrawner/pihelper/InfoFragment.kt new file mode 100644 index 0000000..e27795b --- /dev/null +++ b/app/src/main/java/com/wbrawner/pihelper/InfoFragment.kt @@ -0,0 +1,82 @@ +package com.wbrawner.pihelper + + +import android.content.Intent +import android.os.Build +import android.os.Bundle +import android.text.Html +import android.text.method.LinkMovementMethod +import android.view.LayoutInflater +import android.view.MenuItem +import android.view.View +import android.view.ViewGroup +import androidx.appcompat.app.AlertDialog +import androidx.appcompat.app.AppCompatActivity +import androidx.fragment.app.Fragment +import androidx.navigation.fragment.findNavController +import com.wbrawner.pihelper.MainActivity.Companion.ACTION_FORGET_PIHOLE +import kotlinx.android.synthetic.main.fragment_main.toolbar +import kotlinx.android.synthetic.main.fragment_info.* +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import org.koin.android.ext.android.inject +import java.lang.RuntimeException +import kotlin.coroutines.CoroutineContext + +class InfoFragment : Fragment(), CoroutineScope { + override val coroutineContext: CoroutineContext = Dispatchers.Main + private val viewModel: AddPiHelperViewModel by inject() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setHasOptionsMenu(true) + throw RuntimeException("I crashed!") + } + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? = inflater.inflate(R.layout.fragment_info, container, false) + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + (activity as? AppCompatActivity)?.setSupportActionBar(toolbar) + (activity as? AppCompatActivity)?.supportActionBar?.setDisplayHomeAsUpEnabled(true) + (activity as? AppCompatActivity)?.supportActionBar?.setTitle(R.string.action_settings) + val html = getString(R.string.content_info) + @Suppress("DEPRECATION") + infoContent?.text = if (Build.VERSION.SDK_INT < 24) + Html.fromHtml(html) + else + Html.fromHtml(html, 0) + infoContent.movementMethod = LinkMovementMethod.getInstance() + forgetPiHoleButton?.setOnClickListener { + AlertDialog.Builder(view.context) + .setTitle(R.string.confirm_forget_pihole) + .setMessage(R.string.warning_cannot_be_undone) + .setNegativeButton(android.R.string.cancel) { _, _ -> } + .setPositiveButton(R.string.action_forget_pihole) { _, _ -> + viewModel.forgetPihole() + val refreshIntent = Intent( + view.context.applicationContext, + MainActivity::class.java + ).apply { + action = ACTION_FORGET_PIHOLE + addFlags( + Intent.FLAG_ACTIVITY_CLEAR_TASK + and Intent.FLAG_ACTIVITY_NEW_TASK + ) + } + activity?.startActivity(refreshIntent) + } + .show() + } + } + + override fun onOptionsItemSelected(item: MenuItem): Boolean { + if (item.itemId == android.R.id.home) { + findNavController().navigateUp() + return true + } + return super.onOptionsItemSelected(item) + } +} diff --git a/app/src/main/java/com/wbrawner/pihelper/MainActivity.kt b/app/src/main/java/com/wbrawner/pihelper/MainActivity.kt new file mode 100644 index 0000000..6b6629f --- /dev/null +++ b/app/src/main/java/com/wbrawner/pihelper/MainActivity.kt @@ -0,0 +1,84 @@ +package com.wbrawner.pihelper + +import android.graphics.drawable.ColorDrawable +import android.os.Bundle +import android.widget.Toast +import androidx.appcompat.app.AppCompatActivity +import androidx.navigation.findNavController +import com.wbrawner.pihelper.MainFragment.Companion.ACTION_DISABLE +import com.wbrawner.pihelper.MainFragment.Companion.ACTION_ENABLE +import com.wbrawner.pihelper.MainFragment.Companion.EXTRA_DURATION +import org.koin.android.ext.android.inject + +class MainActivity : AppCompatActivity() { + private val addPiHoleViewModel: AddPiHelperViewModel by inject() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_main) + window.setBackgroundDrawable(ColorDrawable(getColor(R.color.colorSurface))) + val navController = findNavController(R.id.content_main) + val analyticsBundle = Bundle() + analyticsBundle.putString("intent_action", intent.action) + val args = when (intent.action) { + ACTION_ENABLE -> { + if (addPiHoleViewModel.apiKey == null) { + Toast.makeText(this, R.string.configure_pihelper, Toast.LENGTH_SHORT).show() + null + } else { + Bundle().apply { putBoolean(ACTION_ENABLE, true) } + } + } + ACTION_DISABLE -> { + if (addPiHoleViewModel.apiKey == null) { + Toast.makeText(this, R.string.configure_pihelper, Toast.LENGTH_SHORT).show() + null + } else { + Bundle().apply { + putBoolean(ACTION_DISABLE, true) + putLong(EXTRA_DURATION, intent.getIntExtra(EXTRA_DURATION, 10).toLong()) + } + } + } + ACTION_FORGET_PIHOLE -> { + if (intent.component?.packageName == packageName) { + while (navController.popBackStack()) { + // Do nothing, just pop all the items off the back stack + } + // Just return an empty bundle so that the navigation branch below will load + // the correct screen + Bundle() + } else { + null + } + } + else -> null + } + val navDestination = when { + navController.currentDestination?.id != R.id.placeholder && args == null -> { + return + } + addPiHoleViewModel.baseUrl.isNullOrBlank() -> { + R.id.addPiHoleFragment + } + addPiHoleViewModel.apiKey.isNullOrBlank() -> { + R.id.retrieveApiKeyFragment + } + else -> { + R.id.mainFragment + } + } + navController.navigate(navDestination, args) + } + + override fun onBackPressed() { + when (findNavController(R.id.content_main).currentDestination?.id) { + R.id.addPiHoleFragment, R.id.mainFragment -> finish() + else -> super.onBackPressed() + } + } + + companion object { + const val ACTION_FORGET_PIHOLE = "com.wbrawner.pihelper.ACTION_FORGET_PIHOLE" + } +} diff --git a/app/src/main/java/com/wbrawner/pihelper/MainFragment.kt b/app/src/main/java/com/wbrawner/pihelper/MainFragment.kt new file mode 100644 index 0000000..1f877b4 --- /dev/null +++ b/app/src/main/java/com/wbrawner/pihelper/MainFragment.kt @@ -0,0 +1,218 @@ +package com.wbrawner.pihelper + + +import android.graphics.Typeface +import android.os.Bundle +import android.text.SpannableString +import android.text.style.ForegroundColorSpan +import android.text.style.StyleSpan +import android.util.Log +import android.view.* +import android.view.animation.Animation +import android.view.animation.LinearInterpolator +import android.view.animation.RotateAnimation +import android.widget.EditText +import android.widget.RadioGroup +import androidx.appcompat.app.AlertDialog +import androidx.appcompat.app.AppCompatActivity +import androidx.core.content.ContextCompat.getColor +import androidx.core.text.set +import androidx.fragment.app.Fragment +import androidx.lifecycle.Observer +import androidx.navigation.fragment.findNavController +import com.wbrawner.piholeclient.Status +import kotlinx.android.synthetic.main.fragment_main.* +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.launch +import org.koin.android.ext.android.inject +import kotlin.coroutines.CoroutineContext + +class MainFragment : Fragment(), CoroutineScope { + override val coroutineContext: CoroutineContext = Dispatchers.Main + private val viewModel: PiHelperViewModel by inject() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setHasOptionsMenu(true) + launch { + if (arguments?.getBoolean(ACTION_ENABLE) == true) { + viewModel.enablePiHole() + } else if (arguments?.getBoolean(ACTION_DISABLE) == true) { + viewModel.disablePiHole(arguments?.getLong(EXTRA_DURATION)) + } + viewModel.monitorSummary() + } + viewModel.summary.observe(this, Observer { summary -> + showProgress(false) + val (statusColor, statusText) = if ( + summary.status == Status.DISABLED + ) { + enableButton?.visibility = View.VISIBLE + disableButtons?.visibility = View.GONE + Pair(R.color.colorDisabled, R.string.status_disabled) + } else { + enableButton?.visibility = View.GONE + disableButtons?.visibility = View.VISIBLE + Pair(R.color.colorEnabled, R.string.status_enabled) + } + status?.let { + val status = getString(statusText) + val statusLabel = getString(R.string.label_status, status) + val start = statusLabel.indexOf(status) + val end = start + status.length + val statusSpan = SpannableString(statusLabel) + statusSpan[start, end] = StyleSpan(Typeface.BOLD) + statusSpan[start, end] = ForegroundColorSpan(getColor(it.context, statusColor)) + it.text = statusSpan + } + }) + } + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? = inflater.inflate(R.layout.fragment_main, container, false) + + override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { + inflater.inflate(R.menu.main, menu) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + (activity as? AppCompatActivity)?.setSupportActionBar(toolbar) + showProgress(true) + enableButton?.setOnClickListener { + launch { + showProgress(true) + try { + viewModel.enablePiHole() + } catch (ignored: Exception) { + Log.e("Pi-Helper", "Failed to enable Pi-Hole", ignored) + } + } + } + disable10SecondsButton?.setOnClickListener { + launch { + showProgress(true) + try { + viewModel.disablePiHole(10) + } catch (ignored: Exception) { + Log.e("Pi-Helper", "Failed to disable Pi-Hole", ignored) + } + } + } + disable30SecondsButton?.setOnClickListener { + launch { + showProgress(true) + try { + viewModel.disablePiHole(30) + } catch (ignored: Exception) { + Log.e("Pi-Helper", "Failed to disable Pi-Hole", ignored) + } + } + } + disable5MinutesButton?.setOnClickListener { + launch { + showProgress(true) + try { + viewModel.disablePiHole(300) + } catch (ignored: Exception) { + Log.e("Pi-Helper", "Failed to disable Pi-Hole", ignored) + } + } + } + disableCustomTimeButton?.setOnClickListener { + val dialogView = LayoutInflater.from(it.context) + .inflate(R.layout.dialog_disable_custom_time, null, false) + AlertDialog.Builder(it.context) + .setTitle(R.string.action_disable_custom) + .setNegativeButton(android.R.string.cancel) { _, _ -> } + .setPositiveButton(R.string.action_disable, null) + .setView(dialogView) + .create() + .apply { + setOnShowListener { + getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { + launch { + try { + val rawTime = dialogView.findViewById(R.id.time) + .text + .toString() + .toLong() + val checkedId = + dialogView.findViewById(R.id.timeUnit) + .checkedRadioButtonId + val computedTime = if (checkedId == R.id.seconds) rawTime + else rawTime * 60 + viewModel.disablePiHole(computedTime) + dismiss() + } catch (e: Exception) { + dialogView.findViewById(R.id.time) + .error = "Failed to disable Pi-hole" + } + } + } + } + } + .show() + } + disablePermanentlyButton?.setOnClickListener { + launch { + showProgress(true) + try { + viewModel.disablePiHole() + } catch (ignored: Exception) { + Log.e("Pi-Helper", "Failed to disable Pi-Hole", ignored) + } + } + } + } + + override fun onOptionsItemSelected(item: MenuItem): Boolean { + if (item.itemId == R.id.settings) { + findNavController().navigate(R.id.action_mainFragment_to_settingsFragment) + return true + } + return super.onOptionsItemSelected(item) + } + + private fun showProgress(show: Boolean) { + progressBar?.visibility = if (show) { + progressBar?.startAnimation(RotateAnimation( + 0f, + 360f, + Animation.RELATIVE_TO_SELF, + 0.5f, + Animation.RELATIVE_TO_SELF, + 0.5f + ).apply { + duration = resources.getInteger(android.R.integer.config_longAnimTime).toLong() * 2 + repeatMode = Animation.RESTART + repeatCount = Animation.INFINITE + interpolator = LinearInterpolator() + fillAfter = true + }) + View.VISIBLE + } else { + progressBar?.clearAnimation() + View.GONE + } + statusContent?.visibility = if (show) { + View.GONE + } else { + View.VISIBLE + } + } + + override fun onDestroyView() { + coroutineContext[Job]?.cancel() + super.onDestroyView() + } + + companion object { + const val ACTION_DISABLE = "com.wbrawner.pihelper.MainFragment.ACTION_DISABLE" + const val ACTION_ENABLE = "com.wbrawner.pihelper.MainFragment.ACTION_ENABLE" + const val EXTRA_DURATION = "com.wbrawner.pihelper.MainFragment.EXTRA_DURATION" + } +} diff --git a/app/src/main/java/com/wbrawner/pihelper/PiHelperApplication.kt b/app/src/main/java/com/wbrawner/pihelper/PiHelperApplication.kt new file mode 100644 index 0000000..efb4cea --- /dev/null +++ b/app/src/main/java/com/wbrawner/pihelper/PiHelperApplication.kt @@ -0,0 +1,39 @@ +package com.wbrawner.pihelper + +import android.app.Application +import android.content.Context +import com.wbrawner.piholeclient.piHoleClientModule +import org.acra.ACRA +import org.acra.annotation.AcraCore +import org.acra.annotation.AcraMailSender +import org.acra.annotation.AcraNotification +import org.koin.android.ext.koin.androidContext +import org.koin.android.ext.koin.androidLogger +import org.koin.core.context.startKoin + +@AcraCore(buildConfigClass = BuildConfig::class) +@AcraMailSender(mailTo = "pihelper@wbrawner.com") +@AcraNotification( + resIcon = R.drawable.ic_notification, + resTitle = R.string.title_crash_notification, + resText = R.string.text_crash_notification, + resChannelName = R.string.channel_crash_notification +) +class PiHelperApplication: Application() { + override fun onCreate() { + super.onCreate() + startKoin{ + androidLogger() + androidContext(this@PiHelperApplication) + modules(listOf( + piHoleClientModule, + piHelperModule + )) + } + } + + override fun attachBaseContext(base: Context?) { + super.attachBaseContext(base) + ACRA.init(this) + } +} \ No newline at end of file diff --git a/app/src/main/java/com/wbrawner/pihelper/PiHelperModule.kt b/app/src/main/java/com/wbrawner/pihelper/PiHelperModule.kt new file mode 100644 index 0000000..adf00c6 --- /dev/null +++ b/app/src/main/java/com/wbrawner/pihelper/PiHelperModule.kt @@ -0,0 +1,33 @@ +package com.wbrawner.pihelper + +import androidx.security.crypto.EncryptedSharedPreferences +import com.wbrawner.piholeclient.NAME_BASE_URL +import org.koin.androidx.viewmodel.dsl.viewModel +import org.koin.core.qualifier.named +import org.koin.dsl.module + +const val ENCRYPTED_SHARED_PREFS_FILE_NAME = "pihelper.prefs" + +val piHelperModule = module { + single { + EncryptedSharedPreferences.create( + ENCRYPTED_SHARED_PREFS_FILE_NAME, + "pihelper", + get(), + EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, + EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM + ) + } + + viewModel { + AddPiHelperViewModel(get(), get()) + } + + viewModel { + PiHelperViewModel(get()) + } + + single(named(NAME_BASE_URL)) { + get().getString(KEY_BASE_URL, "") + } +} \ No newline at end of file diff --git a/app/src/main/java/com/wbrawner/pihelper/PiHelperViewModel.kt b/app/src/main/java/com/wbrawner/pihelper/PiHelperViewModel.kt new file mode 100644 index 0000000..fd4a1da --- /dev/null +++ b/app/src/main/java/com/wbrawner/pihelper/PiHelperViewModel.kt @@ -0,0 +1,41 @@ +package com.wbrawner.pihelper + +import androidx.lifecycle.MutableLiveData +import androidx.lifecycle.ViewModel +import com.wbrawner.piholeclient.PiHoleApiService +import com.wbrawner.piholeclient.Summary +import kotlinx.coroutines.NonCancellable.isActive +import kotlinx.coroutines.delay +import kotlinx.coroutines.isActive +import kotlinx.coroutines.yield +import java.lang.Exception +import kotlin.coroutines.coroutineContext + +class PiHelperViewModel( + private val apiService: PiHoleApiService +) : ViewModel() { + val summary = MutableLiveData() + + suspend fun monitorSummary() { + while (coroutineContext.isActive) { + try { + loadSummary() + } catch (ignored: Exception) { + break + } + delay(1000) + } + } + + suspend fun loadSummary() { + summary.postValue(apiService.getSummary()) + } + + suspend fun enablePiHole() { + apiService.enable() + } + + suspend fun disablePiHole(duration: Long? = null) { + apiService.disable(duration) + } +} \ No newline at end of file diff --git a/app/src/main/java/com/wbrawner/pihelper/RetrieveApiKeyFragment.kt b/app/src/main/java/com/wbrawner/pihelper/RetrieveApiKeyFragment.kt new file mode 100644 index 0000000..a6d2c3b --- /dev/null +++ b/app/src/main/java/com/wbrawner/pihelper/RetrieveApiKeyFragment.kt @@ -0,0 +1,68 @@ +package com.wbrawner.pihelper + + +import android.os.Bundle +import android.util.Log +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.Fragment +import androidx.lifecycle.Observer +import androidx.navigation.fragment.findNavController +import androidx.transition.TransitionInflater +import kotlinx.android.synthetic.main.fragment_retrieve_api_key.* +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.launch +import org.koin.android.ext.android.inject +import kotlin.coroutines.CoroutineContext + +class RetrieveApiKeyFragment : Fragment(), CoroutineScope { + override val coroutineContext: CoroutineContext = Dispatchers.Main + private val viewModel: AddPiHelperViewModel by inject() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + sharedElementEnterTransition = TransitionInflater.from(context) + .inflateTransition(android.R.transition.move) + viewModel.authenticated.observe(this, Observer { + findNavController().navigate(R.id.action_retrieveApiKeyFragment_to_mainFragment) + }) + } + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? = inflater.inflate(R.layout.fragment_retrieve_api_key, container, false) + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + connectWithPasswordButton.setOnClickListener { + launch { + try { + viewModel.authenticateWithPassword(password.text.toString()) + } catch (ignored: Exception) { + Log.e("Pi-Helper", "Failed to authenticate with password", ignored) + password.error = "Failed to authenticate with given password. Please verify " + + "you've entered it correctly and try again." + } + } + } + + connectWithApiKeyButton.setOnClickListener { + launch { + try { + viewModel.authenticateWithApiKey(apiKey.text.toString()) + } catch (ignored: Exception) { + apiKey.error = "Failed to authenticate with given API key. Please verify " + + "you've entered it correctly and try again." + } + } + } + } + + override fun onDestroyView() { + coroutineContext[Job]?.cancel() + super.onDestroyView() + } +} diff --git a/app/src/main/java/com/wbrawner/pihelper/ScanNetworkFragment.kt b/app/src/main/java/com/wbrawner/pihelper/ScanNetworkFragment.kt new file mode 100644 index 0000000..e3b71b2 --- /dev/null +++ b/app/src/main/java/com/wbrawner/pihelper/ScanNetworkFragment.kt @@ -0,0 +1,165 @@ +package com.wbrawner.pihelper + + +import android.content.Context +import android.net.ConnectivityManager +import android.net.NetworkCapabilities +import android.os.Build +import android.os.Bundle +import android.util.Log +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.view.animation.Animation +import android.view.animation.LinearInterpolator +import android.view.animation.RotateAnimation +import androidx.appcompat.app.AlertDialog +import androidx.fragment.app.Fragment +import androidx.lifecycle.Observer +import androidx.navigation.fragment.FragmentNavigatorExtras +import androidx.navigation.fragment.findNavController +import androidx.transition.Transition +import androidx.transition.TransitionInflater +import kotlinx.android.synthetic.main.fragment_scan_network.* +import kotlinx.coroutines.* +import org.koin.android.ext.android.inject +import java.net.Inet4Address +import kotlin.coroutines.CoroutineContext + +class ScanNetworkFragment : Fragment(), CoroutineScope { + + override val coroutineContext: CoroutineContext = Dispatchers.Main + private val viewModel: AddPiHelperViewModel by inject() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + sharedElementEnterTransition = TransitionInflater.from(context) + .inflateTransition(android.R.transition.move) + .addListener(object : Transition.TransitionListener { + override fun onTransitionEnd(transition: Transition) { + animatePiHelperLogo() + } + + override fun onTransitionResume(transition: Transition) { + } + + override fun onTransitionPause(transition: Transition) { + } + + override fun onTransitionCancel(transition: Transition) { + } + + override fun onTransitionStart(transition: Transition) { + } + }) + } + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View? = inflater.inflate(R.layout.fragment_scan_network, container, false) + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + viewModel.scanningIp.observe(this, Observer { + ipAddress?.text = it + }) + viewModel.piHoleIpAddress.observe(this, Observer { ipAddress -> + if (ipAddress == null) { + AlertDialog.Builder(view.context) + .setTitle(R.string.scan_failed_title) + .setMessage(R.string.scan_failed) + .setPositiveButton(android.R.string.ok) { _, _ -> + findNavController().navigateUp() + } + .show() + return@Observer + } + piHelperLogo?.animation?.let { + it.setAnimationListener(object : Animation.AnimationListener { + override fun onAnimationRepeat(animation: Animation?) { + } + + override fun onAnimationEnd(animation: Animation?) { + navigateToApiKeyScreen() + } + + override fun onAnimationStart(animation: Animation?) { + } + }) + it.repeatCount = 0 + } ?: navigateToApiKeyScreen() + }) + launch(Dispatchers.IO) { + if (BuildConfig.DEBUG && Build.MODEL == "Android SDK built for x86") { + // For emulators, just begin scanning the host machine directly + viewModel.beginScanning("10.0.2.2") + return@launch + } + (view.context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager)?.let { connectivityManager -> + connectivityManager.allNetworks + .filter { + connectivityManager.getNetworkCapabilities(it) + ?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) + ?: false + } + .forEach { network -> + connectivityManager.getLinkProperties(network) + ?.linkAddresses + ?.filter { !it.address.isLoopbackAddress && it.address is Inet4Address } + ?.forEach { address -> + Log.d( + "Pi-Helper", + "Found link address: ${address.address.hostName}" + ) + viewModel.beginScanning(address.address.hostAddress) + } + } + } + } + launch { + delay(500) + if (piHelperLogo?.animation == null) { + animatePiHelperLogo() + } + } + } + + private fun navigateToApiKeyScreen() { + val extras = FragmentNavigatorExtras( + piHelperLogo to "piHelperLogo" + ) + + findNavController().navigate( + R.id.action_scanNetworkFragment_to_retrieveApiKeyFragment, + null, + null, + extras + ) + } + + override fun onDestroyView() { + piHelperLogo.clearAnimation() + coroutineContext[Job]?.cancel() + super.onDestroyView() + } + + private fun animatePiHelperLogo() { + piHelperLogo?.startAnimation( + RotateAnimation( + 0f, + 360f, + Animation.RELATIVE_TO_SELF, + 0.5f, + Animation.RELATIVE_TO_SELF, + 0.5f + ).apply { + duration = resources.getInteger(android.R.integer.config_longAnimTime).toLong() * 2 + repeatMode = Animation.RESTART + repeatCount = Animation.INFINITE + interpolator = LinearInterpolator() + fillAfter = true + } + ) + } +} diff --git a/app/src/main/res/drawable-anydpi-v24/ic_notification.xml b/app/src/main/res/drawable-anydpi-v24/ic_notification.xml new file mode 100644 index 0000000..387fdb5 --- /dev/null +++ b/app/src/main/res/drawable-anydpi-v24/ic_notification.xml @@ -0,0 +1,19 @@ + + + + + diff --git a/app/src/main/res/drawable-hdpi/ic_notification.png b/app/src/main/res/drawable-hdpi/ic_notification.png new file mode 100644 index 0000000..d7b4a7a Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_notification.png differ diff --git a/app/src/main/res/drawable-mdpi/ic_notification.png b/app/src/main/res/drawable-mdpi/ic_notification.png new file mode 100644 index 0000000..e6c7273 Binary files /dev/null and b/app/src/main/res/drawable-mdpi/ic_notification.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_notification.png b/app/src/main/res/drawable-xhdpi/ic_notification.png new file mode 100644 index 0000000..d16b224 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_notification.png differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_notification.png b/app/src/main/res/drawable-xxhdpi/ic_notification.png new file mode 100644 index 0000000..d722b14 Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/ic_notification.png differ diff --git a/app/src/main/res/drawable/background_splash.xml b/app/src/main/res/drawable/background_splash.xml new file mode 100644 index 0000000..8c88d63 --- /dev/null +++ b/app/src/main/res/drawable/background_splash.xml @@ -0,0 +1,12 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/horizontal_rule.xml b/app/src/main/res/drawable/horizontal_rule.xml new file mode 100644 index 0000000..7f702b0 --- /dev/null +++ b/app/src/main/res/drawable/horizontal_rule.xml @@ -0,0 +1,11 @@ + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/ic_app_logo.xml b/app/src/main/res/drawable/ic_app_logo.xml new file mode 100644 index 0000000..4152a11 --- /dev/null +++ b/app/src/main/res/drawable/ic_app_logo.xml @@ -0,0 +1,18 @@ + + + + + diff --git a/app/src/main/res/drawable/ic_launcher_background.xml b/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..b0f73c8 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/ic_launcher_foreground.xml b/app/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 0000000..958ce44 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,18 @@ + + + + + diff --git a/app/src/main/res/drawable/ic_pause.xml b/app/src/main/res/drawable/ic_pause.xml new file mode 100644 index 0000000..8d33792 --- /dev/null +++ b/app/src/main/res/drawable/ic_pause.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_play_arrow.xml b/app/src/main/res/drawable/ic_play_arrow.xml new file mode 100644 index 0000000..13af6d8 --- /dev/null +++ b/app/src/main/res/drawable/ic_play_arrow.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_settings.xml b/app/src/main/res/drawable/ic_settings.xml new file mode 100644 index 0000000..f673399 --- /dev/null +++ b/app/src/main/res/drawable/ic_settings.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_shortcut_enable.xml b/app/src/main/res/drawable/ic_shortcut_enable.xml new file mode 100644 index 0000000..8ccd9f2 --- /dev/null +++ b/app/src/main/res/drawable/ic_shortcut_enable.xml @@ -0,0 +1,16 @@ + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/ic_shortcut_pause.xml b/app/src/main/res/drawable/ic_shortcut_pause.xml new file mode 100644 index 0000000..3b52750 --- /dev/null +++ b/app/src/main/res/drawable/ic_shortcut_pause.xml @@ -0,0 +1,16 @@ + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..eba10ca --- /dev/null +++ b/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,17 @@ + + + + + diff --git a/app/src/main/res/layout/dialog_disable_custom_time.xml b/app/src/main/res/layout/dialog_disable_custom_time.xml new file mode 100644 index 0000000..240d4a5 --- /dev/null +++ b/app/src/main/res/layout/dialog_disable_custom_time.xml @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/fragment_add_pi_hole.xml b/app/src/main/res/layout/fragment_add_pi_hole.xml new file mode 100644 index 0000000..731f381 --- /dev/null +++ b/app/src/main/res/layout/fragment_add_pi_hole.xml @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/fragment_info.xml b/app/src/main/res/layout/fragment_info.xml new file mode 100644 index 0000000..7f7bbb9 --- /dev/null +++ b/app/src/main/res/layout/fragment_info.xml @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/fragment_main.xml b/app/src/main/res/layout/fragment_main.xml new file mode 100644 index 0000000..897e9c7 --- /dev/null +++ b/app/src/main/res/layout/fragment_main.xml @@ -0,0 +1,95 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/fragment_retrieve_api_key.xml b/app/src/main/res/layout/fragment_retrieve_api_key.xml new file mode 100644 index 0000000..5a496db --- /dev/null +++ b/app/src/main/res/layout/fragment_retrieve_api_key.xml @@ -0,0 +1,82 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/fragment_scan_network.xml b/app/src/main/res/layout/fragment_scan_network.xml new file mode 100644 index 0000000..408f2cb --- /dev/null +++ b/app/src/main/res/layout/fragment_scan_network.xml @@ -0,0 +1,35 @@ + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/or_divider.xml b/app/src/main/res/layout/or_divider.xml new file mode 100644 index 0000000..3c066f7 --- /dev/null +++ b/app/src/main/res/layout/or_divider.xml @@ -0,0 +1,34 @@ + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/menu/main.xml b/app/src/main/res/menu/main.xml new file mode 100644 index 0000000..9cc65f6 --- /dev/null +++ b/app/src/main/res/menu/main.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..bbd3e02 --- /dev/null +++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..bbd3e02 --- /dev/null +++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher.png b/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..2f5ce02 Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_round.png b/app/src/main/res/mipmap-hdpi/ic_launcher_round.png new file mode 100644 index 0000000..ae9c128 Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher.png b/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..5b4f5f3 Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_round.png b/app/src/main/res/mipmap-mdpi/ic_launcher_round.png new file mode 100644 index 0000000..758f3c6 Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..f2b86ce Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png new file mode 100644 index 0000000..97a8a9d Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..883fcea Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png new file mode 100644 index 0000000..44fcbc2 Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..95f8904 Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png new file mode 100644 index 0000000..00749a4 Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/navigation/nav_graph.xml b/app/src/main/res/navigation/nav_graph.xml new file mode 100644 index 0000000..387a931 --- /dev/null +++ b/app/src/main/res/navigation/nav_graph.xml @@ -0,0 +1,77 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/values-night/colors.xml b/app/src/main/res/values-night/colors.xml new file mode 100644 index 0000000..24d1d8d --- /dev/null +++ b/app/src/main/res/values-night/colors.xml @@ -0,0 +1,7 @@ + + + #333333 + #f1f1f1 + @color/colorGreenLight + @color/colorRedLight + \ No newline at end of file diff --git a/app/src/main/res/values-night/styles.xml b/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..c754cb1 --- /dev/null +++ b/app/src/main/res/values-night/styles.xml @@ -0,0 +1,13 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..22e9af2 --- /dev/null +++ b/app/src/main/res/values/colors.xml @@ -0,0 +1,17 @@ + + + @color/colorRedLight + @color/colorRedDark + @color/colorRedLight + #f60d1a + #96060c + #30d158 + #34c759 + #000000 + #ffffff + @color/colorGreenDark + @color/colorRedDark + @color/colorWhite + #00000000 + #666666 + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..61c2747 --- /dev/null +++ b/app/src/main/res/values/strings.xml @@ -0,0 +1,33 @@ + + Pi-Helper + Scanning IP Address: + Pi-Helper Logo + Status: %1$s + Enable + Disable + Disable for 10 seconds + Disable for 30 seconds + Disable for 5 minutes + Disable for custom time + Disable Permanently + Disabled + Enabled + Please ensure you are connected to the same Wi-Fi network that the Pi-Hole is running on and try again, or enter the Pi-Hole\'s IP address manually. + Pi-Helper failed to find your Pi-Hole + Please ensure you are connected to the same Wi-Fi network that the Pi-Hole is running on, and that you\'re using the correct IP address and try again. + Pi-Helper failed to connect to your Pi-Hole + Please configure Pi-Helper before using shortcuts + or + Sorry, but no + Yes, I\'ll help! + Would you like to help me make Pi-Helper better by automatically sending crash reports and usage details via Firebase? These are immensely helpful in tracking down issues that may arise or optimizing the app for only the features that are used. You can change your mind at any time from the settings. + Help make Pi-Helper better + Settings + Forget Pi-hole + William Brawner. You can find the source code or report issues on the GitHub page for the project.]]> + Are you sure you want to forget your Pi-hole? + This cannot be undone. + Pi-Helper Crashed! + Would you please consider sending the crash report to me? + Crash Reports + diff --git a/app/src/main/res/values/styles.xml b/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..9b4ff21 --- /dev/null +++ b/app/src/main/res/values/styles.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + diff --git a/app/src/main/res/xml/backup_descriptor.xml b/app/src/main/res/xml/backup_descriptor.xml new file mode 100644 index 0000000..6fd6103 --- /dev/null +++ b/app/src/main/res/xml/backup_descriptor.xml @@ -0,0 +1,4 @@ + + + + diff --git a/app/src/main/res/xml/shortcuts.xml b/app/src/main/res/xml/shortcuts.xml new file mode 100644 index 0000000..a8ff49e --- /dev/null +++ b/app/src/main/res/xml/shortcuts.xml @@ -0,0 +1,62 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/test/java/com/wbrawner/pihelper/ExampleUnitTest.kt b/app/src/test/java/com/wbrawner/pihelper/ExampleUnitTest.kt new file mode 100644 index 0000000..bc95806 --- /dev/null +++ b/app/src/test/java/com/wbrawner/pihelper/ExampleUnitTest.kt @@ -0,0 +1,17 @@ +package com.wbrawner.pihelper + +import org.junit.Test + +import org.junit.Assert.* + +/** + * Example local unit test, which will execute on the development machine (host). + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +class ExampleUnitTest { + @Test + fun addition_isCorrect() { + assertEquals(4, 2 + 2) + } +} diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..4bd2e0a --- /dev/null +++ b/build.gradle @@ -0,0 +1,28 @@ +buildscript { + ext.kotlin_version = '1.3.61' + ext.coroutines_version = '1.3.2' + ext.koin_version = '2.0.1' + ext.okhttp_version = '4.2.2' + repositories { + google() + jcenter() + maven { + url 'https://maven.fabric.io/public' + } + } + dependencies { + classpath 'com.android.tools.build:gradle:3.5.2' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} + +allprojects { + repositories { + google() + jcenter() + } +} + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..23339e0 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,21 @@ +# Project-wide Gradle settings. +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx1536m +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true +# AndroidX package structure to make it clearer which packages are bundled with the +# Android operating system, and which are packaged with your app's APK +# https://developer.android.com/topic/libraries/support-library/androidx-rn +android.useAndroidX=true +# Automatically convert third-party libraries to use AndroidX +android.enableJetifier=true +# Kotlin code style for this project: "official" or "obsolete": +kotlin.code.style=official diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..f6b961f Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..52a0619 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Sat Nov 16 20:08:04 MST 2019 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..cccdd3d --- /dev/null +++ b/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..f955316 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/piholeclient/.gitignore b/piholeclient/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/piholeclient/.gitignore @@ -0,0 +1 @@ +/build diff --git a/piholeclient/build.gradle b/piholeclient/build.gradle new file mode 100644 index 0000000..53b7c9c --- /dev/null +++ b/piholeclient/build.gradle @@ -0,0 +1,45 @@ +apply plugin: 'com.android.library' +apply plugin: 'kotlin-android' +apply plugin: 'kotlin-android-extensions' +apply plugin: 'kotlin-kapt' + +android { + compileSdkVersion 29 + defaultConfig { + minSdkVersion 23 + targetSdkVersion 29 + versionCode 1 + versionName "1.0" + + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + consumerProguardFiles 'consumer-rules.pro' + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } +} + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar']) + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version" + implementation "org.koin:koin-core:$koin_version" + implementation "com.squareup.okhttp3:okhttp:${okhttp_version}" + implementation "com.squareup.okhttp3:logging-interceptor:${okhttp_version}" + implementation 'androidx.appcompat:appcompat:1.1.0' + implementation 'androidx.core:core-ktx:1.1.0' + implementation "com.squareup.moshi:moshi:1.9.2" + kapt "com.squareup.moshi:moshi-kotlin-codegen:1.9.2" + testImplementation 'junit:junit:4.12' + androidTestImplementation 'androidx.test.ext:junit:1.1.1' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' +} diff --git a/piholeclient/consumer-rules.pro b/piholeclient/consumer-rules.pro new file mode 100644 index 0000000..b10b8cf --- /dev/null +++ b/piholeclient/consumer-rules.pro @@ -0,0 +1,67 @@ +# JSR 305 annotations are for embedding nullability information. +-dontwarn javax.annotation.** + +-keepclasseswithmembers class * { + @com.squareup.moshi.* ; +} + +-keep @com.squareup.moshi.JsonQualifier interface * + +# Enum field names are used by the integrated EnumJsonAdapter. +# values() is synthesized by the Kotlin compiler and is used by EnumJsonAdapter indirectly +# Annotate enums with @JsonClass(generateAdapter = false) to use them with Moshi. +-keepclassmembers @com.squareup.moshi.JsonClass class * extends java.lang.Enum { + ; + **[] values(); +} + +# The name of @JsonClass types is used to look up the generated adapter. +-keepnames @com.squareup.moshi.JsonClass class * + +# Retain generated target class's synthetic defaults constructor and keep DefaultConstructorMarker's +# name. We will look this up reflectively to invoke the type's constructor. +# +# We can't _just_ keep the defaults constructor because Proguard/R8's spec doesn't allow wildcard +# matching preceding parameters. +-keepnames class kotlin.jvm.internal.DefaultConstructorMarker +-keepclassmembers @com.squareup.moshi.JsonClass @kotlin.Metadata class * { + synthetic (...); +} + +# Retain generated JsonAdapters if annotated type is retained. +-if @com.squareup.moshi.JsonClass class * +-keep class <1>JsonAdapter { + (...); + ; +} +-if @com.squareup.moshi.JsonClass class **$* +-keep class <1>_<2>JsonAdapter { + (...); + ; +} +-if @com.squareup.moshi.JsonClass class **$*$* +-keep class <1>_<2>_<3>JsonAdapter { + (...); + ; +} +-if @com.squareup.moshi.JsonClass class **$*$*$* +-keep class <1>_<2>_<3>_<4>JsonAdapter { + (...); + ; +} +-if @com.squareup.moshi.JsonClass class **$*$*$*$* +-keep class <1>_<2>_<3>_<4>_<5>JsonAdapter { + (...); + ; +} +-if @com.squareup.moshi.JsonClass class **$*$*$*$*$* +-keep class <1>_<2>_<3>_<4>_<5>_<6>JsonAdapter { + (...); + ; +} + +-keep class kotlin.reflect.jvm.internal.impl.builtins.BuiltInsLoaderImpl + +-keepclassmembers class kotlin.Metadata { + public ; +} diff --git a/piholeclient/proguard-rules.pro b/piholeclient/proguard-rules.pro new file mode 100644 index 0000000..f1b4245 --- /dev/null +++ b/piholeclient/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/piholeclient/src/androidTest/java/com/wbrawner/piholeclient/ExampleInstrumentedTest.kt b/piholeclient/src/androidTest/java/com/wbrawner/piholeclient/ExampleInstrumentedTest.kt new file mode 100644 index 0000000..8ab2bd2 --- /dev/null +++ b/piholeclient/src/androidTest/java/com/wbrawner/piholeclient/ExampleInstrumentedTest.kt @@ -0,0 +1,24 @@ +package com.wbrawner.piholeclient + +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.ext.junit.runners.AndroidJUnit4 + +import org.junit.Test +import org.junit.runner.RunWith + +import org.junit.Assert.* + +/** + * Instrumented test, which will execute on an Android device. + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +@RunWith(AndroidJUnit4::class) +class ExampleInstrumentedTest { + @Test + fun useAppContext() { + // Context of the app under test. + val appContext = InstrumentationRegistry.getInstrumentation().targetContext + assertEquals("com.wbrawner.piholeclient.test", appContext.packageName) + } +} diff --git a/piholeclient/src/main/AndroidManifest.xml b/piholeclient/src/main/AndroidManifest.xml new file mode 100644 index 0000000..3dc5fd8 --- /dev/null +++ b/piholeclient/src/main/AndroidManifest.xml @@ -0,0 +1,5 @@ + + + + diff --git a/piholeclient/src/main/java/com/wbrawner/piholeclient/PiHoleApiService.kt b/piholeclient/src/main/java/com/wbrawner/piholeclient/PiHoleApiService.kt new file mode 100644 index 0000000..1d5027c --- /dev/null +++ b/piholeclient/src/main/java/com/wbrawner/piholeclient/PiHoleApiService.kt @@ -0,0 +1,174 @@ +package com.wbrawner.piholeclient + +import com.squareup.moshi.Moshi +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import okhttp3.HttpUrl +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.RequestBody.Companion.toRequestBody +import kotlin.reflect.KClass + +interface PiHoleApiService { + var baseUrl: String? + var apiKey: String? + + suspend fun login(password: String): String + + suspend fun getApiToken(): String + + suspend fun getSummary( + version: Boolean = false, + type: Boolean = false + ): Summary + + suspend fun getVersion(): VersionResponse + + suspend fun getTopItems(): TopItemsResponse + + suspend fun enable(): StatusResponse + + suspend fun disable(duration: Long? = null): StatusResponse + + /** + @Query("overTimeData10mins") overTimeData10mins: Boolean = true, + @Query("topItems") topItems: Int? = null, + @Query("topClients") topClients: Int? = null, + @Query("getForwardDestinations") getForwardDestinations: Boolean = true, + @Query("getQueryTypes") getQueryTypes: Boolean = true, + @Query("getAllQueries") getAllQueries: Boolean = true + + */ + +// suspend fun login(password: String): Response +// +// @GET("/admin/scripts/pi-hole/php/api_token.php") +// suspend fun apiKey(phpSession: String): Response +} + +const val BASE_PATH = "/admin/api.php" +const val INDEX_PATH = "/admin/index.php" +const val API_TOKEN_PATH = "/admin/scripts/pi-hole/php/api_token.php" + +class OkHttpPiHoleApiService( + private val okHttpClient: OkHttpClient, + private val moshi: Moshi +) : PiHoleApiService { + override var baseUrl: String? = null + @Synchronized + get + @Synchronized + set + override var apiKey: String? = null + @Synchronized + get + @Synchronized + set + + private val urlBuilder: HttpUrl.Builder + get() { + val host = baseUrl ?: throw IllegalStateException("No base URL defined") + return HttpUrl.Builder() + .scheme("http") + .host(host) + .addPathSegments(BASE_PATH) + } + + override suspend fun getSummary(version: Boolean, type: Boolean): Summary { + val url = urlBuilder + .addQueryParameter("summary", "") + if (version) { + url.addQueryParameter("version", "") + } + if (type) { + url.addQueryParameter("type", "") + } + val request = Request.Builder() + .get() + .url(url.build()) + return sendRequest(request.build(), Summary::class)!! + } + + override suspend fun getVersion(): VersionResponse { + val url = urlBuilder + .addQueryParameter("version", "") + val request = Request.Builder() + .get() + .url(url.build()) + return sendRequest(request.build(), VersionResponse::class)!! + } + + override suspend fun getTopItems(): TopItemsResponse { + val apiToken = this.apiKey ?: throw java.lang.IllegalStateException("No API Token provided") + val url = urlBuilder + .addQueryParameter("topItems", "25") + .addQueryParameter("auth", apiToken) + val request = Request.Builder() + .get() + .url(url.build()) + return sendRequest(request.build(), TopItemsResponse::class)!! + } + + override suspend fun login(password: String): String { + val url = urlBuilder + .encodedPath(INDEX_PATH) + .addQueryParameter("login", "") + val body = "pw=$password".toRequestBody("application/x-www-form-urlencoded".toMediaType()) + val request = Request.Builder() + .post(body) + .url(url.build()) + return sendRequest(request.build(), String::class)!! + } + + override suspend fun getApiToken(): String { + val url = urlBuilder + .encodedPath(API_TOKEN_PATH) + val request = Request.Builder() + .get() + .url(url.build()) + return sendRequest(request.build(), String::class)!! + } + + override suspend fun enable(): StatusResponse { + val apiToken = this.apiKey ?: throw java.lang.IllegalStateException("No API Token provided") + val url = urlBuilder + .addQueryParameter("enable", "") + .addQueryParameter("auth", apiToken) + val request = Request.Builder() + .get() + .url(url.build()) + return sendRequest(request.build(), StatusResponse::class)!! + } + + override suspend fun disable(duration: Long?): StatusResponse { + val apiToken = this.apiKey ?: throw java.lang.IllegalStateException("No API Token provided") + val url = urlBuilder + .addQueryParameter("disable", duration?.toString()?: "") + .addQueryParameter("auth", apiToken) + val request = Request.Builder() + .get() + .url(url.build()) + return sendRequest(request.build(), StatusResponse::class)!! + } + + private suspend fun sendRequest(request: Request, responseType: KClass?): T? { + return withContext(Dispatchers.IO) { + val response = okHttpClient.newCall(request).execute() + if (!response.isSuccessful) { + null + } else { + @Suppress("UNCHECKED_CAST") + when (responseType) { + null -> null + String::class -> response.body?.string() as T + else -> response.body?.let { + moshi + .adapter(responseType.javaObjectType) + .fromJson(it.source()) + } + } + } + } + } +} \ No newline at end of file diff --git a/piholeclient/src/main/java/com/wbrawner/piholeclient/PiHoleClientModule.kt b/piholeclient/src/main/java/com/wbrawner/piholeclient/PiHoleClientModule.kt new file mode 100644 index 0000000..832f7e3 --- /dev/null +++ b/piholeclient/src/main/java/com/wbrawner/piholeclient/PiHoleClientModule.kt @@ -0,0 +1,62 @@ +package com.wbrawner.piholeclient + +import com.squareup.moshi.JsonReader +import com.squareup.moshi.Moshi +import okhttp3.Cookie +import okhttp3.CookieJar +import okhttp3.HttpUrl +import okhttp3.OkHttpClient +import okhttp3.logging.HttpLoggingInterceptor +import okio.Buffer +import org.koin.dsl.module +import java.util.concurrent.TimeUnit + +const val NAME_BASE_URL = "baseUrl" + +val piHoleClientModule = module { + single { + Moshi.Builder().build() + } + + single { + val client = OkHttpClient.Builder() + .connectTimeout(500, TimeUnit.MILLISECONDS) + .cookieJar(object : CookieJar { + val cookies = mutableMapOf>() + override fun loadForRequest(url: HttpUrl): List = cookies[url.host] + ?: emptyList() + + override fun saveFromResponse(url: HttpUrl, cookies: List) { + this.cookies[url.host] = cookies + } + }) + if (BuildConfig.DEBUG) { + client.addInterceptor(HttpLoggingInterceptor( + object : HttpLoggingInterceptor.Logger { + val moshi = Moshi.Builder() + .build() + .adapter(Any::class.java) + .indent(" ") + + override fun log(message: String) { + val prettyMessage = try { + val json = JsonReader.of(Buffer().writeUtf8(message)) + moshi.toJson(json.readJsonValue()) + } catch (ignored: Exception) { + message + } + HttpLoggingInterceptor.Logger.DEFAULT.log(prettyMessage) + } + }) + .apply { + level = HttpLoggingInterceptor.Level.BODY + } + ) + } + client.build() + } + + single { + OkHttpPiHoleApiService(get(), get()) + } +} \ No newline at end of file diff --git a/piholeclient/src/main/java/com/wbrawner/piholeclient/Responses.kt b/piholeclient/src/main/java/com/wbrawner/piholeclient/Responses.kt new file mode 100644 index 0000000..8119f98 --- /dev/null +++ b/piholeclient/src/main/java/com/wbrawner/piholeclient/Responses.kt @@ -0,0 +1,79 @@ +package com.wbrawner.piholeclient + +import com.squareup.moshi.Json +import com.squareup.moshi.JsonClass + +@JsonClass(generateAdapter = true) +data class Summary( + @Json(name = "domains_being_blocked") + val domainsBeingBlocked: String, + @Json(name = "dns_queries_today") + val dnsQueriesToday: String, + @Json(name = "ads_blocked_today") + val adsBlockedToday: String, + @Json(name = "ads_percentage_today") + val adsPercentageToday: String, + @Json(name = "unique_domains") + val uniqueDomains: String, + @Json(name = "queries_forwarded") + val queriesForwarded: String, + @Json(name = "clients_ever_seen") + val clientsEverSeen: String, + @Json(name = "unique_clients") + val uniqueClients: String, + @Json(name = "dns_queries_all_types") + val dnsQueriesAllTypes: String, + @Json(name = "queries_cached") + val queriesCached: String, + @Json(name = "no_data_replies") + val noDataReplies: String?, + @Json(name = "nx_domain_replies") + val nxDomainReplies: String?, + @Json(name = "cname_replies") + val cnameReplies: String?, + @Json(name = "in_replies") + val ipReplies: String?, + @Json(name = "privacy_level") + val privacyLevel: String, + val status: Status, + @Json(name = "gravity_last_updated") + val gravity: Gravity?, + val type: String?, + val version: Int? +) + +enum class Status { + @Json(name = "enabled") + ENABLED, + @Json(name = "disabled") + DISABLED +} + +@JsonClass(generateAdapter = true) +data class Gravity( + @Json(name = "file_exists") + val fileExists: Boolean, + val absolute: Int, + val relative: Relative +) + +@JsonClass(generateAdapter = true) +data class Relative( + val days: String, + val hours: String, + val minutes: String +) + +@JsonClass(generateAdapter = true) +data class VersionResponse(val version: Int) + +@JsonClass(generateAdapter = true) +data class TopItemsResponse( + @Json(name = "top_queries") val topQueries: List, + @Json(name = "top_ads") val topAds: List +) + +@JsonClass(generateAdapter = true) +data class StatusResponse( + val status: Status +) diff --git a/piholeclient/src/main/res/values/strings.xml b/piholeclient/src/main/res/values/strings.xml new file mode 100644 index 0000000..9c995ef --- /dev/null +++ b/piholeclient/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + PiHoleClient + diff --git a/piholeclient/src/test/java/com/wbrawner/piholeclient/ExampleUnitTest.kt b/piholeclient/src/test/java/com/wbrawner/piholeclient/ExampleUnitTest.kt new file mode 100644 index 0000000..0f592fe --- /dev/null +++ b/piholeclient/src/test/java/com/wbrawner/piholeclient/ExampleUnitTest.kt @@ -0,0 +1,17 @@ +package com.wbrawner.piholeclient + +import org.junit.Test + +import org.junit.Assert.* + +/** + * Example local unit test, which will execute on the development machine (host). + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +class ExampleUnitTest { + @Test + fun addition_isCorrect() { + assertEquals(4, 2 + 2) + } +} diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..1728ee1 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,2 @@ +include ':app', ':piholeclient' +rootProject.name='Pi-Helper'