assetguard.js 39 KB

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