assetguard.js 32 KB

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