assetguard.js 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336
  1. /**
  2. * AssetGuard
  3. *
  4. * This module aims to provide a comprehensive and stable method for processing
  5. * and downloading game assets for the WesterosCraft server. Download meta is
  6. * for several identifiers (categories) is stored inside of an AssetGuard object.
  7. * This meta data is initially empty until one of the module's processing functions
  8. * are called. That function will process the corresponding asset index and validate
  9. * any exisitng local files. If a file is missing or fails validation, it will be
  10. * placed into a download queue (array). This queue is wrapped in a download tracker object
  11. * so that essential information can be cached. The download tracker object is then
  12. * assigned as the value of the identifier in the AssetGuard object. These download
  13. * trackers will remain idle until an async process is started to process them.
  14. *
  15. * Once the async process is started, any enqueued assets will be downloaded. The AssetGuard
  16. * object will emit events throughout the download whose name correspond to the identifier
  17. * being processed. For example, if the 'assets' identifier was being processed, whenever
  18. * the download stream recieves data, the event 'assetsdlprogress' will be emitted off of
  19. * the AssetGuard instance. This can be listened to by external modules allowing for
  20. * categorical tracking of the downloading process.
  21. *
  22. * @module assetguard
  23. */
  24. // Requirements
  25. const AdmZip = require('adm-zip')
  26. const async = require('async')
  27. const child_process = require('child_process')
  28. const crypto = require('crypto')
  29. const EventEmitter = require('events')
  30. const fs = require('fs')
  31. const mkpath = require('mkdirp');
  32. const path = require('path')
  33. const Registry = require('winreg')
  34. const request = require('request')
  35. // Constants
  36. const PLATFORM_MAP = {
  37. win32: '-windows-x64.tar.gz',
  38. darwin: '-macosx-x64.tar.gz',
  39. linux: '-linux-x64.tar.gz'
  40. }
  41. // Classes
  42. /** Class representing a base asset. */
  43. class Asset {
  44. /**
  45. * Create an asset.
  46. *
  47. * @param {any} id The id of the asset.
  48. * @param {string} hash The hash value of the asset.
  49. * @param {number} size The size in bytes of the asset.
  50. * @param {string} from The url where the asset can be found.
  51. * @param {string} to The absolute local file path of the asset.
  52. */
  53. constructor(id, hash, size, from, to){
  54. this.id = id
  55. this.hash = hash
  56. this.size = size
  57. this.from = from
  58. this.to = to
  59. }
  60. }
  61. /** Class representing a mojang library. */
  62. class Library extends Asset {
  63. /**
  64. * Converts the process.platform OS names to match mojang's OS names.
  65. */
  66. static mojangFriendlyOS(){
  67. const opSys = process.platform
  68. if (opSys === 'darwin') {
  69. return 'osx';
  70. } else if (opSys === 'win32'){
  71. return 'windows';
  72. } else if (opSys === 'linux'){
  73. return 'linux';
  74. } else {
  75. return 'unknown_os';
  76. }
  77. }
  78. /**
  79. * Checks whether or not a library is valid for download on a particular OS, following
  80. * the rule format specified in the mojang version data index. If the allow property has
  81. * an OS specified, then the library can ONLY be downloaded on that OS. If the disallow
  82. * property has instead specified an OS, the library can be downloaded on any OS EXCLUDING
  83. * the one specified.
  84. *
  85. * @param {Object} rules The Library's download rules.
  86. * @returns {boolean} True if the Library follows the specified rules, otherwise false.
  87. */
  88. static validateRules(rules){
  89. if(rules == null) return true
  90. let result = true
  91. rules.forEach(function(rule){
  92. const action = rule['action']
  93. const osProp = rule['os']
  94. if(action != null){
  95. if(osProp != null){
  96. const osName = osProp['name']
  97. const osMoj = Library.mojangFriendlyOS()
  98. if(action === 'allow'){
  99. result = osName === osMoj
  100. return
  101. } else if(action === 'disallow'){
  102. result = osName !== osMoj
  103. return
  104. }
  105. }
  106. }
  107. })
  108. return result
  109. }
  110. }
  111. class DistroModule extends Asset {
  112. /**
  113. * Create a DistroModule. This is for processing,
  114. * not equivalent to the module objects in the
  115. * distro index.
  116. *
  117. * @param {any} id The id of the asset.
  118. * @param {string} hash The hash value of the asset.
  119. * @param {number} size The size in bytes of the asset.
  120. * @param {string} from The url where the asset can be found.
  121. * @param {string} to The absolute local file path of the asset.
  122. * @param {string} type The the module type.
  123. */
  124. constructor(id, hash, size, from, to, type){
  125. super(id, hash, size, from, to)
  126. this.type = type
  127. }
  128. }
  129. /**
  130. * Class representing a download tracker. This is used to store meta data
  131. * about a download queue, including the queue itself.
  132. */
  133. class DLTracker {
  134. /**
  135. * Create a DLTracker
  136. *
  137. * @param {Array.<Asset>} dlqueue An array containing assets queued for download.
  138. * @param {number} dlsize The combined size of each asset in the download queue array.
  139. * @param {function(Asset)} callback Optional callback which is called when an asset finishes downloading.
  140. */
  141. constructor(dlqueue, dlsize, callback = null){
  142. this.dlqueue = dlqueue
  143. this.dlsize = dlsize
  144. this.callback = callback
  145. }
  146. }
  147. let distributionData = null
  148. /**
  149. * Central object class used for control flow. This object stores data about
  150. * categories of downloads. Each category is assigned an identifier with a
  151. * DLTracker object as its value. Combined information is also stored, such as
  152. * the total size of all the queued files in each category. This event is used
  153. * to emit events so that external modules can listen into processing done in
  154. * this module.
  155. */
  156. class AssetGuard extends EventEmitter {
  157. /**
  158. * Create an instance of AssetGuard.
  159. * On creation the object's properties are never-null default
  160. * values. Each identifier is resolved to an empty DLTracker.
  161. *
  162. * @param {string} basePath The base path for asset validation (game root).
  163. * @param {string} javaexec The path to a java executable which will be used
  164. * to finalize installation.
  165. */
  166. constructor(basePath, javaexec){
  167. super()
  168. this.totaldlsize = 0
  169. this.progress = 0
  170. this.assets = new DLTracker([], 0)
  171. this.libraries = new DLTracker([], 0)
  172. this.files = new DLTracker([], 0)
  173. this.forge = new DLTracker([], 0)
  174. this.java = new DLTracker([], 0)
  175. this.basePath = basePath
  176. this.javaexec = javaexec
  177. }
  178. // Static Utility Functions
  179. // #region
  180. // Static General Resolve Functions
  181. // #region
  182. /**
  183. * Resolve an artifact id into a path. For example, on windows
  184. * 'net.minecraftforge:forge:1.11.2-13.20.0.2282', '.jar' becomes
  185. * net\minecraftforge\forge\1.11.2-13.20.0.2282\forge-1.11.2-13.20.0.2282.jar
  186. *
  187. * @param {string} artifactid The artifact id string.
  188. * @param {string} extension The extension of the file at the resolved path.
  189. * @returns {string} The resolved relative path from the artifact id.
  190. */
  191. static _resolvePath(artifactid, extension){
  192. let ps = artifactid.split(':')
  193. let cs = ps[0].split('.')
  194. cs.push(ps[1])
  195. cs.push(ps[2])
  196. cs.push(ps[1].concat('-').concat(ps[2]).concat(extension))
  197. return path.join.apply(path, cs)
  198. }
  199. /**
  200. * Resolve an artifact id into a URL. For example,
  201. * 'net.minecraftforge:forge:1.11.2-13.20.0.2282', '.jar' becomes
  202. * net/minecraftforge/forge/1.11.2-13.20.0.2282/forge-1.11.2-13.20.0.2282.jar
  203. *
  204. * @param {string} artifactid The artifact id string.
  205. * @param {string} extension The extension of the file at the resolved url.
  206. * @returns {string} The resolved relative URL from the artifact id.
  207. */
  208. static _resolveURL(artifactid, extension){
  209. let ps = artifactid.split(':')
  210. let cs = ps[0].split('.')
  211. cs.push(ps[1])
  212. cs.push(ps[2])
  213. cs.push(ps[1].concat('-').concat(ps[2]).concat(extension))
  214. return cs.join('/')
  215. }
  216. // #endregion
  217. // Static Hash Validation Functions
  218. // #region
  219. /**
  220. * Calculates the hash for a file using the specified algorithm.
  221. *
  222. * @param {Buffer} buf The buffer containing file data.
  223. * @param {string} algo The hash algorithm.
  224. * @returns {string} The calculated hash in hex.
  225. */
  226. static _calculateHash(buf, algo){
  227. return crypto.createHash(algo).update(buf).digest('hex')
  228. }
  229. /**
  230. * Used to parse a checksums file. This is specifically designed for
  231. * the checksums.sha1 files found inside the forge scala dependencies.
  232. *
  233. * @param {string} content The string content of the checksums file.
  234. * @returns {Object} An object with keys being the file names, and values being the hashes.
  235. */
  236. static _parseChecksumsFile(content){
  237. let finalContent = {}
  238. let lines = content.split('\n')
  239. for(let i=0; i<lines.length; i++){
  240. let bits = lines[i].split(' ')
  241. if(bits[1] == null) {
  242. continue
  243. }
  244. finalContent[bits[1]] = bits[0]
  245. }
  246. return finalContent
  247. }
  248. /**
  249. * Validate that a file exists and matches a given hash value.
  250. *
  251. * @param {string} filePath The path of the file to validate.
  252. * @param {string} algo The hash algorithm to check against.
  253. * @param {string} hash The existing hash to check against.
  254. * @returns {boolean} True if the file exists and calculated hash matches the given hash, otherwise false.
  255. */
  256. static _validateLocal(filePath, algo, hash){
  257. if(fs.existsSync(filePath)){
  258. //No hash provided, have to assume it's good.
  259. if(hash == null){
  260. return true
  261. }
  262. let fileName = path.basename(filePath)
  263. let buf = fs.readFileSync(filePath)
  264. let calcdhash = AssetGuard._calculateHash(buf, algo)
  265. return calcdhash === hash
  266. }
  267. return false;
  268. }
  269. /**
  270. * Validates a file in the style used by forge's version index.
  271. *
  272. * @param {string} filePath The path of the file to validate.
  273. * @param {Array.<string>} checksums The checksums listed in the forge version index.
  274. * @returns {boolean} True if the file exists and the hashes match, otherwise false.
  275. */
  276. static _validateForgeChecksum(filePath, checksums){
  277. if(fs.existsSync(filePath)){
  278. if(checksums == null || checksums.length === 0){
  279. return true
  280. }
  281. let buf = fs.readFileSync(filePath)
  282. let calcdhash = AssetGuard._calculateHash(buf, 'sha1')
  283. let valid = checksums.includes(calcdhash)
  284. if(!valid && filePath.endsWith('.jar')){
  285. valid = AssetGuard._validateForgeJar(filePath, checksums)
  286. }
  287. return valid
  288. }
  289. return false
  290. }
  291. /**
  292. * Validates a forge jar file dependency who declares a checksums.sha1 file.
  293. * This can be an expensive task as it usually requires that we calculate thousands
  294. * of hashes.
  295. *
  296. * @param {Buffer} buf The buffer of the jar file.
  297. * @param {Array.<string>} checksums The checksums listed in the forge version index.
  298. * @returns {boolean} True if all hashes declared in the checksums.sha1 file match the actual hashes.
  299. */
  300. static _validateForgeJar(buf, checksums){
  301. // Double pass method was the quickest I found. I tried a version where we store data
  302. // to only require a single pass, plus some quick cleanup but that seemed to take slightly more time.
  303. const hashes = {}
  304. let expected = {}
  305. const zip = new AdmZip(buf)
  306. const zipEntries = zip.getEntries()
  307. //First pass
  308. for(let i=0; i<zipEntries.length; i++){
  309. let entry = zipEntries[i]
  310. if(entry.entryName === 'checksums.sha1'){
  311. expected = AssetGuard._parseChecksumsFile(zip.readAsText(entry))
  312. }
  313. hashes[entry.entryName] = AssetGuard._calculateHash(entry.getData(), 'sha1')
  314. }
  315. if(!checksums.includes(hashes['checksums.sha1'])){
  316. return false
  317. }
  318. //Check against expected
  319. const expectedEntries = Object.keys(expected)
  320. for(let i=0; i<expectedEntries.length; i++){
  321. if(expected[expectedEntries[i]] !== hashes[expectedEntries[i]]){
  322. return false
  323. }
  324. }
  325. return true
  326. }
  327. // #endregion
  328. // Static Distribution Index Functions
  329. // #region
  330. /**
  331. * Statically retrieve the distribution data.
  332. *
  333. * @param {string} basePath The base path for asset validation (game root).
  334. * @param {boolean} cached Optional. False if the distro should be freshly downloaded, else
  335. * a cached copy will be returned.
  336. * @returns {Promise.<Object>} A promise which resolves to the distribution data object.
  337. */
  338. static retrieveDistributionData(basePath, cached = true){
  339. return new Promise(function(fulfill, reject){
  340. if(!cached || distributionData == null){
  341. // TODO Download file from upstream.
  342. //const distroURL = 'http://mc.westeroscraft.com/WesterosCraftLauncher/westeroscraft.json'
  343. // TODO Save file to path.join(basePath, 'westeroscraft.json')
  344. // TODO Fulfill with JSON.parse()
  345. // Workaround while file is not hosted.
  346. fs.readFile(path.join(__dirname, '..', 'westeroscraft.json'), 'utf-8', (err, data) => {
  347. distributionData = JSON.parse(data)
  348. fulfill(distributionData)
  349. })
  350. } else {
  351. fulfill(distributionData)
  352. }
  353. })
  354. }
  355. /**
  356. * Statically retrieve the distribution data.
  357. *
  358. * @param {string} basePath The base path for asset validation (game root).
  359. * @param {boolean} cached Optional. False if the distro should be freshly downloaded, else
  360. * a cached copy will be returned.
  361. * @returns {Object} The distribution data object.
  362. */
  363. static retrieveDistributionDataSync(basePath, cached = true){
  364. if(!cached || distributionData == null){
  365. distributionData = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'westeroscraft.json'), 'utf-8'))
  366. }
  367. return distributionData
  368. }
  369. /**
  370. * Resolve the default selected server from the distribution index.
  371. *
  372. * @param {string} basePath The base path for asset validation (game root).
  373. * @returns {Object} An object resolving to the default selected server.
  374. */
  375. static resolveSelectedServer(basePath){
  376. const distro = AssetGuard.retrieveDistributionDataSync(basePath)
  377. const servers = distro.servers
  378. for(let i=0; i<servers.length; i++){
  379. if(servers[i].default_selected){
  380. return servers[i].id
  381. }
  382. }
  383. // If no server declares default_selected, default to the first one declared.
  384. return (servers.length > 0) ? servers[0].id : null
  385. }
  386. /**
  387. * Gets a server from the distro index which maches the provided ID.
  388. * Returns null if the ID could not be found or the distro index has
  389. * not yet been loaded.
  390. *
  391. * @param {string} basePath The base path for asset validation (game root).
  392. * @param {string} serverID The id of the server to retrieve.
  393. * @returns {Object} The server object whose id matches the parameter.
  394. */
  395. static getServerById(basePath, serverID){
  396. if(distributionData == null){
  397. AssetGuard.retrieveDistributionDataSync(basePath, false)
  398. }
  399. const servers = distributionData.servers
  400. let serv = null
  401. for(let i=0; i<servers.length; i++){
  402. if(servers[i].id === serverID){
  403. serv = servers[i]
  404. }
  405. }
  406. return serv
  407. }
  408. // #endregion
  409. // Miscellaneous Static Functions
  410. // #region
  411. /**
  412. * Extracts and unpacks a file from .pack.xz format.
  413. *
  414. * @param {Array.<string>} filePaths The paths of the files to be extracted and unpacked.
  415. * @returns {Promise.<void>} An empty promise to indicate the extraction has completed.
  416. */
  417. static _extractPackXZ(filePaths, javaExecutable){
  418. return new Promise(function(fulfill, reject){
  419. const libPath = path.join(__dirname, '..', 'libraries', 'java', 'PackXZExtract.jar')
  420. const filePath = filePaths.join(',')
  421. const child = child_process.spawn(javaExecutable, ['-jar', libPath, '-packxz', filePath])
  422. child.stdout.on('data', (data) => {
  423. //console.log('PackXZExtract:', data.toString('utf8'))
  424. })
  425. child.stderr.on('data', (data) => {
  426. //console.log('PackXZExtract:', data.toString('utf8'))
  427. })
  428. child.on('close', (code, signal) => {
  429. //console.log('PackXZExtract: Exited with code', code)
  430. fulfill()
  431. })
  432. })
  433. }
  434. /**
  435. * Function which finalizes the forge installation process. This creates a 'version'
  436. * instance for forge and saves its version.json file into that instance. If that
  437. * instance already exists, the contents of the version.json file are read and returned
  438. * in a promise.
  439. *
  440. * @param {Asset} asset The Asset object representing Forge.
  441. * @param {string} basePath Base path for asset validation (game root).
  442. * @returns {Promise.<Object>} A promise which resolves to the contents of forge's version.json.
  443. */
  444. static _finalizeForgeAsset(asset, basePath){
  445. return new Promise(function(fulfill, reject){
  446. fs.readFile(asset.to, (err, data) => {
  447. const zip = new AdmZip(data)
  448. const zipEntries = zip.getEntries()
  449. for(let i=0; i<zipEntries.length; i++){
  450. if(zipEntries[i].entryName === 'version.json'){
  451. const forgeVersion = JSON.parse(zip.readAsText(zipEntries[i]))
  452. const versionPath = path.join(basePath, 'versions', forgeVersion.id)
  453. const versionFile = path.join(versionPath, forgeVersion.id + '.json')
  454. if(!fs.existsSync(versionFile)){
  455. mkpath.sync(versionPath)
  456. fs.writeFileSync(path.join(versionPath, forgeVersion.id + '.json'), zipEntries[i].getData())
  457. fulfill(forgeVersion)
  458. } else {
  459. //Read the saved file to allow for user modifications.
  460. fulfill(JSON.parse(fs.readFileSync(versionFile, 'utf-8')))
  461. }
  462. return
  463. }
  464. }
  465. //We didn't find forge's version.json.
  466. reject('Unable to finalize Forge processing, version.json not found! Has forge changed their format?')
  467. })
  468. })
  469. }
  470. // #endregion
  471. // Static Java Utility
  472. // #region
  473. /**
  474. * @typedef OracleJREData
  475. * @property {string} uri The base uri of the JRE.
  476. * @property {{major: string, update: string, build: string}} version Object containing version information.
  477. */
  478. /**
  479. * Resolves the latest version of Oracle's JRE and parses its download link.
  480. *
  481. * @returns {Promise.<OracleJREData>} Promise which resolved to an object containing the JRE download data.
  482. */
  483. static _latestJREOracle(){
  484. const url = 'http://www.oracle.com/technetwork/java/javase/downloads/jre8-downloads-2133155.html'
  485. const regex = /http:\/\/.+?(?=\/java)\/java\/jdk\/([0-9]+u[0-9]+)-(b[0-9]+)\/([a-f0-9]{32})?\/jre-\1/
  486. return new Promise((resolve, reject) => {
  487. request(url, (err, resp, body) => {
  488. if(!err){
  489. const arr = body.match(regex)
  490. const verSplit = arr[1].split('u')
  491. resolve({
  492. uri: arr[0],
  493. version: {
  494. major: verSplit[0],
  495. update: verSplit[1],
  496. build: arr[2]
  497. }
  498. })
  499. } else {
  500. resolve(null)
  501. }
  502. })
  503. })
  504. }
  505. /**
  506. * Validates that a Java binary is at least 64 bit. This makes use of the non-standard
  507. * command line option -XshowSettings:properties. The output of this contains a property,
  508. * sun.arch.data.model = ARCH, in which ARCH is either 32 or 64. This option is supported
  509. * in Java 8 and 9. Since this is a non-standard option. This will resolve to true if
  510. * the function's code throws errors. That would indicate that the option is changed or
  511. * removed.
  512. *
  513. * @param {string} binaryPath Path to the root of the java binary we wish to validate.
  514. *
  515. * @returns {Promise.<boolean>} Resolves to false only if the test is successful and the result
  516. * is less than 64.
  517. */
  518. static _validateJavaBinary(binaryPath){
  519. return new Promise((resolve, reject) => {
  520. const fBp = path.join(binaryPath, 'bin', 'java.exe')
  521. if(fs.existsSync(fBp)){
  522. child_process.exec('"' + fBp + '" -XshowSettings:properties', (err, stdout, stderr) => {
  523. try {
  524. // Output is stored in stderr?
  525. const res = stderr
  526. const props = res.split('\n')
  527. for(let i=0; i<props.length; i++){
  528. if(props[i].indexOf('sun.arch.data.model') > -1){
  529. let arch = props[i].split('=')[1].trim()
  530. console.log(props[i].trim() + ' for ' + binaryPath)
  531. resolve(parseInt(arch) >= 64)
  532. }
  533. }
  534. // sun.arch.data.model not found?
  535. // Disregard this test.
  536. resolve(true)
  537. } catch (err){
  538. // Output format might have changed, validation cannot be completed.
  539. // Disregard this test in that case.
  540. resolve(true)
  541. }
  542. })
  543. } else {
  544. resolve(false)
  545. }
  546. })
  547. }
  548. /**
  549. * Checks for the presence of the environment variable JAVA_HOME. If it exits, we will check
  550. * to see if the value points to a path which exists. If the path exits, the path is returned.
  551. *
  552. * @returns {string} The path defined by JAVA_HOME, if it exists. Otherwise null.
  553. */
  554. static _scanJavaHome(){
  555. const jHome = process.env.JAVA_HOME
  556. try {
  557. let res = fs.existsSync(jHome)
  558. return res ? jHome : null
  559. } catch (err) {
  560. // Malformed JAVA_HOME property.
  561. return null
  562. }
  563. }
  564. /**
  565. * Scans the registry for 64-bit Java entries. The paths of each entry are added to
  566. * a set and returned. Currently, only Java 8 (1.8) is supported.
  567. *
  568. * @returns {Promise.<Set.<string>>} A promise which resolves to a set of 64-bit Java root
  569. * paths found in the registry.
  570. */
  571. static _scanRegistry(){
  572. return new Promise((resolve, reject) => {
  573. // Keys for Java v9.0.0 and later:
  574. // 'SOFTWARE\\JavaSoft\\JRE'
  575. // 'SOFTWARE\\JavaSoft\\JDK'
  576. // Forge does not yet support Java 9, therefore we do not.
  577. let cbTracker = 0
  578. let cbAcc = 0
  579. // Keys for Java 1.8 and prior:
  580. const regKeys = [
  581. '\\SOFTWARE\\JavaSoft\\Java Runtime Environment',
  582. '\\SOFTWARE\\JavaSoft\\Java Development Kit'
  583. ]
  584. const candidates = new Set()
  585. for(let i=0; i<regKeys.length; i++){
  586. const key = new Registry({
  587. hive: Registry.HKLM,
  588. key: regKeys[i],
  589. arch: 'x64'
  590. })
  591. key.keyExists((err, exists) => {
  592. if(exists) {
  593. key.keys((err, javaVers) => {
  594. if(err){
  595. console.error(err)
  596. if(i === regKeys.length-1 && cbAcc === cbTracker){
  597. resolve(candidates)
  598. }
  599. } else {
  600. cbTracker += javaVers.length
  601. if(i === regKeys.length-1 && cbTracker === cbAcc){
  602. resolve(candidates)
  603. } else {
  604. for(let j=0; j<javaVers.length; j++){
  605. const javaVer = javaVers[j]
  606. const vKey = javaVer.key.substring(javaVer.key.lastIndexOf('\\')+1)
  607. // Only Java 8 is supported currently.
  608. if(parseFloat(vKey) === 1.8){
  609. javaVer.get('JavaHome', (err, res) => {
  610. const jHome = res.value
  611. if(jHome.indexOf('(x86)') === -1){
  612. candidates.add(jHome)
  613. }
  614. cbAcc++
  615. if(i === regKeys.length-1 && cbAcc === cbTracker){
  616. resolve(candidates)
  617. }
  618. })
  619. } else {
  620. cbAcc++
  621. if(i === regKeys.length-1 && cbAcc === cbTracker){
  622. resolve(candidates)
  623. }
  624. }
  625. }
  626. }
  627. }
  628. })
  629. } else {
  630. if(i === regKeys.length-1 && cbAcc === cbTracker){
  631. resolve(candidates)
  632. }
  633. }
  634. })
  635. }
  636. })
  637. }
  638. /**
  639. * Attempts to find a valid x64 installation of Java on Windows machines.
  640. * Possible paths will be pulled from the registry and the JAVA_HOME environment
  641. * variable. The paths will be sorted with higher versions preceeding lower, and
  642. * JREs preceeding JDKs. The binaries at the sorted paths will then be validated.
  643. * The first validated is returned.
  644. *
  645. * Higher versions > Lower versions
  646. * If versions are equal, JRE > JDK.
  647. *
  648. * @returns {string} The root path of a valid x64 Java installation. If none are
  649. * found, null is returned.
  650. */
  651. static async _win32JavaValidate(){
  652. // Get possible paths from the registry.
  653. const pathSet = await AssetGuard._scanRegistry()
  654. console.log(Array.from(pathSet)) // DEBUGGING
  655. // Validate JAVA_HOME
  656. const jHome = AssetGuard._scanJavaHome()
  657. if(jHome != null && jHome.indexOf('(x86)') === -1){
  658. pathSet.add(jHome)
  659. }
  660. // Convert path set to an array for processing.
  661. let pathArr = Array.from(pathSet)
  662. console.log(pathArr) // DEBUGGING
  663. // Sorts array. Higher version numbers preceed lower. JRE preceeds JDK.
  664. pathArr = pathArr.sort((a, b) => {
  665. // Note that Java 9+ uses semver and that will need to be accounted for in
  666. // the future.
  667. const aVer = parseInt(a.split('_')[1])
  668. const bVer = parseInt(b.split('_')[1])
  669. if(bVer === aVer){
  670. return a.indexOf('jdk') > -1 ? 1 : 0
  671. } else {
  672. return bVer - aVer
  673. }
  674. })
  675. console.log(pathArr) // DEBUGGING
  676. // Validate that the binary is actually x64.
  677. for(let i=0; i<pathArr.length; i++) {
  678. let res = await AssetGuard._validateJavaBinary(pathArr[i])
  679. if(res){
  680. return pathArr[i]
  681. }
  682. }
  683. // No suitable candidates found.
  684. return null;
  685. }
  686. /**
  687. * WIP -> get a valid x64 Java path on macOS.
  688. */
  689. static async _darwinJavaValidate(){
  690. return null
  691. }
  692. /**
  693. * WIP -> get a valid x64 Java path on linux.
  694. */
  695. static async _linuxJavaValidate(){
  696. return null
  697. }
  698. static async validateJava(){
  699. return await AssetGuard['_' + process.platform + 'JavaValidate']()
  700. }
  701. // #endregion
  702. // #endregion
  703. // Validation Functions
  704. // #region
  705. /**
  706. * Loads the version data for a given minecraft version.
  707. *
  708. * @param {string} version The game version for which to load the index data.
  709. * @param {boolean} force Optional. If true, the version index will be downloaded even if it exists locally. Defaults to false.
  710. * @returns {Promise.<Object>} Promise which resolves to the version data object.
  711. */
  712. loadVersionData(version, force = false){
  713. const self = this
  714. return new Promise(function(fulfill, reject){
  715. const name = version + '.json'
  716. const url = 'https://s3.amazonaws.com/Minecraft.Download/versions/' + version + '/' + name
  717. const versionPath = path.join(self.basePath, 'versions', version)
  718. const versionFile = path.join(versionPath, name)
  719. if(!fs.existsSync(versionFile) || force){
  720. //This download will never be tracked as it's essential and trivial.
  721. request.head(url, function(err, res, body){
  722. console.log('Preparing download of ' + version + ' assets.')
  723. mkpath.sync(versionPath)
  724. const stream = request(url).pipe(fs.createWriteStream(versionFile))
  725. stream.on('finish', function(){
  726. fulfill(JSON.parse(fs.readFileSync(versionFile)))
  727. })
  728. })
  729. } else {
  730. fulfill(JSON.parse(fs.readFileSync(versionFile)))
  731. }
  732. })
  733. }
  734. loadMojangLauncherData(){
  735. //https://launchermeta.mojang.com/mc/launcher.json
  736. }
  737. // Asset (Category=''') Validation Functions
  738. // #region
  739. /**
  740. * Public asset validation function. This function will handle the validation of assets.
  741. * It will parse the asset index specified in the version data, analyzing each
  742. * asset entry. In this analysis it will check to see if the local file exists and is valid.
  743. * If not, it will be added to the download queue for the 'assets' identifier.
  744. *
  745. * @param {Object} versionData The version data for the assets.
  746. * @param {boolean} force Optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  747. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  748. */
  749. validateAssets(versionData, force = false){
  750. const self = this
  751. return new Promise(function(fulfill, reject){
  752. self._assetChainIndexData(versionData, force).then(() => {
  753. fulfill()
  754. })
  755. })
  756. }
  757. //Chain the asset tasks to provide full async. The below functions are private.
  758. /**
  759. * Private function used to chain the asset validation process. This function retrieves
  760. * the index data.
  761. * @param {Object} versionData
  762. * @param {boolean} force
  763. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  764. */
  765. _assetChainIndexData(versionData, force = false){
  766. const self = this
  767. return new Promise(function(fulfill, reject){
  768. //Asset index constants.
  769. const assetIndex = versionData.assetIndex
  770. const name = assetIndex.id + '.json'
  771. const indexPath = path.join(self.basePath, 'assets', 'indexes')
  772. const assetIndexLoc = path.join(indexPath, name)
  773. let data = null
  774. if(!fs.existsSync(assetIndexLoc) || force){
  775. console.log('Downloading ' + versionData.id + ' asset index.')
  776. mkpath.sync(indexPath)
  777. const stream = request(assetIndex.url).pipe(fs.createWriteStream(assetIndexLoc))
  778. stream.on('finish', function() {
  779. data = JSON.parse(fs.readFileSync(assetIndexLoc, 'utf-8'))
  780. self._assetChainValidateAssets(versionData, data).then(() => {
  781. fulfill()
  782. })
  783. })
  784. } else {
  785. data = JSON.parse(fs.readFileSync(assetIndexLoc, 'utf-8'))
  786. self._assetChainValidateAssets(versionData, data).then(() => {
  787. fulfill()
  788. })
  789. }
  790. })
  791. }
  792. /**
  793. * Private function used to chain the asset validation process. This function processes
  794. * the assets and enqueues missing or invalid files.
  795. * @param {Object} versionData
  796. * @param {boolean} force
  797. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  798. */
  799. _assetChainValidateAssets(versionData, indexData){
  800. const self = this
  801. return new Promise(function(fulfill, reject){
  802. //Asset constants
  803. const resourceURL = 'http://resources.download.minecraft.net/'
  804. const localPath = path.join(self.basePath, 'assets')
  805. const indexPath = path.join(localPath, 'indexes')
  806. const objectPath = path.join(localPath, 'objects')
  807. const assetDlQueue = []
  808. let dlSize = 0;
  809. //const objKeys = Object.keys(data.objects)
  810. async.forEachOfLimit(indexData.objects, 10, function(value, key, cb){
  811. const hash = value.hash
  812. const assetName = path.join(hash.substring(0, 2), hash)
  813. const urlName = hash.substring(0, 2) + "/" + hash
  814. const ast = new Asset(key, hash, String(value.size), resourceURL + urlName, path.join(objectPath, assetName))
  815. if(!AssetGuard._validateLocal(ast.to, 'sha1', ast.hash)){
  816. dlSize += (ast.size*1)
  817. assetDlQueue.push(ast)
  818. }
  819. cb()
  820. }, function(err){
  821. self.assets = new DLTracker(assetDlQueue, dlSize)
  822. fulfill()
  823. })
  824. })
  825. }
  826. // #endregion
  827. // Library (Category=''') Validation Functions
  828. // #region
  829. /**
  830. * Public library validation function. This function will handle the validation of libraries.
  831. * It will parse the version data, analyzing each library entry. In this analysis, it will
  832. * check to see if the local file exists and is valid. If not, it will be added to the download
  833. * queue for the 'libraries' identifier.
  834. *
  835. * @param {Object} versionData The version data for the assets.
  836. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  837. */
  838. validateLibraries(versionData){
  839. const self = this
  840. return new Promise(function(fulfill, reject){
  841. const libArr = versionData.libraries
  842. const libPath = path.join(self.basePath, 'libraries')
  843. const libDlQueue = []
  844. let dlSize = 0
  845. //Check validity of each library. If the hashs don't match, download the library.
  846. async.eachLimit(libArr, 5, function(lib, cb){
  847. if(Library.validateRules(lib.rules)){
  848. let artifact = (lib.natives == null) ? lib.downloads.artifact : lib.downloads.classifiers[lib.natives[Library.mojangFriendlyOS()]]
  849. const libItm = new Library(lib.name, artifact.sha1, artifact.size, artifact.url, path.join(libPath, artifact.path))
  850. if(!AssetGuard._validateLocal(libItm.to, 'sha1', libItm.hash)){
  851. dlSize += (libItm.size*1)
  852. libDlQueue.push(libItm)
  853. }
  854. }
  855. cb()
  856. }, function(err){
  857. self.libraries = new DLTracker(libDlQueue, dlSize)
  858. fulfill()
  859. })
  860. })
  861. }
  862. // #endregion
  863. // Miscellaneous (Category=files) Validation Functions
  864. // #region
  865. /**
  866. * Public miscellaneous mojang file validation function. These files will be enqueued under
  867. * the 'files' identifier.
  868. *
  869. * @param {Object} versionData The version data for the assets.
  870. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  871. */
  872. validateMiscellaneous(versionData){
  873. const self = this
  874. return new Promise(async function(fulfill, reject){
  875. await self.validateClient(versionData)
  876. await self.validateLogConfig(versionData)
  877. fulfill()
  878. })
  879. }
  880. /**
  881. * Validate client file - artifact renamed from client.jar to '{version}'.jar.
  882. *
  883. * @param {Object} versionData The version data for the assets.
  884. * @param {boolean} force Optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  885. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  886. */
  887. validateClient(versionData, force = false){
  888. const self = this
  889. return new Promise(function(fulfill, reject){
  890. const clientData = versionData.downloads.client
  891. const version = versionData.id
  892. const targetPath = path.join(self.basePath, 'versions', version)
  893. const targetFile = version + '.jar'
  894. let client = new Asset(version + ' client', clientData.sha1, clientData.size, clientData.url, path.join(targetPath, targetFile))
  895. if(!AssetGuard._validateLocal(client.to, 'sha1', client.hash) || force){
  896. self.files.dlqueue.push(client)
  897. self.files.dlsize += client.size*1
  898. fulfill()
  899. } else {
  900. fulfill()
  901. }
  902. })
  903. }
  904. /**
  905. * Validate log config.
  906. *
  907. * @param {Object} versionData The version data for the assets.
  908. * @param {boolean} force Optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  909. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  910. */
  911. validateLogConfig(versionData){
  912. const self = this
  913. return new Promise(function(fulfill, reject){
  914. const client = versionData.logging.client
  915. const file = client.file
  916. const targetPath = path.join(self.basePath, 'assets', 'log_configs')
  917. let logConfig = new Asset(file.id, file.sha1, file.size, file.url, path.join(targetPath, file.id))
  918. if(!AssetGuard._validateLocal(logConfig.to, 'sha1', logConfig.hash)){
  919. self.files.dlqueue.push(logConfig)
  920. self.files.dlsize += logConfig.size*1
  921. fulfill()
  922. } else {
  923. fulfill()
  924. }
  925. })
  926. }
  927. // #endregion
  928. // Distribution (Category=forge) Validation Functions
  929. // #region
  930. /**
  931. * Validate the distribution.
  932. *
  933. * @param {string} serverpackid The id of the server to validate.
  934. * @returns {Promise.<Object>} A promise which resolves to the server distribution object.
  935. */
  936. validateDistribution(serverpackid){
  937. const self = this
  938. return new Promise(function(fulfill, reject){
  939. AssetGuard.retrieveDistributionData(self.basePath, false).then((value) => {
  940. /*const servers = value.servers
  941. let serv = null
  942. for(let i=0; i<servers.length; i++){
  943. if(servers[i].id === serverpackid){
  944. serv = servers[i]
  945. break
  946. }
  947. }*/
  948. const serv = AssetGuard.getServerById(self.basePath, serverpackid)
  949. if(serv == null) {
  950. console.error('Invalid server pack id:', serverpackid)
  951. }
  952. self.forge = self._parseDistroModules(serv.modules, serv.mc_version)
  953. //Correct our workaround here.
  954. let decompressqueue = self.forge.callback
  955. self.forge.callback = function(asset){
  956. if(asset.to.toLowerCase().endsWith('.pack.xz')){
  957. AssetGuard._extractPackXZ([asset.to], self.javaexec)
  958. }
  959. if(asset.type === 'forge-hosted' || asset.type === 'forge'){
  960. AssetGuard._finalizeForgeAsset(asset, self.basePath)
  961. }
  962. }
  963. fulfill(serv)
  964. })
  965. })
  966. }
  967. /*//TODO The file should be hosted, the following code is for local testing.
  968. _chainValidateDistributionIndex(basePath){
  969. return new Promise(function(fulfill, reject){
  970. //const distroURL = 'http://mc.westeroscraft.com/WesterosCraftLauncher/westeroscraft.json'
  971. //const targetFile = path.join(basePath, 'westeroscraft.json')
  972. //TEMP WORKAROUND TO TEST WHILE THIS IS NOT HOSTED
  973. fs.readFile(path.join(__dirname, '..', 'westeroscraft.json'), 'utf-8', (err, data) => {
  974. fulfill(JSON.parse(data))
  975. })
  976. })
  977. }*/
  978. _parseDistroModules(modules, version){
  979. let alist = []
  980. let asize = 0;
  981. //This may be removed soon, considering the most efficient way to extract.
  982. let decompressqueue = []
  983. for(let i=0; i<modules.length; i++){
  984. let ob = modules[i]
  985. let obType = ob.type
  986. let obArtifact = ob.artifact
  987. let obPath = obArtifact.path == null ? AssetGuard._resolvePath(ob.id, obArtifact.extension) : obArtifact.path
  988. switch(obType){
  989. case 'forge-hosted':
  990. case 'forge':
  991. case 'library':
  992. obPath = path.join(this.basePath, 'libraries', obPath)
  993. break
  994. case 'forgemod':
  995. //obPath = path.join(this.basePath, 'mods', obPath)
  996. obPath = path.join(this.basePath, 'modstore', obPath)
  997. break
  998. case 'litemod':
  999. //obPath = path.join(this.basePath, 'mods', version, obPath)
  1000. obPath = path.join(this.basePath, 'modstore', obPath)
  1001. break
  1002. case 'file':
  1003. default:
  1004. obPath = path.join(this.basePath, obPath)
  1005. }
  1006. let artifact = new DistroModule(ob.id, obArtifact.MD5, obArtifact.size, obArtifact.url, obPath, obType)
  1007. const validationPath = obPath.toLowerCase().endsWith('.pack.xz') ? obPath.substring(0, obPath.toLowerCase().lastIndexOf('.pack.xz')) : obPath
  1008. if(!AssetGuard._validateLocal(validationPath, 'MD5', artifact.hash)){
  1009. asize += artifact.size*1
  1010. alist.push(artifact)
  1011. if(validationPath !== obPath) decompressqueue.push(obPath)
  1012. }
  1013. //Recursively process the submodules then combine the results.
  1014. if(ob.sub_modules != null){
  1015. let dltrack = this._parseDistroModules(ob.sub_modules, version)
  1016. asize += dltrack.dlsize*1
  1017. alist = alist.concat(dltrack.dlqueue)
  1018. decompressqueue = decompressqueue.concat(dltrack.callback)
  1019. }
  1020. }
  1021. //Since we have no callback at this point, we use this value to store the decompressqueue.
  1022. return new DLTracker(alist, asize, decompressqueue)
  1023. }
  1024. /**
  1025. * Loads Forge's version.json data into memory for the specified server id.
  1026. *
  1027. * @param {string} serverpack The id of the server to load Forge data for.
  1028. * @returns {Promise.<Object>} A promise which resolves to Forge's version.json data.
  1029. */
  1030. loadForgeData(serverpack){
  1031. const self = this
  1032. return new Promise(async function(fulfill, reject){
  1033. let distro = AssetGuard.retrieveDistributionDataSync(self.basePath)
  1034. const servers = distro.servers
  1035. let serv = null
  1036. for(let i=0; i<servers.length; i++){
  1037. if(servers[i].id === serverpack){
  1038. serv = servers[i]
  1039. break
  1040. }
  1041. }
  1042. const modules = serv.modules
  1043. for(let i=0; i<modules.length; i++){
  1044. const ob = modules[i]
  1045. if(ob.type === 'forge-hosted' || ob.type === 'forge'){
  1046. let obArtifact = ob.artifact
  1047. let obPath = obArtifact.path == null ? path.join(self.basePath, 'libraries', AssetGuard._resolvePath(ob.id, obArtifact.extension)) : obArtifact.path
  1048. let asset = new DistroModule(ob.id, obArtifact.MD5, obArtifact.size, obArtifact.url, obPath, ob.type)
  1049. let forgeData = await AssetGuard._finalizeForgeAsset(asset, self.basePath)
  1050. fulfill(forgeData)
  1051. return
  1052. }
  1053. }
  1054. reject('No forge module found!')
  1055. })
  1056. }
  1057. _parseForgeLibraries(){
  1058. /* TODO
  1059. * Forge asset validations are already implemented. When there's nothing much
  1060. * to work on, implement forge downloads using forge's version.json. This is to
  1061. * have the code on standby if we ever need it (since it's half implemented already).
  1062. */
  1063. }
  1064. // #endregion
  1065. // Java (Category=''') Validation (download) Functions
  1066. // #region
  1067. async _enqueueOracleJRE(dir){
  1068. const verData = await AssetGuard._latestJREOracle()
  1069. const combined = verData.uri + PLATFORM_MAP[process.platform]
  1070. const name = combined.substring(combined.lastIndexOf('/')+1)
  1071. const fDir = path.join(dir, name)
  1072. const opts = {
  1073. url: combined,
  1074. headers: {
  1075. 'Cookie': 'oraclelicense=accept-securebackup-cookie'
  1076. }
  1077. }
  1078. if(verData != null){
  1079. const jre = new Asset(name, null, 0, opts, fDir)
  1080. this.java = new DLTracker([jre], jre.size)
  1081. return true
  1082. } else {
  1083. return false
  1084. }
  1085. }
  1086. // #endregion
  1087. // #endregion
  1088. // Control Flow Functions
  1089. // #region
  1090. /**
  1091. * Initiate an async download process for an AssetGuard DLTracker.
  1092. *
  1093. * @param {string} identifier The identifier of the AssetGuard DLTracker.
  1094. * @param {number} limit Optional. The number of async processes to run in parallel.
  1095. * @returns {boolean} True if the process began, otherwise false.
  1096. */
  1097. startAsyncProcess(identifier, limit = 5){
  1098. const self = this
  1099. let acc = 0
  1100. const concurrentDlTracker = this[identifier]
  1101. const concurrentDlQueue = concurrentDlTracker.dlqueue.slice(0)
  1102. if(concurrentDlQueue.length === 0){
  1103. return false
  1104. } else {
  1105. async.eachLimit(concurrentDlQueue, limit, function(asset, cb){
  1106. let count = 0;
  1107. mkpath.sync(path.join(asset.to, ".."))
  1108. let req = request(asset.from)
  1109. req.pause()
  1110. req.on('response', (resp) => {
  1111. if(resp.statusCode === 200){
  1112. let writeStream = fs.createWriteStream(asset.to)
  1113. writeStream.on('close', () => {
  1114. //console.log('DLResults ' + asset.size + ' ' + count + ' ', asset.size === count)
  1115. if(concurrentDlTracker.callback != null){
  1116. concurrentDlTracker.callback.apply(concurrentDlTracker, [asset])
  1117. }
  1118. cb()
  1119. })
  1120. req.pipe(writeStream)
  1121. req.resume()
  1122. } else {
  1123. req.abort()
  1124. const realFrom = typeof asset.from === 'object' ? asset.from.url : asset.from
  1125. console.log('Failed to download ' + realFrom + '. Response code', resp.statusCode)
  1126. self.progress += asset.size*1
  1127. self.emit('totaldlprogress', {acc: self.progress, total: self.totaldlsize})
  1128. cb()
  1129. }
  1130. })
  1131. req.on('data', function(chunk){
  1132. count += chunk.length
  1133. self.progress += chunk.length
  1134. acc += chunk.length
  1135. self.emit(identifier + 'dlprogress', acc)
  1136. self.emit('totaldlprogress', {acc: self.progress, total: self.totaldlsize})
  1137. })
  1138. }, function(err){
  1139. if(err){
  1140. self.emit(identifier + 'dlerror')
  1141. console.log('An item in ' + identifier + ' failed to process');
  1142. } else {
  1143. self.emit(identifier + 'dlcomplete')
  1144. console.log('All ' + identifier + ' have been processed successfully')
  1145. }
  1146. self.totaldlsize -= self[identifier].dlsize
  1147. self.progress -= self[identifier].dlsize
  1148. self[identifier] = new DLTracker([], 0)
  1149. if(self.totaldlsize === 0) {
  1150. self.emit('dlcomplete')
  1151. }
  1152. })
  1153. return true
  1154. }
  1155. }
  1156. /**
  1157. * This function will initiate the download processed for the specified identifiers. If no argument is
  1158. * given, all identifiers will be initiated. Note that in order for files to be processed you need to run
  1159. * the processing function corresponding to that identifier. If you run this function without processing
  1160. * the files, it is likely nothing will be enqueued in the object and processing will complete
  1161. * immediately. Once all downloads are complete, this function will fire the 'dlcomplete' event on the
  1162. * global object instance.
  1163. *
  1164. * @param {Array.<{id: string, limit: number}>} identifiers Optional. The identifiers to process and corresponding parallel async task limit.
  1165. */
  1166. processDlQueues(identifiers = [{id:'assets', limit:20}, {id:'libraries', limit:5}, {id:'files', limit:5}, {id:'forge', limit:5}]){
  1167. this.progress = 0;
  1168. let shouldFire = true
  1169. // Assign dltracking variables.
  1170. this.totaldlsize = 0
  1171. this.progress = 0
  1172. for(let i=0; i<identifiers.length; i++){
  1173. this.totaldlsize += this[identifiers[i].id].dlsize
  1174. }
  1175. for(let i=0; i<identifiers.length; i++){
  1176. let iden = identifiers[i]
  1177. let r = this.startAsyncProcess(iden.id, iden.limit)
  1178. if(r) shouldFire = false
  1179. }
  1180. if(shouldFire){
  1181. this.emit('dlcomplete')
  1182. }
  1183. }
  1184. // #endregion
  1185. }
  1186. module.exports = {
  1187. AssetGuard,
  1188. Asset,
  1189. Library
  1190. }