hachem.wtf
aboutsummaryrefslogtreecommitdiff
path: root/lib/modrinth.js
blob: cf0f697bd539ef24b1cb3ebf529bdf85dccc5475 (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
const axios = require("axios")

const MODRINTH_API = "https://api.modrinth.com/v2"

const GetModVersions = async slug =>
{
    try
    {
        const response = await axios.get(`${MODRINTH_API}/project/${slug}/version`)
        return response.data
    }
    catch (err)
    {
        console.error(`[Modrinth] Failed for ${slug}:`, err.message)
        return null
    }
}

const GetLatestVersion = versions =>
{
    if (!versions || !versions.length)
        return null
    return versions.sort((a, b) => new Date(b.date_published) - new Date(a.date_published))[0]
}

const GetCompatibleVersion = (versions, minecraftVersion, loader = null) =>
{
    if (!versions || !versions.length)
        return null

    const compatible = versions.filter(v =>
    {
        const hasVersion = v.game_versions.includes(minecraftVersion)
        const hasLoader = loader ? v.loaders.includes(loader) : true
        return hasVersion && hasLoader
    })

    if (!compatible.length)
        return null

    return compatible.sort((a, b) => new Date(b.date_published) - new Date(a.date_published))[0]
}

const DownloadFile = async (url, destPath) =>
{
    const fs = require("fs-extra")
    
    try
    {
        const response = await axios.get(url, { responseType: "arraybuffer" })
        await fs.writeFile(destPath, response.data)
        return true
    }
    catch (err)
    {
        console.error(`[Download] Failed:`, err.message)
        return false
    }
}

module.exports =
{
    MODRINTH_API,
    GetModVersions,
    GetLatestVersion,
    GetCompatibleVersion,
    DownloadFile
}