summaryrefslogtreecommitdiff
path: root/plugin/src/main/kotlin/moe/nea/archenemy/mojang/DownloadAssets.kt
blob: 335ac3065da59de7cc5b7e2eca47d3e8ed844eff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package moe.nea.archenemy.mojang

import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.decodeFromStream
import moe.nea.archenemy.util.DownloadUtils
import moe.nea.archenemy.util.sharedExtension
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.TaskAction
import java.net.URL
import javax.inject.Inject

abstract class DownloadAssets @Inject constructor(
    @get:Input
    val version: String
) : DefaultTask() {


    init {
        dependsOn(project.sharedExtension.getDownloadVersionMetadataTask(version))
    }

    @Serializable
    data class AssetIndexList(
        val objects: Map<String, AssetIndexFile>
    )

    @Serializable
    data class AssetIndexFile(
        val hash: String,
        val size: Long,
    )

    @Internal
    fun getAssetDir() =
        project.sharedExtension
            .getGlobalCacheDirectory()
            .resolve("assets")

    @Internal
    fun getAssetIndex() =
        project.sharedExtension
            .getDownloadVersionMetadataTask(version)
            .getVersionMetadataNow()
            .assetIndex

    @TaskAction
    fun execute() {
        val manifest =
            project.sharedExtension
                .getDownloadVersionMetadataTask(version)
                .getVersionMetadata()
        val indexFile = getAssetDir()
            .resolve("indexes")
            .resolve(manifest.assetIndex.id + ".json")
        DownloadUtils.downloadFile(URL(manifest.assetIndex.url), manifest.assetIndex.sha1, indexFile)
        val assetIndexList: AssetIndexList = indexFile.inputStream().use(Json::decodeFromStream)
        for ((path, entry) in assetIndexList.objects) {
            downloadAsset(entry)
        }
    }

    private fun downloadAsset(entry: AssetIndexFile) {
        val prefix = entry.hash.substring(0, 2)
        val file = getAssetDir().resolve("objects").resolve(prefix).resolve(entry.hash)
        DownloadUtils.downloadFile(
            URL("https://resources.download.minecraft.net/$prefix/${entry.hash}"),
            entry.hash,
            file
        )
    }
}