package moe.yuuta.workmode.update import com.elvishew.xlog.XLog import moe.yuuta.workmode.BuildConfig import moe.yuuta.workmode.async.Runnable import org.json.JSONObject import java.io.BufferedReader import java.io.InputStreamReader import java.net.HttpURLConnection import java.net.URL class UpdateChecker : Runnable { private val logger = XLog.tag("UpdateChecker").build() override fun run(): Update { logger.d("Start checking") var httpURLConnection: HttpURLConnection? = null try { val url = URL("https://raw.githubusercontent.com/Trumeet/_priv/master/update/${BuildConfig.APPLICATION_ID}.json") httpURLConnection = url.openConnection() as HttpURLConnection httpURLConnection.requestMethod = "GET" httpURLConnection.connect() val inputStream = httpURLConnection.inputStream val buffer = StringBuffer() if (inputStream == null) { throw IllegalStateException("Str is null.") } val reader = BufferedReader(InputStreamReader(inputStream)) var line: String? while (true) { line = reader.readLine() if (line == null) break buffer.append(line + "\n") } if (buffer.isEmpty()) { throw IllegalStateException("Buffer is empty") } val response = buffer.toString() logger.i("Response: ${httpURLConnection.responseCode} (${httpURLConnection.responseMessage}), data: $response") val json = JSONObject(response) return Update(json.getInt("version"), json.getString("name"), json.getString("alt_url"), json.getBoolean("alt_url_enable"), json.getBoolean("alt_url_force")) } catch (e: Exception) { logger.e("Unable to check", e) throw e } finally { // this is done so that there are no open connections left when this task is going to complete if (httpURLConnection != null) httpURLConnection.disconnect() } } } data class Update( val version: Int, val name: String, val altUrl: String, val altUrlEnabled: Boolean, val altUrlForce: Boolean )