Skip to content

Commit

Permalink
Merge pull request #177 from hannesa2/OptionalAuthTokenHEADER
Browse files Browse the repository at this point in the history
Optional auth token header
  • Loading branch information
hannesa2 authored Nov 29, 2023
2 parents 9fa16b9 + a8866a2 commit 361709e
Show file tree
Hide file tree
Showing 6 changed files with 58 additions and 22 deletions.
3 changes: 2 additions & 1 deletion app/src/main/java/info/hannes/github/sample/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ class MainActivity : AppCompatActivity() {

AppUpdateHelper.checkForNewVersion(
this,
BuildConfig.GIT_REPOSITORY
BuildConfig.GIT_REPOSITORY,
token = "abcdefgh"
)

binding.button.setOnClickListener {
Expand Down
29 changes: 18 additions & 11 deletions githubAppUpdate/src/main/java/info/hannes/github/AppUpdateHelper.kt
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Response
import java.lang.RuntimeException
import java.net.HttpURLConnection
import java.util.concurrent.TimeUnit


Expand All @@ -33,7 +35,6 @@ object AppUpdateHelper {
""
}

@Suppress("DEPRECATION")
fun Context.getPackageInfo(): PackageInfo {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
packageManager.getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(0))
Expand All @@ -43,16 +44,17 @@ object AppUpdateHelper {
}

// silently in background
fun checkForNewVersion(activity: AppCompatActivity, gitRepoUrl: String, repeatTime : Long = 6, timeUnit: TimeUnit = TimeUnit.HOURS) {
fun checkForNewVersion(activity: AppCompatActivity, gitRepoUrl: String, repeatTime : Long = 6, timeUnit: TimeUnit = TimeUnit.HOURS, token: String? = null) {
val currentVersionName = activity.getVersionName()
DownloadWorker.run(activity, currentVersionName, gitRepoUrl, repeatTime, timeUnit)
DownloadWorker.run(activity, currentVersionName, gitRepoUrl, repeatTime, timeUnit, token)
}

fun checkWithDialog(
activity: AppCompatActivity,
gitRepoUrl: String,
callback: ((String) -> Unit)? = null,
force: Boolean = false
force: Boolean = false,
token: String? = null
) = activity.lifecycle.coroutineScope.launch(Dispatchers.Main) {

val currentVersionName = activity.getVersionName()
Expand All @@ -62,7 +64,7 @@ object AppUpdateHelper {

if (force || prefs.getLong(key, 0) < System.currentTimeMillis() - 1000 * 3600 * 24 / 24 / 60 * 5) {
try {
val versionList = requestGithubVersions(gitRepoUrl)
val versionList = requestGithubVersions(gitRepoUrl, token)
prefs.edit().putLong(key, System.currentTimeMillis()).apply()

versionList.body()?.firstOrNull()?.let { release ->
Expand All @@ -76,6 +78,8 @@ object AppUpdateHelper {
callback?.invoke("Nothing to do with ${release.tagName}")
}
}
if (versionList.code() != HttpURLConnection.HTTP_OK)
throw RuntimeException("call delivers ${versionList.code()}")
} catch (e: Exception) {
Log.e("AppUpdateHelper", "git check deliver: ${e.message}")
Toast.makeText(activity, "git check delivers: ${e.message}", Toast.LENGTH_LONG).show()
Expand All @@ -86,10 +90,11 @@ object AppUpdateHelper {
internal fun checkForNewVersionSilent(
appContext: Context,
currentVersionName: String,
gitRepoUrl: String
gitRepoUrl: String,
token: String? = null
){
try {
val versionList = requestVersionsSync(gitRepoUrl)
val versionList = requestVersionsSync(gitRepoUrl, token)

versionList.body()?.firstOrNull()?.let { release ->
val assetApk = release.assets.find { it.name.endsWith("release.apk") }
Expand All @@ -101,19 +106,21 @@ object AppUpdateHelper {
Notify.notification(appContext, text, "New version for '${getAppName(appContext)}'", assetApk, release)
}
}
if (versionList.code() != HttpURLConnection.HTTP_OK)
throw RuntimeException("call delivers ${versionList.code()}")
} catch (e: Exception) {
Log.e("AppUpdateHelper", "git check deliver: ${e.message}")
}
}

private fun requestVersionsSync(gitRepoUrl: String): Response<MutableList<GithubVersion>> {
val client = GithubClient(HttpLoggingInterceptor.Level.BODY)
private fun requestVersionsSync(gitRepoUrl: String, token: String? = null): Response<MutableList<GithubVersion>> {
val client = GithubClient(HttpLoggingInterceptor.Level.BODY, token)
return client.github.getGithubVersions(gitRepoUrl.user(), gitRepoUrl.repo()).execute()
}

private suspend fun requestGithubVersions(gitRepoUrl: String): Response<MutableList<GithubVersion>> {
private suspend fun requestGithubVersions(gitRepoUrl: String, token: String? = null): Response<MutableList<GithubVersion>> {
val versionList = withContext(Dispatchers.Default) {
val client = GithubClient(HttpLoggingInterceptor.Level.BODY)
val client = GithubClient(HttpLoggingInterceptor.Level.BODY, token)
client.github.getGithubVersions(gitRepoUrl.user(), gitRepoUrl.repo()).execute()
}
return versionList
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@ class DownloadWorker(private val appContext: Context, workerParams: WorkerParame
// Get the input
val currentVersion = inputData.getString(CURRENT_VERSION)!!
val repoUrl = inputData.getString(REPO_URL)!!
val token = inputData.getString(TOKEN)!!

val d = async {
check(currentVersion, repoUrl)
check(currentVersion, repoUrl, token)
"done"
}
val value = d.await()
Expand All @@ -25,15 +26,16 @@ class DownloadWorker(private val appContext: Context, workerParams: WorkerParame
Result.success(outputData)
}

private fun check(currentVersion: String, repoUrl: String) {
AppUpdateHelper.checkForNewVersionSilent(appContext, currentVersion, repoUrl)
private fun check(currentVersion: String, repoUrl: String, token: String? = null) {
AppUpdateHelper.checkForNewVersionSilent(appContext, currentVersion, repoUrl, token = token)
}

companion object {
fun run(context: Context, currentVersionName: String, repoUrl: String, repeatTime : Long, timeUnit: TimeUnit): ListenableFuture<MutableList<WorkInfo>> {
fun run(context: Context, currentVersionName: String, repoUrl: String, repeatTime : Long, timeUnit: TimeUnit, token: String? = null): ListenableFuture<MutableList<WorkInfo>> {
val data = workDataOf(
Pair(CURRENT_VERSION, currentVersionName),
Pair(REPO_URL, repoUrl)
Pair(REPO_URL, repoUrl),
Pair(TOKEN, token)
)

val constraints = Constraints.Builder()
Expand All @@ -58,6 +60,7 @@ class DownloadWorker(private val appContext: Context, workerParams: WorkerParame

const val CURRENT_VERSION = "CURRENT_VERSION"
const val REPO_URL = "REPO_URL"
const val TOKEN = "TOKEN"
private const val uniqueWorkName = "PWD"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ package info.hannes.github

import okhttp3.logging.HttpLoggingInterceptor

internal class GithubClient(private val logLevel: HttpLoggingInterceptor.Level) {
internal class GithubClient(private val logLevel: HttpLoggingInterceptor.Level, private val token: String? = null) {

val github: IGithub

private val githubService: IGithub
get() = GithubRestServiceCreationHelper.createGithubService(
IGithub::class.java,
logLevel
IGithub::class.java,
logLevel,
token
)

init {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,18 @@ internal object GithubRestServiceCreationHelper {
.create()
}

fun <T> createGithubService(retrofitInterface: Class<T>, logLevel: HttpLoggingInterceptor.Level): T {
fun <T> createGithubService(retrofitInterface: Class<T>, logLevel: HttpLoggingInterceptor.Level, token: String? = null): T {

httpLoggingInterceptor.level = logLevel

val client = OkHttpClient.Builder()
val clientHttp = OkHttpClient.Builder()
.addInterceptor(httpLoggingInterceptor)

token?.let {
clientHttp.addInterceptor(TokenInterceptor(it))
}

val client = clientHttp
.build()

val gson = createGson()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package info.hannes.github

import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import java.io.IOException

class TokenInterceptor(private val token: String) : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {

//rewrite the request to add bearer token
val newRequest: Request = chain.request().newBuilder()
.header("Authorization", "Token $token")
.build()
return chain.proceed(newRequest)
}
}

0 comments on commit 361709e

Please sign in to comment.