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

43 lines
1.2 KiB
Kotlin
Raw Normal View History

2022-07-18 22:45:35 +05:30
package com.github.libretube.update
2022-06-06 16:17:54 +05:30
2022-07-05 14:44:51 +05:30
import com.github.libretube.GITHUB_API_URL
2022-07-18 18:15:32 +05:30
import com.google.gson.Gson
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-07-18 22:45:35 +05:30
fun checkUpdate(): UpdateInfo? {
var versionInfo: UpdateInfo? = null
2022-06-06 16:17:54 +05:30
// run http request as thread to make it async
val thread = Thread {
// otherwise crashes without internet
try {
2022-07-18 17:54:08 +05:30
versionInfo = getUpdateInfo()
2022-06-06 16:17:54 +05:30
} catch (e: Exception) {
}
}
thread.start()
// wait for the thread to finish
thread.join()
2022-07-18 17:54:08 +05:30
// return the information about the latest version
return versionInfo
2022-06-06 16:17:54 +05:30
}
2022-07-18 22:45:35 +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
2022-07-18 22:45:35 +05:30
// read json
val br = BufferedReader(InputStreamReader(urlConnection.inputStream))
2022-06-06 16:17:54 +05:30
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-07-18 18:15:32 +05:30
val gson = Gson()
2022-07-18 22:45:35 +05:30
return gson.fromJson(json.toString(), UpdateInfo::class.java)
2022-06-06 16:17:54 +05:30
}