mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-24 23:36:04 +00:00
feat(addons): install the CurseForge app and update addons per game (#2986)
* feat(addons): install the CurseForge app and update addons per game The Addons tab installs the official CurseForge Linux app from its own update feed, checks it against the feed's SHA-512, shows its version, offers updates and removes it with the components delete button. Installed addons show their .toc version and are checked against WoWInterface by X-WoWI-ID or the recorded source of addons installed from the Download window; Update replaces them in place. The CurseForge web search chip is replaced by the app. * fix(addons): address review on update ordering, flavor filter, origins lock and failed checks * fix(addons): compact scrollable addon browser with list rows * fix(addons): compare release times as instants and replace the sources file atomically * fix(addons): open the addon browser at the top of the list * Keep the addon browser's search focus and installed version in sync * Track the search field's own focus in the addon browser * Key the installed addon version by install target * Install rar and 7z addon archives
This commit is contained in:
1 parent
3577073ab9
commit
d6496b2f96
16 files changed
+765
-153
No files matched your search
@@ -0,0 +1,10 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
object CurseForgeApp {
|
||||
const val NAME = "CurseForge"
|
||||
const val FEED = "https://curseforge.overwolf.com/electron/linux/latest-linux.yml"
|
||||
|
||||
fun find(apps: List<UserApps.App>): UserApps.App? = apps.firstOrNull { it.feed == FEED }
|
||||
|
||||
fun request(): UserApps.Request = UserApps.Request(UserApps.Source.Feed(FEED), NAME, null)
|
||||
}
|
||||
@@ -36,6 +36,7 @@ object UserApps {
|
||||
private const val GITHUB_TAG = "github-tag"
|
||||
private const val GITHUB_PUBLISHED = "github-published"
|
||||
private const val GITHUB_ASSET = "github-asset"
|
||||
private const val FEED = "update-feed"
|
||||
|
||||
enum class Kind { SCRIPT, APPIMAGE, FLATPAK }
|
||||
|
||||
@@ -43,10 +44,15 @@ object UserApps {
|
||||
val key: String, val kind: Kind, val name: String, val icon: Any?, val detail: String?,
|
||||
val program: String, val args: List<String>, val copied: Boolean = false,
|
||||
val repo: String? = null, val version: String? = null,
|
||||
val fex: String = LinuxFex.AUTO, val arch: String? = null,
|
||||
)
|
||||
val fex: String = LinuxFex.AUTO, val arch: String? = null, val feed: String? = null,
|
||||
) {
|
||||
val updatable get() = repo != null || feed != null
|
||||
}
|
||||
|
||||
class Release(val tag: String, val published: String, val asset: String, val url: String, val sha256: String? = null)
|
||||
class Release(
|
||||
val tag: String, val published: String, val asset: String, val url: String,
|
||||
val sha256: String? = null, val sha512: String? = null,
|
||||
)
|
||||
|
||||
sealed class UpdateCheck {
|
||||
class Current(val tag: String) : UpdateCheck()
|
||||
@@ -58,6 +64,7 @@ object UserApps {
|
||||
class Script(val file: File) : Source()
|
||||
class AppImage(val file: File) : Source()
|
||||
class GitHub(val repo: String, val asset: String? = null) : Source()
|
||||
class Feed(val url: String) : Source()
|
||||
class Flatpak(val id: String) : Source()
|
||||
class FlatpakBundle(val file: File) : Source()
|
||||
}
|
||||
@@ -91,6 +98,7 @@ object UserApps {
|
||||
"appimage:${item.id}", Kind.APPIMAGE, item.name, item.icon, item.comment, AppImageManager.LAUNCHER, listOf(item.guestDir),
|
||||
repo = FileUtils.readString(File(dir, GITHUB_REPO))?.trim(), version = FileUtils.readString(File(dir, GITHUB_TAG))?.trim(),
|
||||
fex = LinuxFex.mode(dir), arch = FileUtils.readString(File(dir, "arch"))?.trim()?.takeIf { it.isNotEmpty() },
|
||||
feed = FileUtils.readString(File(dir, FEED))?.trim()?.takeIf { it.isNotEmpty() },
|
||||
)
|
||||
}
|
||||
val flatpaks = FlatpakManager.installedApps(context).map { app ->
|
||||
@@ -115,6 +123,7 @@ object UserApps {
|
||||
is Source.Script -> addScript(context, s.file, name, icon, request.meta, onProgress)
|
||||
is Source.AppImage -> AppImageManager.import(context, s.file, name, icon, request.meta) { onProgress(it, -1) }
|
||||
is Source.GitHub -> addFromGitHub(context, s.repo, s.asset, name, icon, onProgress)
|
||||
is Source.Feed -> addFromFeed(context, s.url, name, icon, onProgress)
|
||||
is Source.Flatpak -> addFlatpak(context, s.id, name, icon, onProgress)
|
||||
is Source.FlatpakBundle -> addFlatpakBundle(context, s.file, name, icon, onProgress)
|
||||
}
|
||||
@@ -346,11 +355,15 @@ object UserApps {
|
||||
}
|
||||
|
||||
private fun withDownload(context: Context, release: Release, onProgress: (String, Int) -> Unit, use: (File) -> String?): String? {
|
||||
val download = File(context.cacheDir, "github-${release.asset}")
|
||||
val download = File(File(context.cacheDir, "user-apps").apply { mkdirs() }, release.asset)
|
||||
try {
|
||||
val label = context.getString(R.string.user_apps_downloading, release.asset)
|
||||
val ok = Downloader.downloadFile(release.url, download, false, release.sha256) { f -> onProgress(label, if (f < 0) -1 else Math.round(f * 100f)) }
|
||||
return if (ok) use(download) else context.getString(R.string.user_apps_download_failed)
|
||||
if (!ok) return context.getString(R.string.user_apps_download_failed)
|
||||
if (release.sha512 != null && !Hashes.sha512(download).equals(release.sha512, ignoreCase = true)) {
|
||||
return context.getString(R.string.selfinst_checksum_mismatch)
|
||||
}
|
||||
return use(download)
|
||||
} finally {
|
||||
download.delete()
|
||||
}
|
||||
@@ -392,20 +405,57 @@ object UserApps {
|
||||
return urls + listOfNotNull(avatar)
|
||||
}
|
||||
|
||||
internal fun parseFeed(feed: String, body: String): Release? {
|
||||
val top = body.lineSequence().filter { it.isNotEmpty() && !it[0].isWhitespace() && ':' in it }
|
||||
.associate { it.substringBefore(':').trim() to it.substringAfter(':').trim().trim('\'', '"') }
|
||||
val version = top["version"]?.takeIf { it.isNotEmpty() } ?: return null
|
||||
val path = top["path"]?.takeIf { it.endsWith(".AppImage", ignoreCase = true) && '/' !in it && ".." !in it } ?: return null
|
||||
val sha512 = top["sha512"]?.let { runCatching { java.util.Base64.getDecoder().decode(it) }.getOrNull() }
|
||||
?.takeIf { it.size == 64 }?.joinToString("") { "%02x".format(it) } ?: return null
|
||||
val base = feed.substringBeforeLast('/', "").takeIf { it.startsWith("https://") } ?: return null
|
||||
return Release(version, top["releaseDate"].orEmpty(), path, "$base/$path", sha512 = sha512)
|
||||
}
|
||||
|
||||
private fun feedRelease(context: Context, feed: String): Release? =
|
||||
Downloader.downloadString(feed)?.let { parseFeed(feed, it) }
|
||||
|
||||
private fun feedMeta(feed: String, release: Release) =
|
||||
mapOf(FEED to feed, GITHUB_TAG to release.tag, GITHUB_PUBLISHED to release.published, GITHUB_ASSET to release.asset)
|
||||
|
||||
private fun addFromFeed(context: Context, feed: String, name: String?, icon: File?, onProgress: (String, Int) -> Unit): String? {
|
||||
onProgress(context.getString(R.string.user_apps_github_checking, name ?: feed), -1)
|
||||
val release = feedRelease(context, feed) ?: return context.getString(R.string.user_apps_update_failed)
|
||||
return withDownload(context, release, onProgress) { file ->
|
||||
AppImageManager.import(context, file, name ?: release.asset.substringBefore('-'), icon, feedMeta(feed, release)) { onProgress(it, -1) }
|
||||
}
|
||||
}
|
||||
|
||||
internal fun isNewer(release: Release, published: String, installed: String?): Boolean =
|
||||
if (published.isNotEmpty() && release.published.isNotEmpty()) {
|
||||
val feed = runCatching { java.time.Instant.parse(release.published) }.getOrNull()
|
||||
val have = runCatching { java.time.Instant.parse(published) }.getOrNull()
|
||||
if (feed != null && have != null) feed > have else release.published > published
|
||||
} else release.tag != installed
|
||||
|
||||
fun checkUpdate(context: Context, app: App): UpdateCheck {
|
||||
app.feed?.let { feed ->
|
||||
val release = feedRelease(context, feed) ?: return UpdateCheck.Failed(context.getString(R.string.user_apps_update_failed))
|
||||
val published = FileUtils.readString(File(AppImageManager.dir(context, app.key.substringAfter(':')), GITHUB_PUBLISHED))?.trim().orEmpty()
|
||||
return if (isNewer(release, published, app.version)) UpdateCheck.Available(release) else UpdateCheck.Current(app.version ?: release.tag)
|
||||
}
|
||||
val repo = app.repo ?: return UpdateCheck.Failed(context.getString(R.string.user_apps_update_failed))
|
||||
val dir = AppImageManager.dir(context, app.key.substringAfter(':'))
|
||||
val (release, problem) = latestRelease(context, repo, FileUtils.readString(File(dir, GITHUB_ASSET))?.trim()?.takeIf { it.isNotEmpty() })
|
||||
if (release == null) return UpdateCheck.Failed(problem ?: context.getString(R.string.user_apps_update_failed))
|
||||
val published = FileUtils.readString(File(dir, GITHUB_PUBLISHED))?.trim().orEmpty()
|
||||
val newer = if (published.isNotEmpty() && release.published.isNotEmpty()) release.published > published else release.tag != app.version
|
||||
return if (newer) UpdateCheck.Available(release) else UpdateCheck.Current(app.version ?: release.tag)
|
||||
return if (isNewer(release, published, app.version)) UpdateCheck.Available(release) else UpdateCheck.Current(app.version ?: release.tag)
|
||||
}
|
||||
|
||||
fun update(context: Context, app: App, release: Release, onProgress: (String, Int) -> Unit): String? {
|
||||
val repo = app.repo ?: return context.getString(R.string.user_apps_update_failed)
|
||||
val meta = app.feed?.let { feedMeta(it, release) }
|
||||
?: app.repo?.let { githubMeta(it, release) } ?: return context.getString(R.string.user_apps_update_failed)
|
||||
return withDownload(context, release, onProgress) { file ->
|
||||
AppImageManager.replace(context, app.key.substringAfter(':'), file, githubMeta(repo, release)) { onProgress(it, -1) }
|
||||
AppImageManager.replace(context, app.key.substringAfter(':'), file, meta) { onProgress(it, -1) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -38,7 +38,6 @@ object WowAddonCatalog {
|
||||
internal class Cat(val id: String, val name: String, val parents: List<String>)
|
||||
|
||||
private const val WOWI = "https://api.mmoui.com/v3/game/WOW/"
|
||||
private const val CURSEFORGE = "https://www.curseforge.com/wow/search?class=addons"
|
||||
private const val WOWI_FILES = "wowi-filelist.json"
|
||||
internal const val FRESH_MS = 6L * 60 * 60 * 1000
|
||||
|
||||
@@ -209,10 +208,12 @@ object WowAddonCatalog {
|
||||
|
||||
fun categories(context: Context): List<Category> = wowiCategories(context).map { Category(it.id, it.name) }
|
||||
|
||||
internal fun parseWowiDetails(json: String): Pair<String, String?>? {
|
||||
internal class Details(val url: String, val md5: String?, val version: String?)
|
||||
|
||||
internal fun parseWowiDetails(json: String): Details? {
|
||||
val o = JSONArray(json).optJSONObject(0) ?: return null
|
||||
val url = o.optString("UIDownload").ifEmpty { return null }
|
||||
return url to o.optString("UIMD5").ifEmpty { null }
|
||||
return Details(url, o.optString("UIMD5").ifEmpty { null }, o.optString("UIVersion").trim().ifEmpty { null })
|
||||
}
|
||||
|
||||
internal fun isHttps(url: String) = url.startsWith("https://", ignoreCase = true)
|
||||
@@ -220,10 +221,11 @@ object WowAddonCatalog {
|
||||
internal fun md5Matches(file: File, expected: String?): Boolean =
|
||||
expected.isNullOrBlank() || Hashes.md5(file).equals(expected.trim(), ignoreCase = true)
|
||||
|
||||
fun download(context: Context, addon: Addon, dest: File, progress: (Int) -> Unit): File {
|
||||
fun download(context: Context, addon: Addon, dest: File, progress: (Int) -> Unit): String? {
|
||||
val body = StoreNet.get(WOWI + "filedetails/${URLEncoder.encode(addon.id, "UTF-8")}.json", timeoutMs = 30_000)
|
||||
?: throw unreachable(context)
|
||||
val (url, md5) = parseWowiDetails(body) ?: throw IOException(context.getString(R.string.addons_no_file))
|
||||
val details = parseWowiDetails(body) ?: throw IOException(context.getString(R.string.addons_no_file))
|
||||
val url = details.url
|
||||
if (!isHttps(url)) throw IOException(context.getString(R.string.addons_no_file))
|
||||
dest.parentFile?.mkdirs()
|
||||
dest.delete()
|
||||
@@ -232,14 +234,33 @@ object WowAddonCatalog {
|
||||
dest.delete()
|
||||
throw unreachable(context)
|
||||
}
|
||||
if (!md5Matches(dest, md5)) {
|
||||
if (!md5Matches(dest, details.md5)) {
|
||||
dest.delete()
|
||||
throw IOException(context.getString(R.string.selfinst_checksum_mismatch))
|
||||
}
|
||||
progress(100)
|
||||
return dest
|
||||
return details.version
|
||||
}
|
||||
|
||||
internal fun curseForgeUrl(text: String): String =
|
||||
text.trim().let { if (it.isEmpty()) CURSEFORGE else CURSEFORGE + "&search=" + URLEncoder.encode(it, "UTF-8") }
|
||||
internal fun sameVersion(a: String, b: String): Boolean {
|
||||
fun norm(v: String) = v.trim().removePrefix("v").removePrefix("V").trim().lowercase()
|
||||
return norm(a) == norm(b)
|
||||
}
|
||||
|
||||
internal fun findUpdates(entries: List<Entry>, installed: List<WowAddons.Installed>): Map<String, Addon> {
|
||||
val byId = entries.associateBy { it.addon.id }
|
||||
val seen = HashSet<String>()
|
||||
return installed.mapNotNull { item ->
|
||||
val id = item.wowiId ?: return@mapNotNull null
|
||||
val version = item.version ?: return@mapNotNull null
|
||||
val latest = byId[id]?.addon?.takeIf { it.summary.isNotBlank() } ?: return@mapNotNull null
|
||||
if (sameVersion(version, latest.summary) || !seen.add(id)) null else item.name to latest
|
||||
}.toMap()
|
||||
}
|
||||
|
||||
fun updates(context: Context, installed: List<WowAddons.Installed>, target: WowAddons.Target): Map<String, Addon> {
|
||||
if (installed.none { it.wowiId != null }) return emptyMap()
|
||||
val family = client(target).family
|
||||
return runCatching { findUpdates(wowiEntries(context).filter { flavorMatches(it.flavors, family) }, installed) }.getOrDefault(emptyMap())
|
||||
}
|
||||
}
|
||||
@@ -2,15 +2,25 @@ package com.droiddeck.launcher.runtime
|
||||
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import android.content.Context
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreArchiveUnpacker
|
||||
import com.droiddeck.launcher.stores.StoreInstalls
|
||||
import com.droiddeck.launcher.stores.itch.ItchArchives
|
||||
import org.apache.commons.compress.archivers.zip.ZipFile
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.nio.file.FileVisitResult
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.LinkOption
|
||||
import java.nio.file.Path
|
||||
import java.nio.file.SimpleFileVisitor
|
||||
import java.nio.file.attribute.BasicFileAttributes
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
object WowAddons {
|
||||
var imports by mutableIntStateOf(0)
|
||||
@@ -22,6 +32,12 @@ object WowAddons {
|
||||
|
||||
class Addon(val name: String, val root: String)
|
||||
|
||||
class Installed(val name: String, val version: String?, val wowiId: String?)
|
||||
|
||||
class Origin(val id: String, val version: String)
|
||||
|
||||
private const val ORIGINS = ".droiddeck-sources"
|
||||
|
||||
internal const val MAX_EXPANDED_BYTES = 4L * 1024 * 1024 * 1024
|
||||
|
||||
private val SUFFIX = Regex("[-_](standard|mainline|classic|vanilla|tbc|bcc|wrath|wotlkc|cata|mists|forever)$", RegexOption.IGNORE_CASE)
|
||||
@@ -45,53 +61,149 @@ object WowAddons {
|
||||
target.addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") }
|
||||
.map { it.name }.sortedBy { it.lowercase() }
|
||||
|
||||
fun details(target: Target): List<Installed> {
|
||||
val origins = origins(target)
|
||||
return installed(target).map { name ->
|
||||
val toc = toc(File(target.addOns, name))
|
||||
val origin = origins[name]
|
||||
Installed(name, origin?.version ?: toc["Version"], origin?.id ?: toc["X-WoWI-ID"])
|
||||
}
|
||||
}
|
||||
|
||||
internal fun tocFields(text: String): Map<String, String> {
|
||||
val out = LinkedHashMap<String, String>()
|
||||
for (raw in text.lineSequence()) {
|
||||
val line = raw.trim().removePrefix("\uFEFF")
|
||||
if (!line.startsWith("##") || ':' !in line) continue
|
||||
val key = line.removePrefix("##").substringBefore(':').trim()
|
||||
val value = line.substringAfter(':').trim()
|
||||
if (key.isNotEmpty() && value.isNotEmpty() && '@' !in value) out.putIfAbsent(key, value)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
private fun toc(folder: File): Map<String, String> {
|
||||
val tocs = folder.listFiles().orEmpty().filter { it.isFile && it.name.endsWith(".toc", ignoreCase = true) }
|
||||
val main = tocs.firstOrNull { it.name.dropLast(4).equals(folder.name, ignoreCase = true) }
|
||||
?: tocs.firstOrNull { it.name.dropLast(4).replace(SUFFIX, "").equals(folder.name, ignoreCase = true) }
|
||||
?: tocs.minByOrNull { it.name.length } ?: return emptyMap()
|
||||
return runCatching { tocFields(main.readText()) }.getOrDefault(emptyMap())
|
||||
}
|
||||
|
||||
internal fun parseOrigins(text: String): Map<String, Origin> = text.lineSequence().mapNotNull { line ->
|
||||
val parts = line.split('\t')
|
||||
if (parts.size != 3 || parts.any { it.isBlank() }) null else parts[0] to Origin(parts[1], parts[2])
|
||||
}.toMap()
|
||||
|
||||
internal fun formatOrigins(origins: Map<String, Origin>): String =
|
||||
origins.entries.sortedBy { it.key.lowercase() }.joinToString("") { (name, o) -> "$name\t${o.id}\t${o.version.replace(Regex("\\s+"), " ")}\n" }
|
||||
|
||||
private fun originsFile(target: Target) = File(target.addOns, ORIGINS)
|
||||
|
||||
private fun origins(target: Target): Map<String, Origin> =
|
||||
runCatching { parseOrigins(originsFile(target).readText()) }.getOrDefault(emptyMap())
|
||||
|
||||
private val originsLock = Any()
|
||||
|
||||
private fun keepOrigins(target: Target, names: List<String>, origin: Origin?) = synchronized(originsLock) {
|
||||
val current = origins(target)
|
||||
val next = current - names.toSet() + (origin?.let { o -> names.associateWith { o } } ?: emptyMap())
|
||||
if (next != current) {
|
||||
val file = originsFile(target)
|
||||
if (next.isEmpty()) file.delete() else {
|
||||
val temp = File(target.addOns, "$ORIGINS.tmp")
|
||||
temp.writeText(formatOrigins(next))
|
||||
if (!temp.renameTo(file)) {
|
||||
temp.delete()
|
||||
throw IOException("Cannot save $ORIGINS")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun delete(target: Target, name: String) {
|
||||
val folder = target.addOns.listFiles()?.firstOrNull { it.name == name && !it.name.startsWith(".") }
|
||||
?: throw IOException("Cannot find $name")
|
||||
StoreInstalls.deleteTree(folder)
|
||||
if (Files.exists(folder.toPath(), LinkOption.NOFOLLOW_LINKS)) throw IOException("Cannot delete $name")
|
||||
runCatching { keepOrigins(target, listOf(name), null) }
|
||||
imports++
|
||||
}
|
||||
|
||||
fun import(zipFile: File, target: Target): List<String> {
|
||||
fun import(archive: File, target: Target, origin: Origin? = null, context: Context? = null): List<String> {
|
||||
if (context == null || ItchArchives.kind(archive, archive.name) == "zip") return importZip(archive, target, origin)
|
||||
val work = File(File(context.cacheDir, "wowaddons"), "unpack-${System.nanoTime()}")
|
||||
try {
|
||||
if (!work.mkdirs()) throw IOException("Cannot create ${work.path}")
|
||||
val unpacker = StoreArchiveUnpacker(context, AtomicBoolean(), "Addons", R.string.stores_itch_archive, R.string.stores_itch_extract_failed, "addon-unpack")
|
||||
unpacker.work = work
|
||||
unpacker.limit = MAX_EXPANDED_BYTES
|
||||
try {
|
||||
unpacker.unpack(archive, archive.name, { _, _ -> }, {})
|
||||
} catch (_: StoreArchiveUnpacker.TooLarge) {
|
||||
throw TooLarge()
|
||||
}
|
||||
return importFolder(work, target, origin)
|
||||
} finally {
|
||||
StoreInstalls.deleteTree(work)
|
||||
}
|
||||
}
|
||||
|
||||
private class Entry(val path: String, val open: () -> InputStream)
|
||||
|
||||
private fun importZip(zipFile: File, target: Target, origin: Origin?): List<String> =
|
||||
ZipFile.builder().setFile(zipFile).get().use { zip ->
|
||||
val all = zip.entries.toList()
|
||||
if (all.any { it.isUnixSymlink }) return emptyList()
|
||||
val entries = all.filter { clean(it.name) != null }
|
||||
val addons = addons(entries.filter { !it.isDirectory }.mapNotNull { clean(it.name) })
|
||||
if (addons.isEmpty()) return emptyList()
|
||||
val addOns = target.addOns
|
||||
if (!addOns.isDirectory && !addOns.mkdirs()) throw IOException("Cannot create ${addOns.path}")
|
||||
val stage = File(addOns.parentFile, ".addon-import-${System.nanoTime()}")
|
||||
try {
|
||||
val fresh = File(stage, "new")
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
var written = 0L
|
||||
for (entry in entries) {
|
||||
if (entry.isDirectory) continue
|
||||
val path = clean(entry.name) ?: continue
|
||||
val addon = addons.firstOrNull { path.startsWith(it.root) } ?: continue
|
||||
val out = inside(fresh, addon.name + "/" + path.removePrefix(addon.root)) ?: continue
|
||||
out.parentFile?.mkdirs()
|
||||
zip.getInputStream(entry).use { input ->
|
||||
out.outputStream().use { output ->
|
||||
while (true) {
|
||||
val read = input.read(buffer)
|
||||
if (read < 0) break
|
||||
written += read
|
||||
if (written > MAX_EXPANDED_BYTES) throw TooLarge()
|
||||
output.write(buffer, 0, read)
|
||||
}
|
||||
importEntries(all.filter { !it.isDirectory }.mapNotNull { entry -> clean(entry.name)?.let { Entry(it) { zip.getInputStream(entry) } } }, target, origin)
|
||||
}
|
||||
|
||||
internal fun importFolder(folder: File, target: Target, origin: Origin?): List<String> {
|
||||
val entries = ArrayList<Entry>()
|
||||
var links = false
|
||||
Files.walkFileTree(folder.toPath(), object : SimpleFileVisitor<Path>() {
|
||||
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
|
||||
if (!attrs.isRegularFile) links = true
|
||||
else clean(folder.toPath().relativize(file).joinToString("/"))?.let { entries.add(Entry(it) { Files.newInputStream(file, LinkOption.NOFOLLOW_LINKS) }) }
|
||||
return if (links) FileVisitResult.TERMINATE else FileVisitResult.CONTINUE
|
||||
}
|
||||
})
|
||||
return if (links) emptyList() else importEntries(entries, target, origin)
|
||||
}
|
||||
|
||||
private fun importEntries(entries: List<Entry>, target: Target, origin: Origin?): List<String> {
|
||||
val addons = addons(entries.map { it.path })
|
||||
if (addons.isEmpty()) return emptyList()
|
||||
val addOns = target.addOns
|
||||
if (!addOns.isDirectory && !addOns.mkdirs()) throw IOException("Cannot create ${addOns.path}")
|
||||
val stage = File(addOns.parentFile, ".addon-import-${System.nanoTime()}")
|
||||
try {
|
||||
val fresh = File(stage, "new")
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
var written = 0L
|
||||
for (entry in entries) {
|
||||
val addon = addons.firstOrNull { entry.path.startsWith(it.root) } ?: continue
|
||||
val out = inside(fresh, addon.name + "/" + entry.path.removePrefix(addon.root)) ?: continue
|
||||
out.parentFile?.mkdirs()
|
||||
entry.open().use { input ->
|
||||
out.outputStream().use { output ->
|
||||
while (true) {
|
||||
val read = input.read(buffer)
|
||||
if (read < 0) break
|
||||
written += read
|
||||
if (written > MAX_EXPANDED_BYTES) throw TooLarge()
|
||||
output.write(buffer, 0, read)
|
||||
}
|
||||
}
|
||||
}
|
||||
swap(addons.map { File(fresh, it.name) to it.name }, addOns, File(stage, "old").apply { mkdirs() })
|
||||
} finally {
|
||||
StoreInstalls.deleteTree(stage)
|
||||
}
|
||||
imports++
|
||||
return addons.map { it.name }
|
||||
swap(addons.map { File(fresh, it.name) to it.name }, addOns, File(stage, "old").apply { mkdirs() })
|
||||
} finally {
|
||||
StoreInstalls.deleteTree(stage)
|
||||
}
|
||||
runCatching { keepOrigins(target, addons.map { it.name }, origin) }
|
||||
imports++
|
||||
return addons.map { it.name }
|
||||
}
|
||||
|
||||
internal fun addons(files: List<String>): List<Addon> {
|
||||
|
||||
Reference in new issue
Block a user