assetguard.js 39 KB

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