assetguard.js 40 KB

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