assetguard.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  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. A central object
  6. * stores download meta for several identifiers (categories). This meta data
  7. * is initially empty until one of the module's processing functions are called.
  8. * That function will process the corresponding asset index and validate any exisitng
  9. * local files. If a file is missing or fails validation, it will be placed into an
  10. * array which acts as a queue. 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 central 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 central
  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 central object 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 fs = require('fs')
  26. const request = require('request')
  27. const path = require('path')
  28. const mkpath = require('mkdirp');
  29. const async = require('async')
  30. const crypto = require('crypto')
  31. const AdmZip = require('adm-zip')
  32. const child_process = require('child_process')
  33. const EventEmitter = require('events')
  34. const {remote} = require('electron')
  35. // Classes
  36. /** Class representing a base asset. */
  37. class Asset{
  38. /**
  39. * Create an asset.
  40. *
  41. * @param {any} id - id of the asset.
  42. * @param {String} hash - hash value of the asset.
  43. * @param {Number} size - size in bytes of the asset.
  44. * @param {String} from - url where the asset can be found.
  45. * @param {String} to - absolute local file path of the asset.
  46. */
  47. constructor(id, hash, size, from, to){
  48. this.id = id
  49. this.hash = hash
  50. this.size = size
  51. this.from = from
  52. this.to = to
  53. }
  54. }
  55. /** Class representing a mojang library. */
  56. class Library extends Asset{
  57. /**
  58. * Converts the process.platform OS names to match mojang's OS names.
  59. */
  60. static mojangFriendlyOS(){
  61. const opSys = process.platform
  62. if (opSys === 'darwin') {
  63. return 'osx';
  64. } else if (opSys === 'win32'){
  65. return 'windows';
  66. } else if (opSys === 'linux'){
  67. return 'linux';
  68. } else {
  69. return 'unknown_os';
  70. }
  71. }
  72. /**
  73. * Checks whether or not a library is valid for download on a particular OS, following
  74. * the rule format specified in the mojang version data index. If the allow property has
  75. * an OS specified, then the library can ONLY be downloaded on that OS. If the disallow
  76. * property has instead specified an OS, the library can be downloaded on any OS EXCLUDING
  77. * the one specified.
  78. *
  79. * @param {Object} rules - the Library's download rules.
  80. * @returns {Boolean} - true if the Library follows the specified rules, otherwise false.
  81. */
  82. static validateRules(rules){
  83. if(rules == null) return true
  84. let result = true
  85. rules.forEach(function(rule){
  86. const action = rule['action']
  87. const osProp = rule['os']
  88. if(action != null){
  89. if(osProp != null){
  90. const osName = osProp['name']
  91. const osMoj = Library.mojangFriendlyOS()
  92. if(action === 'allow'){
  93. result = osName === osMoj
  94. return
  95. } else if(action === 'disallow'){
  96. result = osName !== osMoj
  97. return
  98. }
  99. }
  100. }
  101. })
  102. return result
  103. }
  104. }
  105. /**
  106. * Class representing a download tracker. This is used to store meta data
  107. * about a download queue, including the queue itself.
  108. */
  109. class DLTracker {
  110. /**
  111. * Create a DLTracker
  112. *
  113. * @param {Array.<Asset>} dlqueue - an array containing assets queued for download.
  114. * @param {Number} dlsize - the combined size of each asset in the download queue array.
  115. */
  116. constructor(dlqueue, dlsize){
  117. this.dlqueue = dlqueue
  118. this.dlsize = dlsize
  119. }
  120. }
  121. /**
  122. * Central object class used for control flow. This object stores data about
  123. * categories of downloads. Each category is assigned an identifier with a
  124. * DLTracker object as its value. Combined information is also stored, such as
  125. * the total size of all the queued files in each category. This event is used
  126. * to emit events so that external modules can listen into processing done in
  127. * this module.
  128. */
  129. class AssetGuard extends EventEmitter{
  130. /**
  131. * AssetGuard class should only ever have one instance which is defined in
  132. * this module. On creation the object's properties are never-null default
  133. * values. Each identifier is resolved to an empty DLTracker.
  134. */
  135. constructor(){
  136. super()
  137. this.totaldlsize = 0;
  138. this.progress = 0;
  139. this.assets = new DLTracker([], 0)
  140. this.libraries = new DLTracker([], 0)
  141. this.files = new DLTracker([], 0)
  142. this.forge = new DLTracker([], 0)
  143. }
  144. }
  145. /**
  146. * Global static final instance of AssetGuard
  147. */
  148. const instance = new AssetGuard()
  149. // Utility Functions
  150. /**
  151. * Resolve an artifact id into a path. For example, on windows
  152. * 'net.minecraftforge:forge:1.11.2-13.20.0.2282', '.jar' becomes
  153. * net\minecraftforge\forge\1.11.2-13.20.0.2282\forge-1.11.2-13.20.0.2282.jar
  154. *
  155. * @param {String} artifact - the artifact id string.
  156. * @param {String} extension - the extension of the file at the resolved path.
  157. * @returns {String} - the resolved relative path from the artifact id.
  158. */
  159. function _resolvePath(artifactid, extension){
  160. let ps = artifactid.split(':')
  161. let cs = ps[0].split('.')
  162. cs.push(ps[1])
  163. cs.push(ps[2])
  164. cs.push(ps[1].concat('-').concat(ps[2]).concat(extension))
  165. return path.join.apply(path, cs)
  166. }
  167. /**
  168. * Calculates the hash for a file using the specified algorithm.
  169. *
  170. * @param {Buffer} buf - the buffer containing file data.
  171. * @param {String} algo - the hash algorithm.
  172. * @returns {String} - the calculated hash in hex.
  173. */
  174. function _calculateHash(buf, algo){
  175. return crypto.createHash(algo).update(buf).digest('hex')
  176. }
  177. /**
  178. * Used to parse a checksums file. This is specifically designed for
  179. * the checksums.sha1 files found inside the forge scala dependencies.
  180. *
  181. * @param {String} content - the string content of the checksums file.
  182. * @returns {Object} - an object with keys being the file names, and values being the hashes.
  183. */
  184. function _parseChecksumsFile(content){
  185. let finalContent = {}
  186. let lines = content.split('\n')
  187. for(let i=0; i<lines.length; i++){
  188. let bits = lines[i].split(' ')
  189. if(bits[1] == null) {
  190. continue
  191. }
  192. finalContent[bits[1]] = bits[0]
  193. }
  194. return finalContent
  195. }
  196. /**
  197. * Validate that a file exists and matches a given hash value.
  198. *
  199. * @param {String} filePath - the path of the file to validate.
  200. * @param {String} algo - the hash algorithm to check against.
  201. * @param {String} hash - the existing hash to check against.
  202. * @returns {Boolean} - true if the file exists and calculated hash matches the given hash, otherwise false.
  203. */
  204. function _validateLocal(filePath, algo, hash){
  205. if(fs.existsSync(filePath)){
  206. let fileName = path.basename(filePath)
  207. let buf = fs.readFileSync(filePath)
  208. let calcdhash = _calculateHash(buf, algo)
  209. return calcdhash === hash
  210. }
  211. return false;
  212. }
  213. /**
  214. * Validates a file in the style used by forge's version index.
  215. *
  216. * @param {String} filePath - the path of the file to validate.
  217. * @param {Array.<String>} checksums - the checksums listed in the forge version index.
  218. * @returns {Boolean} - true if the file exists and the hashes match, otherwise false.
  219. */
  220. function _validateForgeChecksum(filePath, checksums){
  221. if(fs.existsSync(filePath)){
  222. if(checksums == null || checksums.length === 0){
  223. return true
  224. }
  225. let buf = fs.readFileSync(filePath)
  226. let calcdhash = _calculateHash(buf, 'sha1')
  227. let valid = checksums.includes(calcdhash)
  228. if(!valid && filePath.endsWith('.jar')){
  229. valid = _validateForgeJar(filePath, checksums)
  230. }
  231. return valid
  232. }
  233. return false
  234. }
  235. /**
  236. * Validates a forge jar file dependency who declares a checksums.sha1 file.
  237. * This can be an expensive task as it usually requires that we calculate thousands
  238. * of hashes.
  239. *
  240. * @param {Buffer} buf - the buffer of the jar file.
  241. * @param {Array.<String>} checksums - the checksums listed in the forge version index.
  242. * @returns {Boolean} - true if all hashes declared in the checksums.sha1 file match the actual hashes.
  243. */
  244. function _validateForgeJar(buf, checksums){
  245. const hashes = {}
  246. let expected = {}
  247. const zip = new AdmZip(buf)
  248. const zipEntries = zip.getEntries()
  249. //First pass
  250. for(let i=0; i<zipEntries.length; i++){
  251. let entry = zipEntries[i]
  252. if(entry.entryName === 'checksums.sha1'){
  253. expected = _parseChecksumsFile(zip.readAsText(entry))
  254. }
  255. hashes[entry.entryName] = _calculateHash(entry.getData(), 'sha1')
  256. }
  257. if(!checksums.includes(hashes['checksums.sha1'])){
  258. return false
  259. }
  260. //Check against expected
  261. const expectedEntries = Object.keys(expected)
  262. for(let i=0; i<expectedEntries.length; i++){
  263. if(expected[expectedEntries[i]] !== hashes[expectedEntries[i]]){
  264. return false
  265. }
  266. }
  267. return true
  268. }
  269. function _extractPackXZ(filePath){
  270. return new Promise(function(fulfill, reject){
  271. const libPath = path.join(__dirname, '..', 'libraries', 'java', 'PackXZExtract.jar')
  272. const child = child_process.spawn('C:\\Program Files\\Java\\jre1.8.0_131\\bin\\javaw.exe', ['-jar', libPath, '-packxz', filePath])
  273. child.stdout.on('data', (data) => {
  274. console.log('minecraft:', data.toString('utf8'))
  275. })
  276. child.stderr.on('data', (data) => {
  277. console.log('minecraft:', data.toString('utf8'))
  278. })
  279. child.on('close', (code, signal) => {
  280. console.log('exited with code', code)
  281. fulfill()
  282. })
  283. })
  284. }
  285. /**
  286. * Initiate an async download process for an AssetGuard DLTracker.
  287. *
  288. * @param {String} identifier - the identifier of the AssetGuard DLTracker.
  289. * @param {Number} limit - optional. The number of async processes to run in parallel.
  290. * @returns {Boolean} - true if the process began, otherwise false.
  291. */
  292. function startAsyncProcess(identifier, limit = 5){
  293. let win = remote.getCurrentWindow()
  294. let acc = 0
  295. const concurrentDlQueue = instance[identifier].dlqueue.slice(0)
  296. if(concurrentDlQueue.length === 0){
  297. return false
  298. } else {
  299. async.eachLimit(concurrentDlQueue, limit, function(asset, cb){
  300. mkpath.sync(path.join(asset.to, ".."))
  301. let req = request(asset.from)
  302. let writeStream = fs.createWriteStream(asset.to)
  303. req.pipe(writeStream)
  304. req.on('data', function(chunk){
  305. instance.progress += chunk.length
  306. acc += chunk.length
  307. instance.emit(identifier + 'dlprogress', acc)
  308. //console.log(identifier + ' Progress', acc/instance[identifier].dlsize)
  309. win.setProgressBar(instance.progress/instance.totaldlsize)
  310. })
  311. writeStream.on('close', cb)
  312. }, function(err){
  313. if(err){
  314. instance.emit(identifier + 'dlerror')
  315. console.log('An item in ' + identifier + ' failed to process');
  316. } else {
  317. instance.emit(identifier + 'dlcomplete')
  318. console.log('All ' + identifier + ' have been processed successfully')
  319. }
  320. instance.totaldlsize -= instance[identifier].dlsize
  321. instance[identifier] = new DLTracker([], 0)
  322. if(instance.totaldlsize === 0) {
  323. win.setProgressBar(-1)
  324. instance.emit('dlcomplete')
  325. }
  326. })
  327. return true
  328. }
  329. }
  330. // Validation Functions
  331. /**
  332. * Loads the version data for a given minecraft version.
  333. *
  334. * @param {String} version - the game version for which to load the index data.
  335. * @param {String} basePath - the absolute file path which will be prepended to the given relative paths.
  336. * @param {Boolean} force - optional. If true, the version index will be downloaded even if it exists locally. Defaults to false.
  337. * @returns {Promise.<Object>} - Promise which resolves to the version data object.
  338. */
  339. function loadVersionData(version, basePath, force = false){
  340. return new Promise(function(fulfill, reject){
  341. const name = version + '.json'
  342. const url = 'https://s3.amazonaws.com/Minecraft.Download/versions/' + version + '/' + name
  343. const versionPath = path.join(basePath, 'versions', version)
  344. const versionFile = path.join(versionPath, name)
  345. if(!fs.existsSync(versionFile) || force){
  346. //This download will never be tracked as it's essential and trivial.
  347. request.head(url, function(err, res, body){
  348. console.log('Preparing download of ' + version + ' assets.')
  349. mkpath.sync(versionPath)
  350. const stream = request(url).pipe(fs.createWriteStream(versionFile))
  351. stream.on('finish', function(){
  352. fulfill(JSON.parse(fs.readFileSync(versionFile)))
  353. })
  354. })
  355. } else {
  356. fulfill(JSON.parse(fs.readFileSync(versionFile)))
  357. }
  358. })
  359. }
  360. /**
  361. * Public asset validation function. This function will handle the validation of assets.
  362. * It will parse the asset index specified in the version data, analyzing each
  363. * asset entry. In this analysis it will check to see if the local file exists and is valid.
  364. * If not, it will be added to the download queue for the 'assets' identifier.
  365. *
  366. * @param {Object} versionData - the version data for the assets.
  367. * @param {String} basePath - the absolute file path which will be prepended to the given relative paths.
  368. * @param {Boolean} force - optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  369. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  370. */
  371. function validateAssets(versionData, basePath, force = false){
  372. return new Promise(function(fulfill, reject){
  373. _assetChainIndexData(versionData, basePath, force).then(() => {
  374. fulfill()
  375. })
  376. })
  377. }
  378. //Chain the asset tasks to provide full async. The below functions are private.
  379. /**
  380. * Private function used to chain the asset validation process. This function retrieves
  381. * the index data.
  382. * @param {Object} versionData
  383. * @param {String} basePath
  384. * @param {Boolean} force
  385. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  386. */
  387. function _assetChainIndexData(versionData, basePath, force = false){
  388. return new Promise(function(fulfill, reject){
  389. //Asset index constants.
  390. const assetIndex = versionData.assetIndex
  391. const name = assetIndex.id + '.json'
  392. const indexPath = path.join(basePath, 'assets', 'indexes')
  393. const assetIndexLoc = path.join(indexPath, name)
  394. let data = null
  395. if(!fs.existsSync(assetIndexLoc) || force){
  396. console.log('Downloading ' + versionData.id + ' asset index.')
  397. mkpath.sync(indexPath)
  398. const stream = request(assetIndex.url).pipe(fs.createWriteStream(assetIndexLoc))
  399. stream.on('finish', function() {
  400. data = JSON.parse(fs.readFileSync(assetIndexLoc, 'utf-8'))
  401. _assetChainValidateAssets(versionData, basePath, data).then(() => {
  402. fulfill()
  403. })
  404. })
  405. } else {
  406. data = JSON.parse(fs.readFileSync(assetIndexLoc, 'utf-8'))
  407. _assetChainValidateAssets(versionData, basePath, data).then(() => {
  408. fulfill()
  409. })
  410. }
  411. })
  412. }
  413. /**
  414. * Private function used to chain the asset validation process. This function processes
  415. * the assets and enqueues missing or invalid files.
  416. * @param {Object} versionData
  417. * @param {String} basePath
  418. * @param {Boolean} force
  419. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  420. */
  421. function _assetChainValidateAssets(versionData, basePath, indexData){
  422. return new Promise(function(fulfill, reject){
  423. //Asset constants
  424. const resourceURL = 'http://resources.download.minecraft.net/'
  425. const localPath = path.join(basePath, 'assets')
  426. const indexPath = path.join(localPath, 'indexes')
  427. const objectPath = path.join(localPath, 'objects')
  428. const assetDlQueue = []
  429. let dlSize = 0;
  430. //const objKeys = Object.keys(data.objects)
  431. async.forEachOfLimit(indexData.objects, 10, function(value, key, cb){
  432. const hash = value.hash
  433. const assetName = path.join(hash.substring(0, 2), hash)
  434. const urlName = hash.substring(0, 2) + "/" + hash
  435. const ast = new Asset(key, hash, String(value.size), resourceURL + urlName, path.join(objectPath, assetName))
  436. if(!_validateLocal(ast.to, 'sha1', ast.hash)){
  437. dlSize += (ast.size*1)
  438. assetDlQueue.push(ast)
  439. }
  440. cb()
  441. }, function(err){
  442. instance.assets = new DLTracker(assetDlQueue, dlSize)
  443. instance.totaldlsize += dlSize
  444. fulfill()
  445. })
  446. })
  447. }
  448. /**
  449. * Public library validation function. This function will handle the validation of libraries.
  450. * It will parse the version data, analyzing each library entry. In this analysis, it will
  451. * check to see if the local file exists and is valid. If not, it will be added to the download
  452. * queue for the 'libraries' identifier.
  453. *
  454. * @param {Object} versionData - the version data for the assets.
  455. * @param {String} basePath - the absolute file path which will be prepended to the given relative paths.
  456. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  457. */
  458. function validateLibraries(versionData, basePath){
  459. return new Promise(function(fulfill, reject){
  460. const libArr = versionData.libraries
  461. const libPath = path.join(basePath, 'libraries')
  462. const libDlQueue = []
  463. let dlSize = 0
  464. //Check validity of each library. If the hashs don't match, download the library.
  465. async.eachLimit(libArr, 5, function(lib, cb){
  466. if(Library.validateRules(lib.rules)){
  467. let artifact = (lib.natives == null) ? lib.downloads.artifact : lib.downloads.classifiers[lib.natives[Library.mojangFriendlyOS()]]
  468. const libItm = new Library(lib.name, artifact.sha1, artifact.size, artifact.url, path.join(libPath, artifact.path))
  469. if(!_validateLocal(libItm.to, 'sha1', libItm.hash)){
  470. dlSize += (libItm.size*1)
  471. libDlQueue.push(libItm)
  472. }
  473. }
  474. cb()
  475. }, function(err){
  476. instance.libraries = new DLTracker(libDlQueue, dlSize)
  477. instance.totaldlsize += dlSize
  478. fulfill()
  479. })
  480. })
  481. }
  482. /**
  483. * Public miscellaneous mojang file validation function. These files will be enqueued under
  484. * the 'files' identifier.
  485. *
  486. * @param {Object} versionData - the version data for the assets.
  487. * @param {String} basePath - the absolute file path which will be prepended to the given relative paths.
  488. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  489. */
  490. function validateMiscellaneous(versionData, basePath){
  491. return new Promise(async function(fulfill, reject){
  492. await validateClient(versionData, basePath)
  493. await validateLogConfig(versionData, basePath)
  494. fulfill()
  495. })
  496. }
  497. /**
  498. * Validate client file - artifact renamed from client.jar to '{version}'.jar.
  499. *
  500. * @param {Object} versionData - the version data for the assets.
  501. * @param {String} basePath - the absolute file path which will be prepended to the given relative paths.
  502. * @param {Boolean} force - optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  503. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  504. */
  505. function validateClient(versionData, basePath, force = false){
  506. return new Promise(function(fulfill, reject){
  507. const clientData = versionData.downloads.client
  508. const version = versionData.id
  509. const targetPath = path.join(basePath, 'versions', version)
  510. const targetFile = version + '.jar'
  511. let client = new Asset(version + ' client', clientData.sha1, clientData.size, clientData.url, path.join(targetPath, targetFile))
  512. if(!_validateLocal(client.to, 'sha1', client.hash) || force){
  513. instance.files.dlqueue.push(client)
  514. instance.files.dlsize += client.size*1
  515. fulfill()
  516. } else {
  517. fulfill()
  518. }
  519. })
  520. }
  521. /**
  522. * Validate log config.
  523. *
  524. * @param {Object} versionData - the version data for the assets.
  525. * @param {String} basePath - the absolute file path which will be prepended to the given relative paths.
  526. * @param {Boolean} force - optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  527. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  528. */
  529. function validateLogConfig(versionData, basePath){
  530. return new Promise(function(fulfill, reject){
  531. const client = versionData.logging.client
  532. const file = client.file
  533. const targetPath = path.join(basePath, 'assets', 'log_configs')
  534. let logConfig = new Asset(file.id, file.sha1, file.size, file.url, path.join(targetPath, file.id))
  535. if(!_validateLocal(logConfig.to, 'sha1', logConfig.hash)){
  536. instance.files.dlqueue.push(logConfig)
  537. instance.files.dlsize += client.size*1
  538. fulfill()
  539. } else {
  540. fulfill()
  541. }
  542. })
  543. }
  544. function validateDistribution(serverpackid, basePath){
  545. return new Promise(function(fulfill, reject){
  546. let distroindex = _chainValidateDistributionIndex(basePath).then((value) => {
  547. let servers = value.servers
  548. let serv = null
  549. for(let i=0; i<servers.length; i++){
  550. if(servers[i].id === serverpackid){
  551. serv = servers[i]
  552. break
  553. }
  554. }
  555. instance.forge = _parseDistroModules(serv.modules, basePath, serv.mc_version)
  556. instance.totaldlsize += instance.forge.dlsize*1
  557. fulfill()
  558. })
  559. })
  560. }
  561. //TODO The distro index should be downloaded in the 'pre-loader'. This is because
  562. //we will eventually NEED the index to generate the server list on the ui.
  563. function _chainValidateDistributionIndex(basePath){
  564. return new Promise(function(fulfill, reject){
  565. //const distroURL = 'http://mc.westeroscraft.com/WesterosCraftLauncher/westeroscraft.json'
  566. const targetFile = path.join(basePath, 'westeroscraft.json')
  567. //TEMP WORKAROUND TO TEST WHILE THIS IS NOT HOSTED
  568. fs.readFile(path.join(basePath, '..', 'app', 'assets', 'westeroscraft.json'), 'utf-8', (err, data) => {
  569. fulfill(JSON.parse(data))
  570. })
  571. })
  572. }
  573. function _parseDistroModules(modules, basePath, version){
  574. let alist = []
  575. let asize = 0;
  576. for(let i=0; i<modules.length; i++){
  577. let ob = modules[i]
  578. let obType = ob.type
  579. let obArtifact = ob.artifact
  580. let obPath = obArtifact.path == null ? _resolvePath(ob.id, obArtifact.extension) : obArtifact.path
  581. switch(obType){
  582. case 'forge-hosted':
  583. obPath = path.join(basePath, 'libraries', obPath)
  584. break;
  585. case 'library':
  586. obPath = path.join(basePath, 'libraries', obPath)
  587. break;
  588. case 'forgemod':
  589. obPath = path.join(basePath, 'mods', obPath)
  590. break;
  591. case 'litemod':
  592. obPath = path.join(basePath, 'mods', version, obPath)
  593. break;
  594. default:
  595. obPath = path.join(basePath, obPath)
  596. }
  597. let artifact = new Asset(ob.id, obArtifact.MD5, obArtifact.size, obArtifact.url, obPath)
  598. asize += artifact.size*1
  599. alist.push(artifact)
  600. if(ob.sub_modules != null){
  601. let dltrack = _parseDistroModules(ob.sub_modules, basePath, version)
  602. asize += dltrack.dlsize
  603. alist = alist.concat(dltrack.dlqueue)
  604. }
  605. }
  606. return new DLTracker(alist, asize)
  607. }
  608. /**
  609. * This function will initiate the download processed for the specified identifiers. If no argument is
  610. * given, all identifiers will be initiated. Note that in order for files to be processed you need to run
  611. * the processing function corresponding to that identifier. If you run this function without processing
  612. * the files, it is likely nothing will be enqueued in the global object and processing will complete
  613. * immediately. Once all downloads are complete, this function will fire the 'dlcomplete' event on the
  614. * global object instance.
  615. *
  616. * @param {Array.<{id: string, limit: number}>} identifiers - optional. The identifiers to process and corresponding parallel async task limit.
  617. */
  618. function processDlQueues(identifiers = [{id:'assets', limit:20}, {id:'libraries', limit:5}, {id:'files', limit:5}, {id:'forge', limit:5}]){
  619. this.progress = 0;
  620. let win = remote.getCurrentWindow()
  621. let shouldFire = true
  622. for(let i=0; i<identifiers.length; i++){
  623. let iden = identifiers[i]
  624. let r = startAsyncProcess(iden.id, iden.limit)
  625. if(r) shouldFire = false
  626. }
  627. if(shouldFire){
  628. instance.emit('dlcomplete')
  629. }
  630. }
  631. module.exports = {
  632. loadVersionData,
  633. validateAssets,
  634. validateLibraries,
  635. validateMiscellaneous,
  636. processDlQueues,
  637. instance,
  638. Asset,
  639. Library,
  640. validateDistribution
  641. }