-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
72 lines (68 loc) · 2.57 KB
/
main.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
// jshint -W119
let scriptName = 'your_script_name';
let scriptUrl = 'https://your_script_url';
let modulePath = await downloadModule(scriptName, scriptUrl); // jshint ignore:line
if (modulePath != null) {
let importedModule = importModule(modulePath);
await importedModule.main(); // jshint ignore:line
} else {
console.log('Failed to download new module and could not find any local version.');
}
async function downloadModule(scriptName, scriptUrl) {
// returns path of latest module version which is accessible
let fm = FileManager.local();
let scriptPath = module.filename;
let moduleDir = scriptPath.replace(fm.fileName(scriptPath, true), scriptName);
if (fm.fileExists(moduleDir) && !fm.isDirectory(moduleDir)) fm.remove(moduleDir);
if (!fm.fileExists(moduleDir)) fm.createDirectory(moduleDir);
let dayNumber = Math.floor(Date.now() / 1000 / 60 / 60 / 24);
let moduleFilename = dayNumber.toString() + '.js';
let modulePath = fm.joinPath(moduleDir, moduleFilename);
if (fm.fileExists(modulePath)) {
console.log('Module already downlaoded ' + moduleFilename);
return modulePath;
} else {
let [moduleFiles, moduleLatestFile] = getModuleVersions(scriptName);
console.log('Downloading ' + moduleFilename + ' from URL: ' + scriptUrl);
let req = new Request(scriptUrl);
let moduleJs = await req.load().catch(() => {
return null;
});
if (moduleJs) {
fm.write(modulePath, moduleJs);
if (moduleFiles != null) {
moduleFiles.map(x => {
fm.remove(fm.joinPath(moduleDir, x));
});
}
return modulePath;
} else {
console.log('Failed to download new module. Using latest local version: ' + moduleLatestFile);
return (moduleLatestFile != null) ? fm.joinPath(moduleDir, moduleLatestFile) : null;
}
}
}
function getModuleVersions(scriptName) {
// returns all saved module versions and latest version of them
let fm = FileManager.local();
let scriptPath = module.filename;
let moduleDir = scriptPath.replace(fm.fileName(scriptPath, true), scriptName);
let dirContents = fm.listContents(moduleDir);
if (dirContents.length > 0) {
let versions = dirContents.map(x => {
if (x.endsWith('.js')) return parseInt(x.replace('.js', ''));
});
versions.sort(function(a, b) {
return b - a;
});
versions = versions.filter(Boolean);
if (versions.length > 0) {
let moduleFiles = versions.map(x => {
return x + '.js';
});
moduleLatestFile = versions[0] + '.js';
return [moduleFiles, moduleLatestFile];
}
}
return [null, null];
}