assetguard.js 28 KB

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