LibreTube/app/src/main/java/com/github/libretube/util/UpdateChecker.kt

76 lines
2.7 KiB
Kotlin
Raw Normal View History

2022-06-06 16:17:54 +05:30
package com.github.libretube.util
import android.util.Log
import androidx.fragment.app.FragmentManager
import com.github.libretube.BuildConfig
2022-06-14 22:38:02 +05:30
import com.github.libretube.GITHUB_API_URL
2022-06-09 12:45:51 +05:30
import com.github.libretube.dialogs.NoUpdateAvailableDialog
2022-06-06 16:17:54 +05:30
import com.github.libretube.dialogs.UpdateAvailableDialog
2022-06-14 22:38:02 +05:30
import com.github.libretube.obj.UpdateInfo
2022-06-06 16:17:54 +05:30
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.URL
import javax.net.ssl.HttpsURLConnection
2022-06-07 19:30:51 +05:30
import org.json.JSONArray
import org.json.JSONObject
2022-06-06 16:17:54 +05:30
fun checkUpdate(childFragmentManager: FragmentManager) {
var updateInfo: UpdateInfo? = UpdateInfo("", "")
// run http request as thread to make it async
val thread = Thread {
// otherwise crashes without internet
try {
updateInfo = getUpdateInfo()
} catch (e: Exception) {
}
}
thread.start()
// wait for the thread to finish
thread.join()
// show the UpdateAvailableDialog if there's an update available
if (updateInfo?.tagName != "" && BuildConfig.VERSION_NAME != updateInfo?.tagName) {
val updateAvailableDialog = UpdateAvailableDialog(
updateInfo?.tagName!!,
2022-06-09 12:45:51 +05:30
updateInfo?.updateUrl!!
2022-06-07 19:22:10 +05:30
)
2022-06-09 12:45:51 +05:30
updateAvailableDialog.show(childFragmentManager, "UpdateAvailableDialog")
2022-06-07 19:22:10 +05:30
} else {
// otherwise show the no update available dialog
2022-06-09 12:45:51 +05:30
val noUpdateAvailableDialog = NoUpdateAvailableDialog()
noUpdateAvailableDialog.show(childFragmentManager, "NoUpdateAvailableDialog")
2022-06-06 16:17:54 +05:30
}
}
fun getUpdateInfo(): UpdateInfo? {
2022-06-14 22:38:02 +05:30
val latest = URL(GITHUB_API_URL)
2022-06-06 16:17:54 +05:30
val json = StringBuilder()
val urlConnection: HttpsURLConnection?
urlConnection = latest.openConnection() as HttpsURLConnection
val br = BufferedReader(InputStreamReader(urlConnection.inputStream))
var line: String?
while (br.readLine().also { line = it } != null) json.append(line)
2022-06-14 22:38:02 +05:30
// Parse and return the json data
2022-06-06 16:17:54 +05:30
val jsonRoot = JSONObject(json.toString())
if (jsonRoot.has("tag_name") &&
jsonRoot.has("html_url") &&
jsonRoot.has("assets")
) {
val updateUrl = jsonRoot.getString("html_url")
val jsonAssets: JSONArray = jsonRoot.getJSONArray("assets")
for (i in 0 until jsonAssets.length()) {
val jsonAsset = jsonAssets.getJSONObject(i)
if (jsonAsset.has("name")) {
val name = jsonAsset.getString("name")
if (name.endsWith(".apk")) {
val tagName = jsonRoot.getString("name")
2022-06-14 22:38:02 +05:30
Log.i("", "Latest version: $tagName")
2022-06-06 16:17:54 +05:30
return UpdateInfo(updateUrl, tagName)
}
}
}
}
return null
}