Implement working Pi-hole connections and management

Signed-off-by: William Brawner <me@wbrawner.com>
This commit is contained in:
William Brawner 2020-01-01 14:21:33 -06:00
commit 1347b9ea10
89 changed files with 3007 additions and 0 deletions

14
.gitignore vendored Normal file
View file

@ -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

1
.idea/.name Normal file
View file

@ -0,0 +1 @@
Pi-Helper

View file

@ -0,0 +1,126 @@
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173">
<AndroidXmlCodeStyleSettings>
<option name="ARRANGEMENT_SETTINGS_MIGRATED_TO_191" value="true" />
</AndroidXmlCodeStyleSettings>
<JetCodeStyleSettings>
<option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" />
</JetCodeStyleSettings>
<codeStyleSettings language="XML">
<indentOptions>
<option name="CONTINUATION_INDENT_SIZE" value="4" />
</indentOptions>
<arrangement>
<rules>
<section>
<rule>
<match>
<AND>
<NAME>xmlns:android</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>xmlns:.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
<order>BY_NAME</order>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*:id</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*:name</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>name</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>style</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
<order>BY_NAME</order>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
</AND>
</match>
<order>ANDROID_ATTRIBUTE_ORDER</order>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>.*</XML_NAMESPACE>
</AND>
</match>
<order>BY_NAME</order>
</rule>
</section>
</rules>
</arrangement>
</codeStyleSettings>
<codeStyleSettings language="kotlin">
<option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" />
<option name="WRAP_ON_TYPING" value="1" />
</codeStyleSettings>
</code_scheme>
</component>

View file

@ -0,0 +1,5 @@
<component name="ProjectCodeStyleConfiguration">
<state>
<option name="USE_PER_PROJECT_SETTINGS" value="true" />
</state>
</component>

20
.idea/gradle.xml Normal file
View file

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="distributionType" value="DEFAULT_WRAPPED" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
<option value="$PROJECT_DIR$/piholeclient" />
</set>
</option>
<option name="resolveModulePerSourceSet" value="false" />
<option name="testRunner" value="PLATFORM" />
</GradleProjectSettings>
</option>
</component>
</project>

14
.idea/misc.xml Normal file
View file

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CMakeSettings">
<configurations>
<configuration PROFILE_NAME="Debug" CONFIG_NAME="Debug" />
</configurations>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">
<option name="id" value="Android" />
</component>
</project>

View file

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RunConfigurationProducerService">
<option name="ignoredProducers">
<set>
<option value="org.jetbrains.plugins.gradle.execution.test.runner.AllInPackageGradleConfigurationProducer" />
<option value="org.jetbrains.plugins.gradle.execution.test.runner.TestClassGradleConfigurationProducer" />
<option value="org.jetbrains.plugins.gradle.execution.test.runner.TestMethodGradleConfigurationProducer" />
</set>
</option>
</component>
</project>

6
.idea/vcs.xml Normal file
View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

1
app/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
/build

53
app/build.gradle Normal file
View file

@ -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"
}

48
app/google-services.json Normal file
View file

@ -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"
}

21
app/proguard-rules.pro vendored Normal file
View file

@ -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

View file

@ -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)
}
}

View file

@ -0,0 +1,60 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.wbrawner.pihelper">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:name=".PiHelperApplication"
android:allowBackup="true"
android:fullBackupContent="@xml/backup_descriptor"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="pihelper.app"
android:scheme="http" />
<data
android:host="pihelper.app"
android:scheme="https" />
<data
android:host="pihelper.wbrawner.com"
android:scheme="http" />
<data
android:host="pihelper.wbrawner.com"
android:scheme="https" />
<data
android:host="pihelper.brawner.dev"
android:scheme="http" />
<data
android:host="pihelper.brawner.dev"
android:scheme="https" />
</intent-filter>
<meta-data
android:name="android.app.shortcuts"
android:resource="@xml/shortcuts" />
</activity>
<meta-data
android:name="firebase_crashlytics_collection_enabled"
android:value="false" />
<meta-data
android:name="firebase_analytics_collection_enabled"
android:value="false" />
</application>
</manifest>

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

View file

@ -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<String?>()
val scanningIp = MutableLiveData<String?>()
val authenticated = MutableLiveData<Boolean>()
suspend fun beginScanning(deviceIpAddress: String) {
val addressParts = deviceIpAddress.split(".").toMutableList()
var chunks = 1
val ipAddresses = mutableListOf<String>()
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<String>) {
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
}
}

View file

@ -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()
}
}

View file

@ -0,0 +1,3 @@
package com.wbrawner.pihelper
fun <T, R> R.transform(block: (R) -> T): T = block(this)

View file

@ -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)
}
}

View file

@ -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"
}
}

View file

@ -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<EditText>(R.id.time)
.text
.toString()
.toLong()
val checkedId =
dialogView.findViewById<RadioGroup>(R.id.timeUnit)
.checkedRadioButtonId
val computedTime = if (checkedId == R.id.seconds) rawTime
else rawTime * 60
viewModel.disablePiHole(computedTime)
dismiss()
} catch (e: Exception) {
dialogView.findViewById<EditText>(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"
}
}

View file

@ -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)
}
}

View file

@ -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<EncryptedSharedPreferences>().getString(KEY_BASE_URL, "")
}
}

View file

@ -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<Summary>()
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)
}
}

View file

@ -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()
}
}

View file

@ -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
}
)
}
}

View file

@ -0,0 +1,19 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="196.32849"
android:viewportHeight="196.32849"
android:tint="#FFFFFF">
<group android:translateX="-37.302414"
android:translateY="-37.302414">
<path
android:pathData="M135.467,53.19C94.537,53.19 61.19,86.537 61.19,127.467C61.19,139.777 64.21,151.399 69.543,161.636A33.872,33.872 135,0 0,61.191 183.871A33.872,33.872 0,0 0,95.063 217.743A33.872,33.872 0,0 0,124.303 200.904A33.872,33.872 0,0 0,124.304 200.903C127.946,201.455 131.673,201.743 135.467,201.743C176.397,201.743 209.743,168.397 209.743,127.467C209.743,86.537 176.397,53.19 135.467,53.19zM135.467,68.748C167.99,68.748 194.192,94.944 194.192,127.467C194.192,159.99 167.99,186.192 135.467,186.192C133.225,186.192 131.014,186.063 128.839,185.82A33.872,33.872 0,0 0,128.839 185.813A33.872,33.872 0,0 0,128.936 183.871A33.872,33.872 0,0 0,95.063 149.999A33.872,33.872 0,0 0,82.318 152.512C82.318,152.511 82.318,152.511 82.318,152.511A33.872,33.872 135,0 0,82.312 152.513C78.744,144.922 76.748,136.436 76.748,127.467C76.748,94.944 102.944,68.748 135.467,68.748z"
android:strokeAlpha="1"
android:strokeLineJoin="miter"
android:strokeWidth="6.53636312"
android:fillColor="#1a1a1a"
android:strokeColor="#00000000"
android:fillAlpha="1"
android:strokeLineCap="butt"/>
</group>
</vector>

Binary file not shown.

After

Width:  |  Height:  |  Size: 610 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 403 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 791 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

View file

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:bottom="0dp"
android:drawable="@color/colorSurface"
android:end="0dp"
android:start="0dp"
android:top="0dp" />
<item
android:gravity="center"
android:drawable="@drawable/ic_launcher_foreground" />
</layer-list>

View file

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:width="500dp"
android:height="1dp"
android:gravity="center">
<color android:color="@color/colorOnSurface" />
<shape android:shape="rectangle" />
</item>
</layer-list>

View file

@ -0,0 +1,18 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="404.37808"
android:viewportHeight="404.37808">
<group android:translateX="66.72238"
android:translateY="66.72238">
<path
android:pathData="m135.467,61.19c-40.93,0 -74.277,33.347 -74.277,74.277 0,12.31 3.02,23.932 8.352,34.169a33.872,33.872 0,0 0,-8.351 22.235,33.872 33.872,0 0,0 33.872,33.872 33.872,33.872 0,0 0,29.24 -16.839,33.872 33.872,0 0,0 0.001,-0.001c3.642,0.552 7.37,0.84 11.163,0.84 40.93,0 74.277,-33.346 74.277,-74.276 0,-40.93 -33.347,-74.277 -74.277,-74.277zM135.467,76.748c32.523,0 58.725,26.195 58.725,58.718 0,32.523 -26.202,58.725 -58.725,58.725 -2.242,0 -4.453,-0.129 -6.628,-0.372a33.872,33.872 0,0 0,0 -0.007,33.872 33.872,0 0,0 0.097,-1.943A33.872,33.872 0,0 0,95.063 157.999,33.872 33.872,0 0,0 82.318,160.512c-0,-0 -0,-0.001 -0.001,-0.001a33.872,33.872 0,0 0,-0.006 0.003c-3.568,-7.591 -5.564,-16.077 -5.564,-25.047 0,-32.523 26.195,-58.718 58.718,-58.718z"
android:strokeAlpha="1"
android:strokeLineJoin="miter"
android:strokeWidth="1.72941"
android:fillColor="@color/colorOnSurface"
android:strokeColor="#00000000"
android:fillAlpha="1"
android:strokeLineCap="butt"/>
</group>
</vector>

View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient android:endColor="@color/colorRedLight"
android:startColor="@color/colorRedDark"
android:angle="90 " />
</shape>

View file

@ -0,0 +1,18 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="404.37808"
android:viewportHeight="404.37808">
<group android:translateX="66.72238"
android:translateY="66.72238">
<path
android:pathData="m135.467,61.19c-40.93,0 -74.277,33.347 -74.277,74.277 0,12.31 3.02,23.932 8.352,34.169a33.872,33.872 0,0 0,-8.351 22.235,33.872 33.872,0 0,0 33.872,33.872 33.872,33.872 0,0 0,29.24 -16.839,33.872 33.872,0 0,0 0.001,-0.001c3.642,0.552 7.37,0.84 11.163,0.84 40.93,0 74.277,-33.346 74.277,-74.276 0,-40.93 -33.347,-74.277 -74.277,-74.277zM135.467,76.748c32.523,0 58.725,26.195 58.725,58.718 0,32.523 -26.202,58.725 -58.725,58.725 -2.242,0 -4.453,-0.129 -6.628,-0.372a33.872,33.872 0,0 0,0 -0.007,33.872 33.872,0 0,0 0.097,-1.943A33.872,33.872 0,0 0,95.063 157.999,33.872 33.872,0 0,0 82.318,160.512c-0,-0 -0,-0.001 -0.001,-0.001a33.872,33.872 0,0 0,-0.006 0.003c-3.568,-7.591 -5.564,-16.077 -5.564,-25.047 0,-32.523 26.195,-58.718 58.718,-58.718z"
android:strokeAlpha="1"
android:strokeLineJoin="miter"
android:strokeWidth="1.72941"
android:fillColor="@color/colorWhite"
android:strokeColor="#00000000"
android:fillAlpha="1"
android:strokeLineCap="butt"/>
</group>
</vector>

View file

@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="@color/colorRedDark"
android:pathData="M6,19h4L10,5L6,5v14zM14,5v14h4L18,5h-4z"/>
</vector>

View file

@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="@color/colorGreenDark"
android:pathData="M8,5v14l11,-7z"/>
</vector>

View file

@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="@color/colorOnSurface"
android:pathData="M19.1,12.9a2.8,2.8 0,0 0,0.1 -0.9,2.8 2.8,0 0,0 -0.1,-0.9l2.1,-1.6a0.7,0.7 0,0 0,0.1 -0.6L19.4,5.5a0.7,0.7 0,0 0,-0.6 -0.2l-2.4,1a6.5,6.5 0,0 0,-1.6 -0.9l-0.4,-2.6a0.5,0.5 0,0 0,-0.5 -0.4H10.1a0.5,0.5 0,0 0,-0.5 0.4L9.3,5.4a5.6,5.6 0,0 0,-1.7 0.9l-2.4,-1a0.4,0.4 0,0 0,-0.5 0.2l-2,3.4c-0.1,0.2 0,0.4 0.2,0.6l2,1.6a2.8,2.8 0,0 0,-0.1 0.9,2.8 2.8,0 0,0 0.1,0.9L2.8,14.5a0.7,0.7 0,0 0,-0.1 0.6l1.9,3.4a0.7,0.7 0,0 0,0.6 0.2l2.4,-1a6.5,6.5 0,0 0,1.6 0.9l0.4,2.6a0.5,0.5 0,0 0,0.5 0.4h3.8a0.5,0.5 0,0 0,0.5 -0.4l0.3,-2.6a5.6,5.6 0,0 0,1.7 -0.9l2.4,1a0.4,0.4 0,0 0,0.5 -0.2l2,-3.4c0.1,-0.2 0,-0.4 -0.2,-0.6ZM12,15.6A3.6,3.6 0,1 1,15.6 12,3.6 3.6,0 0,1 12,15.6Z"/>
</vector>

View file

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:width="48dp"
android:height="48dp">
<shape
android:shape="oval"
android:tint="@color/colorWhite" />
</item>
<item
android:bottom="0dp"
android:drawable="@drawable/ic_play_arrow"
android:end="0dp"
android:start="0dp"
android:top="0dp" />
</layer-list>

View file

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:width="48dp"
android:height="48dp">
<shape
android:shape="oval"
android:tint="@color/colorWhite" />
</item>
<item
android:bottom="0dp"
android:drawable="@drawable/ic_pause"
android:end="0dp"
android:start="0dp"
android:top="0dp" />
</layer-list>

View file

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:background="@color/colorSurface">
<fragment
android:id="@+id/content_main"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_graph" />
</FrameLayout>

View file

@ -0,0 +1,44 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingStart="16dp"
android:paddingEnd="16dp"
tools:background="@color/colorSurface">
<com.google.android.material.textfield.TextInputLayout
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Time to disable">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number|numberSigned" />
</com.google.android.material.textfield.TextInputLayout>
<RadioGroup
android:id="@+id/timeUnit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="horizontal">
<RadioButton
android:id="@+id/seconds"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Secs" />
<RadioButton
android:id="@+id/minutes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Mins" />
</RadioGroup>
</LinearLayout>

View file

@ -0,0 +1,67 @@
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:animateLayoutChanges="true"
tools:background="@color/colorSurface"
tools:context=".AddPiHoleFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical"
android:padding="16dp">
<ImageView
android:id="@+id/piHelperLogo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="@drawable/ic_app_logo"
android:tint="@color/colorOnSurface"
android:transitionName="piHelperLogo" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="If you're not sure what the IP address for your Pi-Hole is, Pi-Helper can attempt to find it for you by scanning your network."
android:textAlignment="center" />
<com.google.android.material.button.MaterialButton
android:id="@+id/scanNetworkButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Scan Network" />
<include layout="@layout/or_divider" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="If you already know the IP address of your Pi-Hole, you can also enter it below:"
android:textAlignment="center" />
<com.google.android.material.textfield.TextInputLayout
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Pi-Hole IP Address">
<!-- TODO: Figure out how to get this to work for inputting an IP address -->
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/ipAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.button.MaterialButton
android:id="@+id/connectButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Connect to Pi-Hole" />
</LinearLayout>
</ScrollView>

View file

@ -0,0 +1,53 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:background="@color/colorSurface"
tools:context=".InfoFragment">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@+id/toolbar">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical"
android:padding="16dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:contentDescription="@string/app_name"
android:src="@drawable/ic_app_logo" />
<TextView
android:id="@+id/infoContent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/content_info"
android:textAlignment="center" />
<com.google.android.material.button.MaterialButton
android:id="@+id/forgetPiHoleButton"
style="@style/Widget.MaterialComponents.Button.TextButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/action_forget_pihole" />
</LinearLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>

View file

@ -0,0 +1,95 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:animateLayoutChanges="true"
tools:background="@color/colorSurface">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent" />
<ScrollView
android:id="@+id/statusContent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@+id/toolbar">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainFragment">
<TextView
android:id="@+id/status"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp"
android:textAlignment="center"
tools:text="Enabled"
tools:textColor="@color/colorGreenDark" />
<com.google.android.material.button.MaterialButton
android:id="@+id/enableButton"
style="@style/AppTheme.Button.Green"
android:text="@string/action_enable" />
<LinearLayout
android:id="@+id/disableButtons"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:visibility="gone"
tools:visibility="visible">
<com.google.android.material.button.MaterialButton
android:id="@+id/disable10SecondsButton"
style="@style/AppTheme.Button.Red"
android:text="@string/action_disable_10_seconds" />
<com.google.android.material.button.MaterialButton
android:id="@+id/disable30SecondsButton"
style="@style/AppTheme.Button.Red"
android:text="@string/action_disable_30_seconds" />
<com.google.android.material.button.MaterialButton
android:id="@+id/disable5MinutesButton"
style="@style/AppTheme.Button.Red"
android:text="@string/action_disable_5_minutes" />
<com.google.android.material.button.MaterialButton
android:id="@+id/disableCustomTimeButton"
style="@style/AppTheme.Button.Red"
android:text="@string/action_disable_custom" />
<com.google.android.material.button.MaterialButton
android:id="@+id/disablePermanentlyButton"
style="@style/AppTheme.Button.Red"
android:text="@string/action_disable_permanently" />
</LinearLayout>
</LinearLayout>
</ScrollView>
<ImageView
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_app_logo"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/toolbar" />
</androidx.constraintlayout.widget.ConstraintLayout>

View file

@ -0,0 +1,82 @@
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:animateLayoutChanges="true"
tools:background="@color/colorSurface"
tools:context=".RetrieveApiKeyFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical"
android:padding="16dp">
<ImageView
android:id="@+id/piHelperLogo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:contentDescription="@string/accessibility_description_pi_helper_logo"
android:src="@drawable/ic_app_logo"
android:tint="@color/colorOnSurface"
android:transitionName="piHelperLogo" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Pi-Helper has successfully connected to your Pi-Hole!"
android:textAlignment="center" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="You'll need to authenticate in order to enable and disable the Pi-hole."
android:textAlignment="center" />
<com.google.android.material.textfield.TextInputLayout
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Pi-Hole Web Password">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.button.MaterialButton
android:id="@+id/connectWithPasswordButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Authenticate with Password" />
<include layout="@layout/or_divider" />
<com.google.android.material.textfield.TextInputLayout
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Pi-Hole API Key">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/apiKey"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.button.MaterialButton
android:id="@+id/connectWithApiKeyButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Authenticate with API Key" />
</LinearLayout>
</ScrollView>

View file

@ -0,0 +1,35 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="16dp"
tools:background="@color/colorSurface"
tools:context=".ScanNetworkFragment">
<ImageView
android:id="@+id/piHelperLogo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="@drawable/ic_app_logo"
android:tint="@color/colorOnSurface"
android:transitionName="piHelperLogo"
android:contentDescription="@string/accessibility_description_pi_helper_logo" />
<TextView
android:id="@+id/ipAddressScanningInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/scanning_ip_address"
android:textAlignment="center" />
<TextView
android:id="@+id/ipAddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAlignment="center" />
</LinearLayout>

View file

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:background="@color/colorSurface">
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:scaleType="fitXY"
android:src="@drawable/horizontal_rule" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="16dp"
android:text="@string/or"
android:textAlignment="center"
android:textAllCaps="true" />
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:scaleType="fitXY"
android:src="@drawable/horizontal_rule" />
</LinearLayout>

View file

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/settings"
android:icon="@drawable/ic_settings"
android:title="@string/action_settings"
app:showAsAction="ifRoom" />
</menu>

View file

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background"/>
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
</adaptive-icon>

View file

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background"/>
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
</adaptive-icon>

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

View file

@ -0,0 +1,77 @@
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/nav_graph"
app:startDestination="@id/placeholder">
<fragment
android:id="@+id/addPiHoleFragment"
android:name="com.wbrawner.pihelper.AddPiHoleFragment"
android:label="fragment_add_pi_hole"
tools:layout="@layout/fragment_add_pi_hole" >
<action
android:id="@+id/action_addPiHoleFragment_to_scanNetworkFragment"
app:destination="@id/scanNetworkFragment"
app:enterAnim="@anim/nav_default_enter_anim"
app:exitAnim="@anim/nav_default_exit_anim"
app:popEnterAnim="@anim/nav_default_pop_enter_anim"
app:popExitAnim="@anim/nav_default_pop_exit_anim" />
<action
android:id="@+id/action_addPiHoleFragment_to_retrieveApiKeyFragment"
app:destination="@id/retrieveApiKeyFragment"
app:enterAnim="@anim/nav_default_enter_anim"
app:exitAnim="@anim/nav_default_exit_anim"
app:popEnterAnim="@anim/nav_default_pop_enter_anim"
app:popExitAnim="@anim/nav_default_pop_exit_anim" />
</fragment>
<fragment
android:id="@+id/placeholder"
android:name="androidx.fragment.app.Fragment" />
<fragment
android:id="@+id/scanNetworkFragment"
android:name="com.wbrawner.pihelper.ScanNetworkFragment"
android:label="fragment_scan_network"
tools:layout="@layout/fragment_scan_network" >
<action
android:id="@+id/action_scanNetworkFragment_to_retrieveApiKeyFragment"
app:destination="@id/retrieveApiKeyFragment"
app:enterAnim="@anim/nav_default_enter_anim"
app:exitAnim="@anim/nav_default_exit_anim"
app:popEnterAnim="@anim/nav_default_pop_enter_anim"
app:popExitAnim="@anim/nav_default_pop_exit_anim"
app:popUpTo="@+id/addPiHoleFragment" />
</fragment>
<fragment
android:id="@+id/retrieveApiKeyFragment"
android:name="com.wbrawner.pihelper.RetrieveApiKeyFragment"
android:label="fragment_retrieve_api_key"
tools:layout="@layout/fragment_retrieve_api_key" >
<action
android:id="@+id/action_retrieveApiKeyFragment_to_mainFragment"
app:destination="@id/mainFragment"
app:enterAnim="@anim/nav_default_enter_anim"
app:exitAnim="@anim/nav_default_exit_anim"
app:popEnterAnim="@anim/nav_default_pop_enter_anim"
app:popExitAnim="@anim/nav_default_pop_exit_anim" />
</fragment>
<fragment
android:id="@+id/mainFragment"
android:name="com.wbrawner.pihelper.MainFragment"
android:label="@string/app_name"
tools:layout="@layout/fragment_main" >
<action
android:id="@+id/action_mainFragment_to_settingsFragment"
app:destination="@id/settingsFragment"
app:enterAnim="@anim/nav_default_enter_anim"
app:exitAnim="@anim/nav_default_exit_anim"
app:popEnterAnim="@anim/nav_default_pop_enter_anim"
app:popExitAnim="@anim/nav_default_pop_exit_anim" />
</fragment>
<fragment
android:id="@+id/settingsFragment"
android:name="com.wbrawner.pihelper.InfoFragment"
android:label="@string/action_settings"
tools:layout="@layout/fragment_info" />
</navigation>

View file

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorSurface">#333333</color>
<color name="colorOnSurface">#f1f1f1</color>
<color name="colorEnabled">@color/colorGreenLight</color>
<color name="colorDisabled">@color/colorRedLight</color>
</resources>

View file

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="BaseTheme">
<item name="android:windowLightStatusBar">false</item>
</style>
<style name="AppTheme.Button.Red" parent="Widget.MaterialComponents.Button">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="backgroundTint">@color/colorRedLight</item>
<item name="android:textColor">@color/colorWhite</item>
</style>
</resources>

View file

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">@color/colorRedLight</color>
<color name="colorPrimaryDark">@color/colorRedDark</color>
<color name="colorAccent">@color/colorRedLight</color>
<color name="colorRedLight">#f60d1a</color>
<color name="colorRedDark">#96060c</color>
<color name="colorGreenLight">#30d158</color>
<color name="colorGreenDark">#34c759</color>
<color name="colorOnSurface">#000000</color>
<color name="colorWhite">#ffffff</color>
<color name="colorEnabled">@color/colorGreenDark</color>
<color name="colorDisabled">@color/colorRedDark</color>
<color name="colorSurface">@color/colorWhite</color>
<color name="colorTransparent">#00000000</color>
<color name="colorButtonSecondary">#666666</color>
</resources>

View file

@ -0,0 +1,33 @@
<resources>
<string name="app_name">Pi-Helper</string>
<string name="scanning_ip_address">Scanning IP Address:</string>
<string name="accessibility_description_pi_helper_logo">Pi-Helper Logo</string>
<string name="label_status">Status: %1$s</string>
<string name="action_enable">Enable</string>
<string name="action_disable">Disable</string>
<string name="action_disable_10_seconds">Disable for 10 seconds</string>
<string name="action_disable_30_seconds">Disable for 30 seconds</string>
<string name="action_disable_5_minutes">Disable for 5 minutes</string>
<string name="action_disable_custom">Disable for custom time</string>
<string name="action_disable_permanently">Disable Permanently</string>
<string name="status_disabled">Disabled</string>
<string name="status_enabled">Enabled</string>
<string name="scan_failed">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.</string>
<string name="scan_failed_title">Pi-Helper failed to find your Pi-Hole</string>
<string name="connection_failed">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.</string>
<string name="connection_failed_title">Pi-Helper failed to connect to your Pi-Hole</string>
<string name="configure_pihelper">Please configure Pi-Helper before using shortcuts</string>
<string name="or">or</string>
<string name="action_opt_out">Sorry, but no</string>
<string name="action_opt_in">Yes, I\'ll help!</string>
<string name="prompt_usage_opt_in">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.</string>
<string name="title_usage_opt_in">Help make Pi-Helper better</string>
<string name="action_settings">Settings</string>
<string name="action_forget_pihole">Forget Pi-hole</string>
<string name="content_info"><![CDATA[Pi-Helper was made with ❤ by <a href=\"https://wbrawner.com\">William Brawner</a>. You can find the source code or report issues on the <a href=\"https://github.com/wbrawner/PiHelperAndroid\">GitHub page</a> for the project.]]></string>
<string name="confirm_forget_pihole">Are you sure you want to forget your Pi-hole?</string>
<string name="warning_cannot_be_undone">This cannot be undone.</string>
<string name="title_crash_notification">Pi-Helper Crashed!</string>
<string name="text_crash_notification">Would you please consider sending the crash report to me?</string>
<string name="channel_crash_notification">Crash Reports</string>
</resources>

View file

@ -0,0 +1,28 @@
<resources>
<style name="BaseTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:windowBackground">@drawable/background_splash</item>
<item name="android:statusBarColor">@color/colorTransparent</item>
<item name="android:textColor">@color/colorOnSurface</item>
</style>
<style name="AppTheme" parent="BaseTheme">
<item name="android:windowLightStatusBar">true</item>
</style>
<style name="AppTheme.Button" parent="Widget.MaterialComponents.Button">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textColor">@color/colorWhite</item>
</style>
<style name="AppTheme.Button.Green" parent="AppTheme.Button">
<item name="backgroundTint">@color/colorGreenDark</item>
</style>
<style name="AppTheme.Button.Red" parent="AppTheme.Button">
<item name="backgroundTint">@color/colorRedDark</item>
</style>
</resources>

View file

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<full-backup-content>
<!-- Exclude specific shared preferences that contain GCM registration Id -->
</full-backup-content>

View file

@ -0,0 +1,62 @@
<?xml version="1.0" encoding="utf-8"?>
<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
<shortcut
android:enabled="true"
android:icon="@drawable/ic_shortcut_pause"
android:shortcutId="disable5Minutes"
android:shortcutLongLabel="@string/action_disable_5_minutes"
android:shortcutShortLabel="@string/action_disable_5_minutes">
<intent
android:action="com.wbrawner.pihelper.MainFragment.ACTION_DISABLE"
android:targetClass="com.wbrawner.pihelper.MainActivity"
android:targetPackage="com.wbrawner.pihelper">
<extra
android:name="com.wbrawner.pihelper.MainFragment.EXTRA_DURATION"
android:value="300" />
</intent>
</shortcut>
<shortcut
android:enabled="true"
android:icon="@drawable/ic_shortcut_pause"
android:shortcutId="disable30Seconds"
android:shortcutLongLabel="@string/action_disable_30_seconds"
android:shortcutShortLabel="@string/action_disable_30_seconds">
<intent
android:action="com.wbrawner.pihelper.MainFragment.ACTION_DISABLE"
android:targetClass="com.wbrawner.pihelper.MainActivity"
android:targetPackage="com.wbrawner.pihelper">
<extra
android:name="com.wbrawner.pihelper.MainFragment.EXTRA_DURATION"
android:value="30" />
</intent>
</shortcut>
<shortcut
android:enabled="true"
android:icon="@drawable/ic_shortcut_pause"
android:shortcutId="disable10Seconds"
android:shortcutLongLabel="@string/action_disable_10_seconds"
android:shortcutShortLabel="@string/action_disable_10_seconds">
<intent
android:action="com.wbrawner.pihelper.MainFragment.ACTION_DISABLE"
android:targetClass="com.wbrawner.pihelper.MainActivity"
android:targetPackage="com.wbrawner.pihelper">
<extra
android:name="com.wbrawner.pihelper.MainFragment.EXTRA_DURATION"
android:value="10" />
</intent>
</shortcut>
<shortcut
android:enabled="true"
android:icon="@drawable/ic_shortcut_enable"
android:shortcutId="enable"
android:shortcutLongLabel="@string/action_enable"
android:shortcutShortLabel="@string/action_enable">
<intent
android:action="com.wbrawner.pihelper.MainFragment.ACTION_ENABLE"
android:targetClass="com.wbrawner.pihelper.MainActivity"
android:targetPackage="com.wbrawner.pihelper" />
</shortcut>
</shortcuts>

View file

@ -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)
}
}

28
build.gradle Normal file
View file

@ -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
}

21
gradle.properties Normal file
View file

@ -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

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View file

@ -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

172
gradlew vendored Executable file
View file

@ -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" "$@"

84
gradlew.bat vendored Normal file
View file

@ -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

1
piholeclient/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
/build

45
piholeclient/build.gradle Normal file
View file

@ -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'
}

View file

@ -0,0 +1,67 @@
# JSR 305 annotations are for embedding nullability information.
-dontwarn javax.annotation.**
-keepclasseswithmembers class * {
@com.squareup.moshi.* <methods>;
}
-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 {
<fields>;
**[] 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 <init>(...);
}
# Retain generated JsonAdapters if annotated type is retained.
-if @com.squareup.moshi.JsonClass class *
-keep class <1>JsonAdapter {
<init>(...);
<fields>;
}
-if @com.squareup.moshi.JsonClass class **$*
-keep class <1>_<2>JsonAdapter {
<init>(...);
<fields>;
}
-if @com.squareup.moshi.JsonClass class **$*$*
-keep class <1>_<2>_<3>JsonAdapter {
<init>(...);
<fields>;
}
-if @com.squareup.moshi.JsonClass class **$*$*$*
-keep class <1>_<2>_<3>_<4>JsonAdapter {
<init>(...);
<fields>;
}
-if @com.squareup.moshi.JsonClass class **$*$*$*$*
-keep class <1>_<2>_<3>_<4>_<5>JsonAdapter {
<init>(...);
<fields>;
}
-if @com.squareup.moshi.JsonClass class **$*$*$*$*$*
-keep class <1>_<2>_<3>_<4>_<5>_<6>JsonAdapter {
<init>(...);
<fields>;
}
-keep class kotlin.reflect.jvm.internal.impl.builtins.BuiltInsLoaderImpl
-keepclassmembers class kotlin.Metadata {
public <methods>;
}

21
piholeclient/proguard-rules.pro vendored Normal file
View file

@ -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

View file

@ -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)
}
}

View file

@ -0,0 +1,5 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.wbrawner.piholeclient">
<uses-permission android:name="android.permission.INTERNET" />
<application android:usesCleartextTraffic="true" />
</manifest>

View file

@ -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<String>
//
// @GET("/admin/scripts/pi-hole/php/api_token.php")
// suspend fun apiKey(phpSession: String): Response<String>
}
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 <T : Any> sendRequest(request: Request, responseType: KClass<T>?): 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())
}
}
}
}
}
}

View file

@ -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<String, List<Cookie>>()
override fun loadForRequest(url: HttpUrl): List<Cookie> = cookies[url.host]
?: emptyList()
override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
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<PiHoleApiService> {
OkHttpPiHoleApiService(get(), get())
}
}

View file

@ -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<String>,
@Json(name = "top_ads") val topAds: List<String>
)
@JsonClass(generateAdapter = true)
data class StatusResponse(
val status: Status
)

View file

@ -0,0 +1,3 @@
<resources>
<string name="app_name">PiHoleClient</string>
</resources>

View file

@ -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)
}
}

2
settings.gradle Normal file
View file

@ -0,0 +1,2 @@
include ':app', ':piholeclient'
rootProject.name='Pi-Helper'