aboutsummaryrefslogtreecommitdiff
path: root/build/constants.js
blob: 961e998f48e0962400fdc86ad39ee580f2e9ed95 (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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
"use strict";
/**
 * Fetch and edit constants from the skyblock-constants repo
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.addCollections = exports.addStats = exports.fetchCollections = exports.fetchStats = void 0;
const node_fetch_1 = __importDefault(require("node-fetch"));
const https_1 = require("https");
const node_cache_1 = __importDefault(require("node-cache"));
const httpsAgent = new https_1.Agent({
    keepAlive: true
});
const githubApiBase = 'https://api.github.com';
const owner = 'skyblockstats';
const repo = 'skyblock-constants';
/**
 * Send a request to the GitHub API
 * @param method The HTTP method, for example GET, PUT, POST, etc
 * @param route The route to send the request to
 * @param headers The extra headers
 * @param json The JSON body, only applicable for some types of methods
 */
async function fetchGithubApi(method, route, headers, json) {
    return await node_fetch_1.default(githubApiBase + route, {
        agent: () => httpsAgent,
        body: json ? JSON.stringify(json) : null,
        method,
        headers: Object.assign({
            'Authorization': `token ${process.env.github_token}`
        }, headers),
    });
}
// cache files for an hour
const fileCache = new node_cache_1.default({
    stdTTL: 60 * 60,
    checkperiod: 60,
    useClones: false,
});
/**
 * Fetch a file from skyblock-constants
 * @param path The file path, for example stats.json
 */
async function fetchFile(path) {
    if (fileCache.has(path))
        return fileCache.get(path);
    const r = await fetchGithubApi('GET', `/repos/${owner}/${repo}/contents/${path}`, {
        'Accept': 'application/vnd.github.v3+json',
        'Authorization': undefined
    });
    const data = await r.json();
    const file = {
        path: data.path,
        content: Buffer.from(data.content, data.encoding).toString(),
        sha: data.sha
    };
    fileCache.set(path, file);
    return file;
}
/**
 * Edit a file on skyblock-constants
 * @param file The GithubFile you got from fetchFile
 * @param message The commit message
 * @param newContent The new content in the file
 */
async function editFile(file, message, newContent) {
    const r = await fetchGithubApi('PUT', `/repos/${owner}/${repo}/contents/${file.path}`, { 'Content-Type': 'application/json' }, {
        message: message,
        content: Buffer.from(newContent).toString('base64'),
        sha: file.sha,
        branch: 'main'
    });
    const data = await r.json();
    fileCache.set(file.path, {
        path: data.content.path,
        content: newContent,
        sha: data.content.sha
    });
}
/** Fetch all the known SkyBlock stats as an array of strings */
async function fetchStats() {
    const file = await fetchFile('stats.json');
    try {
        return JSON.parse(file.content);
    }
    catch {
        // probably invalid json, return an empty array
        return [];
    }
}
exports.fetchStats = fetchStats;
/** Fetch all the known SkyBlock collections as an array of strings */
async function fetchCollections() {
    const file = await fetchFile('collections.json');
    try {
        return JSON.parse(file.content);
    }
    catch {
        // probably invalid json, return an empty array
        return [];
    }
}
exports.fetchCollections = fetchCollections;
/** Add stats to skyblock-constants. This has caching so it's fine to call many times */
async function addStats(addingStats) {
    if (addingStats.length === 0)
        return; // no stats provided, just return
    const file = await fetchFile('stats.json');
    if (!file.path)
        return;
    let oldStats;
    try {
        oldStats = JSON.parse(file.content);
    }
    catch {
        // invalid json, set it as an empty array
        oldStats = [];
    }
    const updatedStats = oldStats
        .concat(addingStats)
        // remove duplicates
        .filter((value, index, array) => array.indexOf(value) === index)
        .sort((a, b) => a.localeCompare(b));
    const newStats = updatedStats.filter(value => !oldStats.includes(value));
    // there's not actually any new stats, just return
    if (newStats.length === 0)
        return;
    const commitMessage = newStats.length >= 2 ? `Add ${newStats.length} new stats` : `Add '${newStats[0]}'`;
    await editFile(file, commitMessage, JSON.stringify(updatedStats, null, 2));
}
exports.addStats = addStats;
/** Add stats to skyblock-constants. This has caching so it's fine to call many times */
async function addCollections(addingCollections) {
    if (addingCollections.length === 0)
        return; // no stats provided, just return
    const file = await fetchFile('collections.json');
    if (!file.path)
        return;
    let oldCollections;
    try {
        oldCollections = JSON.parse(file.content);
    }
    catch {
        // invalid json, set it as an empty array
        oldCollections = [];
    }
    const updatedCollections = oldCollections
        .concat(addingCollections)
        // remove duplicates
        .filter((value, index, array) => array.indexOf(value) === index)
        .sort((a, b) => a.localeCompare(b));
    const newCollections = updatedCollections.filter(value => !oldCollections.includes(value));
    // there's not actually any new stats, just return
    if (newCollections.length === 0)
        return;
    const commitMessage = newCollections.length >= 2 ? `Add ${newCollections.length} new collections` : `Add '${newCollections[0]}'`;
    await editFile(file, commitMessage, JSON.stringify(updatedCollections, null, 2));
}
exports.addCollections = addCollections;