de.comhix.commons.updater.Updater.kt Maven / Gradle / Ivy
package de.comhix.commons.updater
import com.google.gson.GsonBuilder
import okhttp3.OkHttpClient.Builder
import okhttp3.Request
import okio.Okio
import java.io.*
import java.util.zip.ZipInputStream
/**
* @author Benjamin Beeker
*/
class Updater> private constructor(
private val url: String,
private val currentVersion: Info,
private val updateUrlProvider: (Info) -> String,
private val versionProvider: (Info) -> Version) {
private val info: Info by lazy {
GsonBuilder().create().fromJson(InputStreamReader(loadInfo()), currentVersion::class.java as Class)
}
@Throws(IOException::class)
fun loadInfo(): InputStream {
val client = Builder().build()
val response = client.newCall(Request.Builder().url(url).build()).execute()
return response.body()!!.byteStream()
}
@Throws(IOException::class)
fun hasUpdate(): Boolean {
return versionProvider.invoke(currentVersion) < versionProvider.invoke(info)
}
@Throws(IOException::class)
fun doUpdate() {
val client = Builder().build()
val response = client.newCall(Request.Builder().url(updateUrlProvider.invoke(info)).build()).execute()
Okio.buffer(Okio.sink(File("update.zip"))).use { output -> output.writeAll(Okio.source(response.body()!!.byteStream())) }
val buffer = ByteArray(1024)
val zis = ZipInputStream(FileInputStream("update.zip"))
var zipEntry = zis.nextEntry
while (zipEntry != null) {
val fileName = zipEntry.name
val newFile = File(fileName)
val fos = FileOutputStream(newFile)
var len: Int
while (zis.read(buffer).also { len = it } > 0) {
fos.write(buffer, 0, len)
}
fos.close()
zipEntry = zis.nextEntry
}
zis.closeEntry()
zis.close()
File("update.zip").deleteOnExit()
}
companion object {
fun > create(url: String,
currentVersion: Info,
updateUrlProvider: (Info) -> String,
versionProvider: (Info) -> Version): Updater {
return Updater(url, currentVersion, updateUrlProvider, versionProvider)
}
}
} © 2015 - 2025 Weber Informatics LLC | Privacy Policy