-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
updater.js
244 lines (210 loc) · 9.18 KB
/
updater.js
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
const axios = require('axios');
const _ = require('lodash');
const fs = require('fs-extra');
const path = require('path');
const log = require('./logger/log.js');
let chalk;
try {
chalk = require("./func/colors.js").colors;
}
catch (e) {
chalk = require("chalk");
}
const sep = path.sep;
const currentConfig = require('./config.json');
const langCode = currentConfig.language;
const execSync = require('child_process').execSync;
let pathLanguageFile = `${process.cwd()}/languages/${langCode}.lang`;
if (!fs.existsSync(pathLanguageFile)) {
log.warn("LANGUAGE", `Can't find language file ${langCode}, using default language file "${path.normalize(`${process.cwd()}/languages/en.lang`)}"`);
pathLanguageFile = `${process.cwd()}/languages/en.lang`;
}
const readLanguage = fs.readFileSync(pathLanguageFile, "utf-8");
const languageData = readLanguage
.split(/\r?\n|\r/)
.filter(line => line && !line.trim().startsWith("#") && !line.trim().startsWith("//") && line != "");
global.language = {};
for (const sentence of languageData) {
const getSeparator = sentence.indexOf('=');
const itemKey = sentence.slice(0, getSeparator).trim();
const itemValue = sentence.slice(getSeparator + 1, sentence.length).trim();
const head = itemKey.slice(0, itemKey.indexOf('.'));
const key = itemKey.replace(head + '.', '');
const value = itemValue.replace(/\\n/gi, '\n');
if (!global.language[head])
global.language[head] = {};
global.language[head][key] = value;
}
function getText(head, key, ...args) {
if (!global.language[head]?.[key])
return `Can't find text: "${head}.${key}"`;
let text = global.language[head][key];
for (let i = args.length - 1; i >= 0; i--)
text = text.replace(new RegExp(`%${i + 1}`, 'g'), args[i]);
return text;
}
const defaultWriteFileSync = fs.writeFileSync;
const defaulCopyFileSync = fs.copyFileSync;
function checkAndAutoCreateFolder(pathFolder) {
const splitPath = path.normalize(pathFolder).split(sep);
let currentPath = '';
for (const i in splitPath) {
currentPath += splitPath[i] + sep;
if (!fs.existsSync(currentPath))
fs.mkdirSync(currentPath);
}
}
// override fs.writeFileSync and fs.copyFileSync to auto create folder if not exist
fs.writeFileSync = function (fullPath, data) {
fullPath = path.normalize(fullPath);
const pathFolder = fullPath.split(sep);
if (pathFolder.length > 1)
pathFolder.pop();
checkAndAutoCreateFolder(pathFolder.join(path.sep));
defaultWriteFileSync(fullPath, data);
};
fs.copyFileSync = function (src, dest) {
src = path.normalize(src);
dest = path.normalize(dest);
const pathFolder = dest.split(sep);
if (pathFolder.length > 1)
pathFolder.pop();
checkAndAutoCreateFolder(pathFolder.join(path.sep));
defaulCopyFileSync(src, dest);
};
(async () => {
const { data: lastCommit } = await axios.get('https://api.github.com/repos/ntkhang03/Goat-Bot-V2/commits/main');
const lastCommitDate = new Date(lastCommit.commit.committer.date);
// if < 5min then stop update and show message
if (new Date().getTime() - lastCommitDate.getTime() < 5 * 60 * 1000) {
const minutes = Math.floor((5 * 60 * 1000 - (new Date().getTime() - lastCommitDate.getTime())) / 1000 / 60);
const seconds = Math.floor((5 * 60 * 1000 - (new Date().getTime() - lastCommitDate.getTime())) / 1000 % 60);
return log.error("ERROR", getText("updater", "updateTooFast", minutes, seconds));
}
const { data: versions } = await axios.get('https://raw.githubusercontent.com/ntkhang03/Goat-Bot-V2/main/versions.json');
const currentVersion = require('./package.json').version;
const indexCurrentVersion = versions.findIndex(v => v.version === currentVersion);
if (indexCurrentVersion === -1)
return log.error("ERROR", getText("updater", "cantFindVersion", chalk.yellow(currentVersion)));
const versionsNeedToUpdate = versions.slice(indexCurrentVersion + 1);
if (versionsNeedToUpdate.length === 0)
return log.info("SUCCESS", getText("updater", "latestVersion"));
fs.writeFileSync(`${process.cwd()}/versions.json`, JSON.stringify(versions, null, 2));
log.info("UPDATE", getText("updater", "newVersions", chalk.yellow(versionsNeedToUpdate.length)));
const createUpdate = {
version: "",
files: {},
deleteFiles: {},
reinstallDependencies: false
};
for (const version of versionsNeedToUpdate) {
for (const filePath in version.files) {
if (["config.json", "configCommands.json"].includes(filePath)) {
if (!createUpdate.files[filePath])
createUpdate.files[filePath] = {};
createUpdate.files[filePath] = {
...createUpdate.files[filePath],
...version.files[filePath]
};
}
else
createUpdate.files[filePath] = version.files[filePath];
if (version.reinstallDependencies)
createUpdate.reinstallDependencies = true;
if (createUpdate.deleteFiles[filePath])
delete createUpdate.deleteFiles[filePath];
for (const filePath in version.deleteFiles)
createUpdate.deleteFiles[filePath] = version.deleteFiles[filePath];
createUpdate.version = version.version;
}
}
const backupsPath = `${process.cwd()}/backups`;
if (!fs.existsSync(backupsPath))
fs.mkdirSync(backupsPath);
const folderBackup = `${backupsPath}/backup_${currentVersion}`;
// find all folders start with "backup_" (these folders are created by updater in old version), and move to backupsPath
const foldersBackup = fs.readdirSync(process.cwd())
.filter(folder => folder.startsWith("backup_") && fs.lstatSync(folder).isDirectory());
for (const folder of foldersBackup)
fs.moveSync(folder, `${backupsPath}/${folder}`);
log.info("UPDATE", `Update to version ${chalk.yellow(createUpdate.version)}`);
const { files, deleteFiles, reinstallDependencies } = createUpdate;
for (const filePath in files) {
const description = files[filePath];
const fullPath = `${process.cwd()}/${filePath}`;
let getFile;
try {
const response = await axios.get(`https://github.com/ntkhang03/Goat-Bot-V2/raw/main/${filePath}`, {
responseType: 'arraybuffer'
});
getFile = response.data;
}
catch (e) {
continue;
}
if (["config.json", "configCommands.json"].includes(filePath)) {
const currentConfig = JSON.parse(fs.readFileSync(fullPath, "utf-8"));
const configValueUpdate = files[filePath];
for (const key in configValueUpdate) {
const value = configValueUpdate[key];
if (typeof value == "string" && value.startsWith("DEFAULT_")) {
const keyOfDefault = value.replace("DEFAULT_", "");
_.set(currentConfig, key, _.get(currentConfig, keyOfDefault));
}
else
_.set(currentConfig, key, value);
}
if (fs.existsSync(fullPath))
fs.copyFileSync(fullPath, `${folderBackup}/${filePath}`);
fs.writeFileSync(fullPath, JSON.stringify(currentConfig, null, 2));
console.log(chalk.bold.blue('[↑]'), filePath);
console.log(chalk.bold.yellow('[!]'), getText("updater", "configChanged", chalk.yellow(filePath)));
}
else {
const contentsSkip = ["DO NOT UPDATE", "SKIP UPDATE", "DO NOT UPDATE THIS FILE"];
const fileExists = fs.existsSync(fullPath);
// if file exists, backup it
if (fileExists)
fs.copyFileSync(fullPath, `${folderBackup}/${filePath}`);
// check first line of file, if it contains any contentsSkip, skip update this file
const firstLine = fileExists ? fs.readFileSync(fullPath, "utf-8").trim().split(/\r?\n|\r/)[0] : "";
const indexSkip = contentsSkip.findIndex(c => firstLine.includes(c));
if (indexSkip !== -1) {
console.log(chalk.bold.yellow('[!]'), getText("updater", "skipFile", chalk.yellow(filePath), chalk.yellow(contentsSkip[indexSkip])));
continue;
}
else {
fs.writeFileSync(fullPath, Buffer.from(getFile));
if (fileExists)
console.log(chalk.bold.blue('[↑]'), `${filePath}:`, chalk.hex('#858585')(typeof description == "string" ? description : typeof description == "object" ? JSON.stringify(description, null, 2) : description));
else
console.log(chalk.bold.green('[+]'), `${filePath}:`, chalk.hex('#858585')(typeof description == "string" ? description : typeof description == "object" ? JSON.stringify(description, null, 2) : description));
}
}
}
for (const filePath in deleteFiles) {
const description = deleteFiles[filePath];
const fullPath = `${process.cwd()}/${filePath}`;
if (fs.existsSync(fullPath)) {
if (fs.lstatSync(fullPath).isDirectory())
fs.removeSync(fullPath);
else {
fs.copyFileSync(fullPath, `${folderBackup}/${filePath}`);
fs.unlinkSync(fullPath);
}
console.log(chalk.bold.red('[-]'), `${filePath}:`, chalk.hex('#858585')(description));
}
}
const { data: packageHTML } = await axios.get("https://github.com/ntkhang03/Goat-Bot-V2/blob/main/package.json");
const json = packageHTML.split('data-target="react-app.embeddedData">')[1].split('</script>')[0];
const packageJSON = JSON.parse(json).payload.blob.rawLines.join('\n');
fs.writeFileSync(`${process.cwd()}/package.json`, JSON.stringify(JSON.parse(packageJSON), null, 2));
log.info("UPDATE", getText("updater", "updateSuccess", !reinstallDependencies ? getText("updater", "restartToApply") : ""));
// npm install
if (reinstallDependencies) {
log.info("UPDATE", getText("updater", "installingPackages"));
execSync("npm install", { stdio: 'inherit' });
log.info("UPDATE", getText("updater", "installSuccess"));
}
log.info("UPDATE", getText("updater", "backupSuccess", chalk.yellow(folderBackup)));
})();