assetguard.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  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 {DEFAULT_CONFIG} = require('./constants')
  30. const EventEmitter = require('events')
  31. const fs = require('fs')
  32. const mkpath = require('mkdirp');
  33. const path = require('path')
  34. const request = require('request')
  35. const {remote} = require('electron')
  36. // Classes
  37. /** Class representing a base asset. */
  38. class Asset {
  39. /**
  40. * Create an asset.
  41. *
  42. * @param {any} id - id of the asset.
  43. * @param {String} hash - hash value of the asset.
  44. * @param {Number} size - size in bytes of the asset.
  45. * @param {String} from - url where the asset can be found.
  46. * @param {String} to - absolute local file path of the asset.
  47. */
  48. constructor(id, hash, size, from, to){
  49. this.id = id
  50. this.hash = hash
  51. this.size = size
  52. this.from = from
  53. this.to = to
  54. }
  55. }
  56. /** Class representing a mojang library. */
  57. class Library extends Asset {
  58. /**
  59. * Converts the process.platform OS names to match mojang's OS names.
  60. */
  61. static mojangFriendlyOS(){
  62. const opSys = process.platform
  63. if (opSys === 'darwin') {
  64. return 'osx';
  65. } else if (opSys === 'win32'){
  66. return 'windows';
  67. } else if (opSys === 'linux'){
  68. return 'linux';
  69. } else {
  70. return 'unknown_os';
  71. }
  72. }
  73. /**
  74. * Checks whether or not a library is valid for download on a particular OS, following
  75. * the rule format specified in the mojang version data index. If the allow property has
  76. * an OS specified, then the library can ONLY be downloaded on that OS. If the disallow
  77. * property has instead specified an OS, the library can be downloaded on any OS EXCLUDING
  78. * the one specified.
  79. *
  80. * @param {Object} rules - the Library's download rules.
  81. * @returns {Boolean} - true if the Library follows the specified rules, otherwise false.
  82. */
  83. static validateRules(rules){
  84. if(rules == null) return true
  85. let result = true
  86. rules.forEach(function(rule){
  87. const action = rule['action']
  88. const osProp = rule['os']
  89. if(action != null){
  90. if(osProp != null){
  91. const osName = osProp['name']
  92. const osMoj = Library.mojangFriendlyOS()
  93. if(action === 'allow'){
  94. result = osName === osMoj
  95. return
  96. } else if(action === 'disallow'){
  97. result = osName !== osMoj
  98. return
  99. }
  100. }
  101. }
  102. })
  103. return result
  104. }
  105. }
  106. class DistroModule extends Asset {
  107. /**
  108. * Create a DistroModule. This is for processing,
  109. * not equivalent to the module objects in the
  110. * distro index.
  111. *
  112. * @param {any} id - id of the asset.
  113. * @param {String} hash - hash value of the asset.
  114. * @param {Number} size - size in bytes of the asset.
  115. * @param {String} from - url where the asset can be found.
  116. * @param {String} to - absolute local file path of the asset.
  117. * @param {String} type - the module type.
  118. */
  119. constructor(id, hash, size, from, to, type){
  120. super(id, hash, size, from, to)
  121. this.type = type
  122. }
  123. }
  124. /**
  125. * Class representing a download tracker. This is used to store meta data
  126. * about a download queue, including the queue itself.
  127. */
  128. class DLTracker {
  129. /**
  130. * Create a DLTracker
  131. *
  132. * @param {Array.<Asset>} dlqueue - an array containing assets queued for download.
  133. * @param {Number} dlsize - the combined size of each asset in the download queue array.
  134. * @param {function(Asset)} callback - optional callback which is called when an asset finishes downloading.
  135. */
  136. constructor(dlqueue, dlsize, callback = null){
  137. this.dlqueue = dlqueue
  138. this.dlsize = dlsize
  139. this.callback = callback
  140. }
  141. }
  142. /**
  143. * Central object class used for control flow. This object stores data about
  144. * categories of downloads. Each category is assigned an identifier with a
  145. * DLTracker object as its value. Combined information is also stored, such as
  146. * the total size of all the queued files in each category. This event is used
  147. * to emit events so that external modules can listen into processing done in
  148. * this module.
  149. */
  150. class AssetGuard extends EventEmitter {
  151. /**
  152. * AssetGuard class should only ever have one instance which is defined in
  153. * this module. On creation the object's properties are never-null default
  154. * values. Each identifier is resolved to an empty DLTracker.
  155. */
  156. constructor(){
  157. super()
  158. this.totaldlsize = 0;
  159. this.progress = 0;
  160. this.assets = new DLTracker([], 0)
  161. this.libraries = new DLTracker([], 0)
  162. this.files = new DLTracker([], 0)
  163. this.forge = new DLTracker([], 0)
  164. }
  165. // Static Utility Functions
  166. /**
  167. * Resolve an artifact id into a path. For example, on windows
  168. * 'net.minecraftforge:forge:1.11.2-13.20.0.2282', '.jar' becomes
  169. * net\minecraftforge\forge\1.11.2-13.20.0.2282\forge-1.11.2-13.20.0.2282.jar
  170. *
  171. * @param {String} artifactid - the artifact id string.
  172. * @param {String} extension - the extension of the file at the resolved path.
  173. * @returns {String} - the resolved relative path from the artifact id.
  174. */
  175. static _resolvePath(artifactid, extension){
  176. let ps = artifactid.split(':')
  177. let cs = ps[0].split('.')
  178. cs.push(ps[1])
  179. cs.push(ps[2])
  180. cs.push(ps[1].concat('-').concat(ps[2]).concat(extension))
  181. return path.join.apply(path, cs)
  182. }
  183. /**
  184. * Resolve an artifact id into a URL. For example,
  185. * 'net.minecraftforge:forge:1.11.2-13.20.0.2282', '.jar' becomes
  186. * net/minecraftforge/forge/1.11.2-13.20.0.2282/forge-1.11.2-13.20.0.2282.jar
  187. *
  188. * @param {String} artifactid - the artifact id string.
  189. * @param {String} extension - the extension of the file at the resolved url.
  190. * @returns {String} - the resolved relative URL from the artifact id.
  191. */
  192. static _resolveURL(artifactid, extension){
  193. let ps = artifactid.split(':')
  194. let cs = ps[0].split('.')
  195. cs.push(ps[1])
  196. cs.push(ps[2])
  197. cs.push(ps[1].concat('-').concat(ps[2]).concat(extension))
  198. return cs.join('/')
  199. }
  200. /**
  201. * Calculates the hash for a file using the specified algorithm.
  202. *
  203. * @param {Buffer} buf - the buffer containing file data.
  204. * @param {String} algo - the hash algorithm.
  205. * @returns {String} - the calculated hash in hex.
  206. */
  207. static _calculateHash(buf, algo){
  208. return crypto.createHash(algo).update(buf).digest('hex')
  209. }
  210. /**
  211. * Used to parse a checksums file. This is specifically designed for
  212. * the checksums.sha1 files found inside the forge scala dependencies.
  213. *
  214. * @param {String} content - the string content of the checksums file.
  215. * @returns {Object} - an object with keys being the file names, and values being the hashes.
  216. */
  217. static _parseChecksumsFile(content){
  218. let finalContent = {}
  219. let lines = content.split('\n')
  220. for(let i=0; i<lines.length; i++){
  221. let bits = lines[i].split(' ')
  222. if(bits[1] == null) {
  223. continue
  224. }
  225. finalContent[bits[1]] = bits[0]
  226. }
  227. return finalContent
  228. }
  229. /**
  230. * Validate that a file exists and matches a given hash value.
  231. *
  232. * @param {String} filePath - the path of the file to validate.
  233. * @param {String} algo - the hash algorithm to check against.
  234. * @param {String} hash - the existing hash to check against.
  235. * @returns {Boolean} - true if the file exists and calculated hash matches the given hash, otherwise false.
  236. */
  237. static _validateLocal(filePath, algo, hash){
  238. if(fs.existsSync(filePath)){
  239. //No hash provided, have to assume it's good.
  240. if(hash == null){
  241. return true
  242. }
  243. let fileName = path.basename(filePath)
  244. let buf = fs.readFileSync(filePath)
  245. let calcdhash = AssetGuard._calculateHash(buf, algo)
  246. return calcdhash === hash
  247. }
  248. return false;
  249. }
  250. /**
  251. * Validates a file in the style used by forge's version index.
  252. *
  253. * @param {String} filePath - the path of the file to validate.
  254. * @param {Array.<String>} checksums - the checksums listed in the forge version index.
  255. * @returns {Boolean} - true if the file exists and the hashes match, otherwise false.
  256. */
  257. static _validateForgeChecksum(filePath, checksums){
  258. if(fs.existsSync(filePath)){
  259. if(checksums == null || checksums.length === 0){
  260. return true
  261. }
  262. let buf = fs.readFileSync(filePath)
  263. let calcdhash = AssetGuard._calculateHash(buf, 'sha1')
  264. let valid = checksums.includes(calcdhash)
  265. if(!valid && filePath.endsWith('.jar')){
  266. valid = AssetGuard._validateForgeJar(filePath, checksums)
  267. }
  268. return valid
  269. }
  270. return false
  271. }
  272. /**
  273. * Validates a forge jar file dependency who declares a checksums.sha1 file.
  274. * This can be an expensive task as it usually requires that we calculate thousands
  275. * of hashes.
  276. *
  277. * @param {Buffer} buf - the buffer of the jar file.
  278. * @param {Array.<String>} checksums - the checksums listed in the forge version index.
  279. * @returns {Boolean} - true if all hashes declared in the checksums.sha1 file match the actual hashes.
  280. */
  281. static _validateForgeJar(buf, checksums){
  282. // Double pass method was the quickest I found. I tried a version where we store data
  283. // to only require a single pass, plus some quick cleanup but that seemed to take slightly more time.
  284. const hashes = {}
  285. let expected = {}
  286. const zip = new AdmZip(buf)
  287. const zipEntries = zip.getEntries()
  288. //First pass
  289. for(let i=0; i<zipEntries.length; i++){
  290. let entry = zipEntries[i]
  291. if(entry.entryName === 'checksums.sha1'){
  292. expected = AssetGuard._parseChecksumsFile(zip.readAsText(entry))
  293. }
  294. hashes[entry.entryName] = AssetGuard._calculateHash(entry.getData(), 'sha1')
  295. }
  296. if(!checksums.includes(hashes['checksums.sha1'])){
  297. return false
  298. }
  299. //Check against expected
  300. const expectedEntries = Object.keys(expected)
  301. for(let i=0; i<expectedEntries.length; i++){
  302. if(expected[expectedEntries[i]] !== hashes[expectedEntries[i]]){
  303. return false
  304. }
  305. }
  306. return true
  307. }
  308. /**
  309. * Extracts and unpacks a file from .pack.xz format.
  310. *
  311. * @param {Array.<String>} filePaths - The paths of the files to be extracted and unpacked.
  312. * @returns {Promise.<Void>} - An empty promise to indicate the extraction has completed.
  313. */
  314. static _extractPackXZ(filePaths){
  315. return new Promise(function(fulfill, reject){
  316. const libPath = path.join(__dirname, '..', 'libraries', 'java', 'PackXZExtract.jar')
  317. const filePath = filePaths.join(',')
  318. const child = child_process.spawn(DEFAULT_CONFIG.getJavaExecutable(), ['-jar', libPath, '-packxz', filePath])
  319. child.stdout.on('data', (data) => {
  320. //console.log('PackXZExtract:', data.toString('utf8'))
  321. })
  322. child.stderr.on('data', (data) => {
  323. //console.log('PackXZExtract:', data.toString('utf8'))
  324. })
  325. child.on('close', (code, signal) => {
  326. //console.log('PackXZExtract: Exited with code', code)
  327. fulfill()
  328. })
  329. })
  330. }
  331. /**
  332. * Function which finalizes the forge installation process. This creates a 'version'
  333. * instance for forge and saves its version.json file into that instance. If that
  334. * instance already exists, the contents of the version.json file are read and returned
  335. * in a promise.
  336. *
  337. * @param {Asset} asset - The Asset object representing Forge.
  338. * @param {String} basePath
  339. * @returns {Promise.<Object>} - A promise which resolves to the contents of forge's version.json.
  340. */
  341. static _finalizeForgeAsset(asset, basePath){
  342. return new Promise(function(fulfill, reject){
  343. fs.readFile(asset.to, (err, data) => {
  344. const zip = new AdmZip(data)
  345. const zipEntries = zip.getEntries()
  346. for(let i=0; i<zipEntries.length; i++){
  347. if(zipEntries[i].entryName === 'version.json'){
  348. const forgeVersion = JSON.parse(zip.readAsText(zipEntries[i]))
  349. const versionPath = path.join(basePath, 'versions', forgeVersion.id)
  350. const versionFile = path.join(versionPath, forgeVersion.id + '.json')
  351. if(!fs.existsSync(versionFile)){
  352. mkpath.sync(versionPath)
  353. fs.writeFileSync(path.join(versionPath, forgeVersion.id + '.json'), zipEntries[i].getData())
  354. fulfill(forgeVersion)
  355. } else {
  356. //Read the saved file to allow for user modifications.
  357. fulfill(JSON.parse(fs.readFileSync(versionFile, 'utf-8')))
  358. }
  359. return
  360. }
  361. }
  362. //We didn't find forge's version.json.
  363. reject('Unable to finalize Forge processing, version.json not found! Has forge changed their format?')
  364. })
  365. })
  366. }
  367. /**
  368. * Initiate an async download process for an AssetGuard DLTracker.
  369. *
  370. * @param {String} identifier - the identifier of the AssetGuard DLTracker.
  371. * @param {Number} limit - optional. The number of async processes to run in parallel.
  372. * @returns {Boolean} - true if the process began, otherwise false.
  373. */
  374. startAsyncProcess(identifier, limit = 5){
  375. const self = this
  376. let win = remote.getCurrentWindow()
  377. let acc = 0
  378. const concurrentDlTracker = this[identifier]
  379. const concurrentDlQueue = concurrentDlTracker.dlqueue.slice(0)
  380. if(concurrentDlQueue.length === 0){
  381. return false
  382. } else {
  383. async.eachLimit(concurrentDlQueue, limit, function(asset, cb){
  384. let count = 0;
  385. mkpath.sync(path.join(asset.to, ".."))
  386. let req = request(asset.from)
  387. req.pause()
  388. req.on('response', (resp) => {
  389. if(resp.statusCode === 200){
  390. let writeStream = fs.createWriteStream(asset.to)
  391. writeStream.on('close', () => {
  392. //console.log('DLResults ' + asset.size + ' ' + count + ' ', asset.size === count)
  393. if(concurrentDlTracker.callback != null){
  394. concurrentDlTracker.callback.apply(concurrentDlTracker, [asset])
  395. }
  396. cb()
  397. })
  398. req.pipe(writeStream)
  399. req.resume()
  400. } else {
  401. req.abort()
  402. console.log('Failed to download ' + asset.from + '. Response code', resp.statusCode)
  403. self.progress += asset.size*1
  404. win.setProgressBar(self.progress/self.totaldlsize)
  405. self.emit('totaldlprogress', {acc: self.progress, total: self.totaldlsize})
  406. cb()
  407. }
  408. })
  409. req.on('data', function(chunk){
  410. count += chunk.length
  411. self.progress += chunk.length
  412. acc += chunk.length
  413. self.emit(identifier + 'dlprogress', acc)
  414. //console.log(identifier + ' Progress', acc/this[identifier].dlsize)
  415. win.setProgressBar(self.progress/self.totaldlsize)
  416. self.emit('totaldlprogress', {acc: self.progress, total: self.totaldlsize})
  417. })
  418. }, function(err){
  419. if(err){
  420. self.emit(identifier + 'dlerror')
  421. console.log('An item in ' + identifier + ' failed to process');
  422. } else {
  423. self.emit(identifier + 'dlcomplete')
  424. console.log('All ' + identifier + ' have been processed successfully')
  425. }
  426. self.totaldlsize -= self[identifier].dlsize
  427. self.progress -= self[identifier].dlsize
  428. self[identifier] = new DLTracker([], 0)
  429. if(self.totaldlsize === 0) {
  430. win.setProgressBar(-1)
  431. self.emit('dlcomplete')
  432. }
  433. })
  434. return true
  435. }
  436. }
  437. // Validation Functions
  438. /**
  439. * Loads the version data for a given minecraft version.
  440. *
  441. * @param {String} version - the game version for which to load the index data.
  442. * @param {String} basePath - the absolute file path which will be prepended to the given relative paths.
  443. * @param {Boolean} force - optional. If true, the version index will be downloaded even if it exists locally. Defaults to false.
  444. * @returns {Promise.<Object>} - Promise which resolves to the version data object.
  445. */
  446. loadVersionData(version, basePath, force = false){
  447. return new Promise(function(fulfill, reject){
  448. const name = version + '.json'
  449. const url = 'https://s3.amazonaws.com/Minecraft.Download/versions/' + version + '/' + name
  450. const versionPath = path.join(basePath, 'versions', version)
  451. const versionFile = path.join(versionPath, name)
  452. if(!fs.existsSync(versionFile) || force){
  453. //This download will never be tracked as it's essential and trivial.
  454. request.head(url, function(err, res, body){
  455. console.log('Preparing download of ' + version + ' assets.')
  456. mkpath.sync(versionPath)
  457. const stream = request(url).pipe(fs.createWriteStream(versionFile))
  458. stream.on('finish', function(){
  459. fulfill(JSON.parse(fs.readFileSync(versionFile)))
  460. })
  461. })
  462. } else {
  463. fulfill(JSON.parse(fs.readFileSync(versionFile)))
  464. }
  465. })
  466. }
  467. /**
  468. * Public asset validation function. This function will handle the validation of assets.
  469. * It will parse the asset index specified in the version data, analyzing each
  470. * asset entry. In this analysis it will check to see if the local file exists and is valid.
  471. * If not, it will be added to the download queue for the 'assets' identifier.
  472. *
  473. * @param {Object} versionData - the version data for the assets.
  474. * @param {String} basePath - the absolute file path which will be prepended to the given relative paths.
  475. * @param {Boolean} force - optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  476. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  477. */
  478. validateAssets(versionData, basePath, force = false){
  479. const self = this
  480. return new Promise(function(fulfill, reject){
  481. self._assetChainIndexData(versionData, basePath, force).then(() => {
  482. fulfill()
  483. })
  484. })
  485. }
  486. //Chain the asset tasks to provide full async. The below functions are private.
  487. /**
  488. * Private function used to chain the asset validation process. This function retrieves
  489. * the index data.
  490. * @param {Object} versionData
  491. * @param {String} basePath
  492. * @param {Boolean} force
  493. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  494. */
  495. _assetChainIndexData(versionData, basePath, force = false){
  496. const self = this
  497. return new Promise(function(fulfill, reject){
  498. //Asset index constants.
  499. const assetIndex = versionData.assetIndex
  500. const name = assetIndex.id + '.json'
  501. const indexPath = path.join(basePath, 'assets', 'indexes')
  502. const assetIndexLoc = path.join(indexPath, name)
  503. let data = null
  504. if(!fs.existsSync(assetIndexLoc) || force){
  505. console.log('Downloading ' + versionData.id + ' asset index.')
  506. mkpath.sync(indexPath)
  507. const stream = request(assetIndex.url).pipe(fs.createWriteStream(assetIndexLoc))
  508. stream.on('finish', function() {
  509. data = JSON.parse(fs.readFileSync(assetIndexLoc, 'utf-8'))
  510. self._assetChainValidateAssets(versionData, basePath, data).then(() => {
  511. fulfill()
  512. })
  513. })
  514. } else {
  515. data = JSON.parse(fs.readFileSync(assetIndexLoc, 'utf-8'))
  516. self._assetChainValidateAssets(versionData, basePath, data).then(() => {
  517. fulfill()
  518. })
  519. }
  520. })
  521. }
  522. /**
  523. * Private function used to chain the asset validation process. This function processes
  524. * the assets and enqueues missing or invalid files.
  525. * @param {Object} versionData
  526. * @param {String} basePath
  527. * @param {Boolean} force
  528. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  529. */
  530. _assetChainValidateAssets(versionData, basePath, indexData){
  531. const self = this
  532. return new Promise(function(fulfill, reject){
  533. //Asset constants
  534. const resourceURL = 'http://resources.download.minecraft.net/'
  535. const localPath = path.join(basePath, 'assets')
  536. const indexPath = path.join(localPath, 'indexes')
  537. const objectPath = path.join(localPath, 'objects')
  538. const assetDlQueue = []
  539. let dlSize = 0;
  540. //const objKeys = Object.keys(data.objects)
  541. async.forEachOfLimit(indexData.objects, 10, function(value, key, cb){
  542. const hash = value.hash
  543. const assetName = path.join(hash.substring(0, 2), hash)
  544. const urlName = hash.substring(0, 2) + "/" + hash
  545. const ast = new Asset(key, hash, String(value.size), resourceURL + urlName, path.join(objectPath, assetName))
  546. if(!AssetGuard._validateLocal(ast.to, 'sha1', ast.hash)){
  547. dlSize += (ast.size*1)
  548. assetDlQueue.push(ast)
  549. }
  550. cb()
  551. }, function(err){
  552. self.assets = new DLTracker(assetDlQueue, dlSize)
  553. fulfill()
  554. })
  555. })
  556. }
  557. /**
  558. * Public library validation function. This function will handle the validation of libraries.
  559. * It will parse the version data, analyzing each library entry. In this analysis, it will
  560. * check to see if the local file exists and is valid. If not, it will be added to the download
  561. * queue for the 'libraries' identifier.
  562. *
  563. * @param {Object} versionData - the version data for the assets.
  564. * @param {String} basePath - the absolute file path which will be prepended to the given relative paths.
  565. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  566. */
  567. validateLibraries(versionData, basePath){
  568. const self = this
  569. return new Promise(function(fulfill, reject){
  570. const libArr = versionData.libraries
  571. const libPath = path.join(basePath, 'libraries')
  572. const libDlQueue = []
  573. let dlSize = 0
  574. //Check validity of each library. If the hashs don't match, download the library.
  575. async.eachLimit(libArr, 5, function(lib, cb){
  576. if(Library.validateRules(lib.rules)){
  577. let artifact = (lib.natives == null) ? lib.downloads.artifact : lib.downloads.classifiers[lib.natives[Library.mojangFriendlyOS()]]
  578. const libItm = new Library(lib.name, artifact.sha1, artifact.size, artifact.url, path.join(libPath, artifact.path))
  579. if(!AssetGuard._validateLocal(libItm.to, 'sha1', libItm.hash)){
  580. dlSize += (libItm.size*1)
  581. libDlQueue.push(libItm)
  582. }
  583. }
  584. cb()
  585. }, function(err){
  586. self.libraries = new DLTracker(libDlQueue, dlSize)
  587. fulfill()
  588. })
  589. })
  590. }
  591. /**
  592. * Public miscellaneous mojang file validation function. These files will be enqueued under
  593. * the 'files' identifier.
  594. *
  595. * @param {Object} versionData - the version data for the assets.
  596. * @param {String} basePath - the absolute file path which will be prepended to the given relative paths.
  597. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  598. */
  599. validateMiscellaneous(versionData, basePath){
  600. const self = this
  601. return new Promise(async function(fulfill, reject){
  602. await self.validateClient(versionData, basePath)
  603. await self.validateLogConfig(versionData, basePath)
  604. fulfill()
  605. })
  606. }
  607. /**
  608. * Validate client file - artifact renamed from client.jar to '{version}'.jar.
  609. *
  610. * @param {Object} versionData - the version data for the assets.
  611. * @param {String} basePath - the absolute file path which will be prepended to the given relative paths.
  612. * @param {Boolean} force - optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  613. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  614. */
  615. validateClient(versionData, basePath, force = false){
  616. const self = this
  617. return new Promise(function(fulfill, reject){
  618. const clientData = versionData.downloads.client
  619. const version = versionData.id
  620. const targetPath = path.join(basePath, 'versions', version)
  621. const targetFile = version + '.jar'
  622. let client = new Asset(version + ' client', clientData.sha1, clientData.size, clientData.url, path.join(targetPath, targetFile))
  623. if(!AssetGuard._validateLocal(client.to, 'sha1', client.hash) || force){
  624. self.files.dlqueue.push(client)
  625. self.files.dlsize += client.size*1
  626. fulfill()
  627. } else {
  628. fulfill()
  629. }
  630. })
  631. }
  632. /**
  633. * Validate log config.
  634. *
  635. * @param {Object} versionData - the version data for the assets.
  636. * @param {String} basePath - the absolute file path which will be prepended to the given relative paths.
  637. * @param {Boolean} force - optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  638. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  639. */
  640. validateLogConfig(versionData, basePath){
  641. const self = this
  642. return new Promise(function(fulfill, reject){
  643. const client = versionData.logging.client
  644. const file = client.file
  645. const targetPath = path.join(basePath, 'assets', 'log_configs')
  646. let logConfig = new Asset(file.id, file.sha1, file.size, file.url, path.join(targetPath, file.id))
  647. if(!AssetGuard._validateLocal(logConfig.to, 'sha1', logConfig.hash)){
  648. self.files.dlqueue.push(logConfig)
  649. self.files.dlsize += logConfig.size*1
  650. fulfill()
  651. } else {
  652. fulfill()
  653. }
  654. })
  655. }
  656. /**
  657. * Validate the distribution.
  658. *
  659. * @param {String} serverpackid - The id of the server to validate.
  660. * @param {String} basePath - the absolute file path which will be prepended to the given relative paths.
  661. * @returns {Promise.<Object>} - A promise which resolves to the server distribution object.
  662. */
  663. validateDistribution(serverpackid, basePath){
  664. const self = this
  665. return new Promise(function(fulfill, reject){
  666. self._chainValidateDistributionIndex(basePath).then((value) => {
  667. let servers = value.servers
  668. let serv = null
  669. for(let i=0; i<servers.length; i++){
  670. if(servers[i].id === serverpackid){
  671. serv = servers[i]
  672. break
  673. }
  674. }
  675. self.forge = self._parseDistroModules(serv.modules, basePath, serv.mc_version)
  676. //Correct our workaround here.
  677. let decompressqueue = self.forge.callback
  678. self.forge.callback = function(asset){
  679. if(asset.to.toLowerCase().endsWith('.pack.xz')){
  680. AssetGuard._extractPackXZ([asset.to])
  681. }
  682. if(asset.type === 'forge-hosted' || asset.type === 'forge'){
  683. AssetGuard._finalizeForgeAsset(asset, basePath)
  684. }
  685. }
  686. fulfill(serv)
  687. })
  688. })
  689. }
  690. //TODO The distro index should be downloaded in the 'pre-loader'. This is because
  691. //we will eventually NEED the index to generate the server list on the ui.
  692. _chainValidateDistributionIndex(basePath){
  693. return new Promise(function(fulfill, reject){
  694. //const distroURL = 'http://mc.westeroscraft.com/WesterosCraftLauncher/westeroscraft.json'
  695. const targetFile = path.join(basePath, 'westeroscraft.json')
  696. //TEMP WORKAROUND TO TEST WHILE THIS IS NOT HOSTED
  697. fs.readFile(path.join(__dirname, '..', 'westeroscraft.json'), 'utf-8', (err, data) => {
  698. fulfill(JSON.parse(data))
  699. })
  700. })
  701. }
  702. _parseDistroModules(modules, basePath, version){
  703. let alist = []
  704. let asize = 0;
  705. //This may be removed soon, considering the most efficient way to extract.
  706. let decompressqueue = []
  707. for(let i=0; i<modules.length; i++){
  708. let ob = modules[i]
  709. let obType = ob.type
  710. let obArtifact = ob.artifact
  711. let obPath = obArtifact.path == null ? AssetGuard._resolvePath(ob.id, obArtifact.extension) : obArtifact.path
  712. switch(obType){
  713. case 'forge-hosted':
  714. case 'forge':
  715. case 'library':
  716. obPath = path.join(basePath, 'libraries', obPath)
  717. break
  718. case 'forgemod':
  719. //obPath = path.join(basePath, 'mods', obPath)
  720. obPath = path.join(basePath, 'modstore', obPath)
  721. break
  722. case 'litemod':
  723. //obPath = path.join(basePath, 'mods', version, obPath)
  724. obPath = path.join(basePath, 'modstore', obPath)
  725. break
  726. case 'file':
  727. default:
  728. obPath = path.join(basePath, obPath)
  729. }
  730. let artifact = new DistroModule(ob.id, obArtifact.MD5, obArtifact.size, obArtifact.url, obPath, obType)
  731. const validationPath = obPath.toLowerCase().endsWith('.pack.xz') ? obPath.substring(0, obPath.toLowerCase().lastIndexOf('.pack.xz')) : obPath
  732. if(!AssetGuard._validateLocal(validationPath, 'MD5', artifact.hash)){
  733. asize += artifact.size*1
  734. alist.push(artifact)
  735. if(validationPath !== obPath) decompressqueue.push(obPath)
  736. }
  737. //Recursively process the submodules then combine the results.
  738. if(ob.sub_modules != null){
  739. let dltrack = this._parseDistroModules(ob.sub_modules, basePath, version)
  740. asize += dltrack.dlsize*1
  741. alist = alist.concat(dltrack.dlqueue)
  742. decompressqueue = decompressqueue.concat(dltrack.callback)
  743. }
  744. }
  745. //Since we have no callback at this point, we use this value to store the decompressqueue.
  746. return new DLTracker(alist, asize, decompressqueue)
  747. }
  748. /**
  749. * Loads Forge's version.json data into memory for the specified server id.
  750. *
  751. * @param {String} serverpack - The id of the server to load Forge data for.
  752. * @param {String} basePath
  753. * @returns {Promise.<Object>} - A promise which resolves to Forge's version.json data.
  754. */
  755. loadForgeData(serverpack, basePath){
  756. const self = this
  757. return new Promise(async function(fulfill, reject){
  758. let distro = await self._chainValidateDistributionIndex(basePath)
  759. const servers = distro.servers
  760. let serv = null
  761. for(let i=0; i<servers.length; i++){
  762. if(servers[i].id === serverpack){
  763. serv = servers[i]
  764. break
  765. }
  766. }
  767. const modules = serv.modules
  768. for(let i=0; i<modules.length; i++){
  769. const ob = modules[i]
  770. if(ob.type === 'forge-hosted' || ob.type === 'forge'){
  771. let obArtifact = ob.artifact
  772. let obPath = obArtifact.path == null ? path.join(basePath, 'libraries', AssetGuard._resolvePath(ob.id, obArtifact.extension)) : obArtifact.path
  773. let asset = new DistroModule(ob.id, obArtifact.MD5, obArtifact.size, obArtifact.url, obPath, ob.type)
  774. let forgeData = await AssetGuard._finalizeForgeAsset(asset, basePath)
  775. fulfill(forgeData)
  776. return
  777. }
  778. }
  779. reject('No forge module found!')
  780. })
  781. }
  782. _parseForgeLibraries(){
  783. /* TODO
  784. * Forge asset validations are already implemented. When there's nothing much
  785. * to work on, implement forge downloads using forge's version.json. This is to
  786. * have the code on standby if we ever need it (since it's half implemented already).
  787. */
  788. }
  789. /**
  790. * This function will initiate the download processed for the specified identifiers. If no argument is
  791. * given, all identifiers will be initiated. Note that in order for files to be processed you need to run
  792. * the processing function corresponding to that identifier. If you run this function without processing
  793. * the files, it is likely nothing will be enqueued in the object and processing will complete
  794. * immediately. Once all downloads are complete, this function will fire the 'dlcomplete' event on the
  795. * global object instance.
  796. *
  797. * @param {Array.<{id: string, limit: number}>} identifiers - optional. The identifiers to process and corresponding parallel async task limit.
  798. */
  799. processDlQueues(identifiers = [{id:'assets', limit:20}, {id:'libraries', limit:5}, {id:'files', limit:5}, {id:'forge', limit:5}]){
  800. this.progress = 0;
  801. let win = remote.getCurrentWindow()
  802. let shouldFire = true
  803. // Assign dltracking variables.
  804. this.totaldlsize = 0
  805. this.progress = 0
  806. for(let i=0; i<identifiers.length; i++){
  807. this.totaldlsize += this[identifiers[i].id].dlsize
  808. }
  809. for(let i=0; i<identifiers.length; i++){
  810. let iden = identifiers[i]
  811. let r = this.startAsyncProcess(iden.id, iden.limit)
  812. if(r) shouldFire = false
  813. }
  814. if(shouldFire){
  815. this.emit('dlcomplete')
  816. }
  817. }
  818. }
  819. module.exports = {
  820. AssetGuard,
  821. Asset,
  822. Library
  823. }