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 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 win = remote.getCurrentWindow()
  461. let acc = 0
  462. const concurrentDlTracker = this[identifier]
  463. const concurrentDlQueue = concurrentDlTracker.dlqueue.slice(0)
  464. if(concurrentDlQueue.length === 0){
  465. return false
  466. } else {
  467. async.eachLimit(concurrentDlQueue, limit, function(asset, cb){
  468. let count = 0;
  469. mkpath.sync(path.join(asset.to, ".."))
  470. let req = request(asset.from)
  471. req.pause()
  472. req.on('response', (resp) => {
  473. if(resp.statusCode === 200){
  474. let writeStream = fs.createWriteStream(asset.to)
  475. writeStream.on('close', () => {
  476. //console.log('DLResults ' + asset.size + ' ' + count + ' ', asset.size === count)
  477. if(concurrentDlTracker.callback != null){
  478. concurrentDlTracker.callback.apply(concurrentDlTracker, [asset])
  479. }
  480. cb()
  481. })
  482. req.pipe(writeStream)
  483. req.resume()
  484. } else {
  485. req.abort()
  486. console.log('Failed to download ' + asset.from + '. Response code', resp.statusCode)
  487. self.progress += asset.size*1
  488. win.setProgressBar(self.progress/self.totaldlsize)
  489. self.emit('totaldlprogress', {acc: self.progress, total: self.totaldlsize})
  490. cb()
  491. }
  492. })
  493. req.on('data', function(chunk){
  494. count += chunk.length
  495. self.progress += chunk.length
  496. acc += chunk.length
  497. self.emit(identifier + 'dlprogress', acc)
  498. //console.log(identifier + ' Progress', acc/this[identifier].dlsize)
  499. win.setProgressBar(self.progress/self.totaldlsize)
  500. self.emit('totaldlprogress', {acc: self.progress, total: self.totaldlsize})
  501. })
  502. }, function(err){
  503. if(err){
  504. self.emit(identifier + 'dlerror')
  505. console.log('An item in ' + identifier + ' failed to process');
  506. } else {
  507. self.emit(identifier + 'dlcomplete')
  508. console.log('All ' + identifier + ' have been processed successfully')
  509. }
  510. self.totaldlsize -= self[identifier].dlsize
  511. self.progress -= self[identifier].dlsize
  512. self[identifier] = new DLTracker([], 0)
  513. if(self.totaldlsize === 0) {
  514. win.setProgressBar(-1)
  515. self.emit('dlcomplete')
  516. }
  517. })
  518. return true
  519. }
  520. }
  521. // Validation Functions
  522. /**
  523. * Loads the version data for a given minecraft version.
  524. *
  525. * @param {String} version - the game version for which to load the index data.
  526. * @param {Boolean} force - optional. If true, the version index will be downloaded even if it exists locally. Defaults to false.
  527. * @returns {Promise.<Object>} - Promise which resolves to the version data object.
  528. */
  529. loadVersionData(version, force = false){
  530. const self = this
  531. return new Promise(function(fulfill, reject){
  532. const name = version + '.json'
  533. const url = 'https://s3.amazonaws.com/Minecraft.Download/versions/' + version + '/' + name
  534. const versionPath = path.join(self.basePath, 'versions', version)
  535. const versionFile = path.join(versionPath, name)
  536. if(!fs.existsSync(versionFile) || force){
  537. //This download will never be tracked as it's essential and trivial.
  538. request.head(url, function(err, res, body){
  539. console.log('Preparing download of ' + version + ' assets.')
  540. mkpath.sync(versionPath)
  541. const stream = request(url).pipe(fs.createWriteStream(versionFile))
  542. stream.on('finish', function(){
  543. fulfill(JSON.parse(fs.readFileSync(versionFile)))
  544. })
  545. })
  546. } else {
  547. fulfill(JSON.parse(fs.readFileSync(versionFile)))
  548. }
  549. })
  550. }
  551. /**
  552. * Public asset validation function. This function will handle the validation of assets.
  553. * It will parse the asset index specified in the version data, analyzing each
  554. * asset entry. In this analysis it will check to see if the local file exists and is valid.
  555. * If not, it will be added to the download queue for the 'assets' identifier.
  556. *
  557. * @param {Object} versionData - the version data for the assets.
  558. * @param {Boolean} force - optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  559. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  560. */
  561. validateAssets(versionData, force = false){
  562. const self = this
  563. return new Promise(function(fulfill, reject){
  564. self._assetChainIndexData(versionData, force).then(() => {
  565. fulfill()
  566. })
  567. })
  568. }
  569. //Chain the asset tasks to provide full async. The below functions are private.
  570. /**
  571. * Private function used to chain the asset validation process. This function retrieves
  572. * the index data.
  573. * @param {Object} versionData
  574. * @param {Boolean} force
  575. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  576. */
  577. _assetChainIndexData(versionData, force = false){
  578. const self = this
  579. return new Promise(function(fulfill, reject){
  580. //Asset index constants.
  581. const assetIndex = versionData.assetIndex
  582. const name = assetIndex.id + '.json'
  583. const indexPath = path.join(self.basePath, 'assets', 'indexes')
  584. const assetIndexLoc = path.join(indexPath, name)
  585. let data = null
  586. if(!fs.existsSync(assetIndexLoc) || force){
  587. console.log('Downloading ' + versionData.id + ' asset index.')
  588. mkpath.sync(indexPath)
  589. const stream = request(assetIndex.url).pipe(fs.createWriteStream(assetIndexLoc))
  590. stream.on('finish', function() {
  591. data = JSON.parse(fs.readFileSync(assetIndexLoc, 'utf-8'))
  592. self._assetChainValidateAssets(versionData, data).then(() => {
  593. fulfill()
  594. })
  595. })
  596. } else {
  597. data = JSON.parse(fs.readFileSync(assetIndexLoc, 'utf-8'))
  598. self._assetChainValidateAssets(versionData, data).then(() => {
  599. fulfill()
  600. })
  601. }
  602. })
  603. }
  604. /**
  605. * Private function used to chain the asset validation process. This function processes
  606. * the assets and enqueues missing or invalid files.
  607. * @param {Object} versionData
  608. * @param {Boolean} force
  609. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  610. */
  611. _assetChainValidateAssets(versionData, indexData){
  612. const self = this
  613. return new Promise(function(fulfill, reject){
  614. //Asset constants
  615. const resourceURL = 'http://resources.download.minecraft.net/'
  616. const localPath = path.join(self.basePath, 'assets')
  617. const indexPath = path.join(localPath, 'indexes')
  618. const objectPath = path.join(localPath, 'objects')
  619. const assetDlQueue = []
  620. let dlSize = 0;
  621. //const objKeys = Object.keys(data.objects)
  622. async.forEachOfLimit(indexData.objects, 10, function(value, key, cb){
  623. const hash = value.hash
  624. const assetName = path.join(hash.substring(0, 2), hash)
  625. const urlName = hash.substring(0, 2) + "/" + hash
  626. const ast = new Asset(key, hash, String(value.size), resourceURL + urlName, path.join(objectPath, assetName))
  627. if(!AssetGuard._validateLocal(ast.to, 'sha1', ast.hash)){
  628. dlSize += (ast.size*1)
  629. assetDlQueue.push(ast)
  630. }
  631. cb()
  632. }, function(err){
  633. self.assets = new DLTracker(assetDlQueue, dlSize)
  634. fulfill()
  635. })
  636. })
  637. }
  638. /**
  639. * Public library validation function. This function will handle the validation of libraries.
  640. * It will parse the version data, analyzing each library entry. In this analysis, it will
  641. * check to see if the local file exists and is valid. If not, it will be added to the download
  642. * queue for the 'libraries' identifier.
  643. *
  644. * @param {Object} versionData - the version data for the assets.
  645. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  646. */
  647. validateLibraries(versionData){
  648. const self = this
  649. return new Promise(function(fulfill, reject){
  650. const libArr = versionData.libraries
  651. const libPath = path.join(self.basePath, 'libraries')
  652. const libDlQueue = []
  653. let dlSize = 0
  654. //Check validity of each library. If the hashs don't match, download the library.
  655. async.eachLimit(libArr, 5, function(lib, cb){
  656. if(Library.validateRules(lib.rules)){
  657. let artifact = (lib.natives == null) ? lib.downloads.artifact : lib.downloads.classifiers[lib.natives[Library.mojangFriendlyOS()]]
  658. const libItm = new Library(lib.name, artifact.sha1, artifact.size, artifact.url, path.join(libPath, artifact.path))
  659. if(!AssetGuard._validateLocal(libItm.to, 'sha1', libItm.hash)){
  660. dlSize += (libItm.size*1)
  661. libDlQueue.push(libItm)
  662. }
  663. }
  664. cb()
  665. }, function(err){
  666. self.libraries = new DLTracker(libDlQueue, dlSize)
  667. fulfill()
  668. })
  669. })
  670. }
  671. /**
  672. * Public miscellaneous mojang file validation function. These files will be enqueued under
  673. * the 'files' identifier.
  674. *
  675. * @param {Object} versionData - the version data for the assets.
  676. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  677. */
  678. validateMiscellaneous(versionData){
  679. const self = this
  680. return new Promise(async function(fulfill, reject){
  681. await self.validateClient(versionData)
  682. await self.validateLogConfig(versionData)
  683. fulfill()
  684. })
  685. }
  686. /**
  687. * Validate client file - artifact renamed from client.jar to '{version}'.jar.
  688. *
  689. * @param {Object} versionData - the version data for the assets.
  690. * @param {Boolean} force - optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  691. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  692. */
  693. validateClient(versionData, force = false){
  694. const self = this
  695. return new Promise(function(fulfill, reject){
  696. const clientData = versionData.downloads.client
  697. const version = versionData.id
  698. const targetPath = path.join(self.basePath, 'versions', version)
  699. const targetFile = version + '.jar'
  700. let client = new Asset(version + ' client', clientData.sha1, clientData.size, clientData.url, path.join(targetPath, targetFile))
  701. if(!AssetGuard._validateLocal(client.to, 'sha1', client.hash) || force){
  702. self.files.dlqueue.push(client)
  703. self.files.dlsize += client.size*1
  704. fulfill()
  705. } else {
  706. fulfill()
  707. }
  708. })
  709. }
  710. /**
  711. * Validate log config.
  712. *
  713. * @param {Object} versionData - the version data for the assets.
  714. * @param {Boolean} force - optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  715. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  716. */
  717. validateLogConfig(versionData){
  718. const self = this
  719. return new Promise(function(fulfill, reject){
  720. const client = versionData.logging.client
  721. const file = client.file
  722. const targetPath = path.join(self.basePath, 'assets', 'log_configs')
  723. let logConfig = new Asset(file.id, file.sha1, file.size, file.url, path.join(targetPath, file.id))
  724. if(!AssetGuard._validateLocal(logConfig.to, 'sha1', logConfig.hash)){
  725. self.files.dlqueue.push(logConfig)
  726. self.files.dlsize += logConfig.size*1
  727. fulfill()
  728. } else {
  729. fulfill()
  730. }
  731. })
  732. }
  733. /**
  734. * Validate the distribution.
  735. *
  736. * @param {String} serverpackid - The id of the server to validate.
  737. * @returns {Promise.<Object>} - A promise which resolves to the server distribution object.
  738. */
  739. validateDistribution(serverpackid){
  740. const self = this
  741. return new Promise(function(fulfill, reject){
  742. AssetGuard.retrieveDistributionData(self.basePath, false).then((value) => {
  743. /*const servers = value.servers
  744. let serv = null
  745. for(let i=0; i<servers.length; i++){
  746. if(servers[i].id === serverpackid){
  747. serv = servers[i]
  748. break
  749. }
  750. }*/
  751. const serv = AssetGuard.getServerById(self.basePath, serverpackid)
  752. self.forge = self._parseDistroModules(serv.modules, serv.mc_version)
  753. //Correct our workaround here.
  754. let decompressqueue = self.forge.callback
  755. self.forge.callback = function(asset){
  756. if(asset.to.toLowerCase().endsWith('.pack.xz')){
  757. AssetGuard._extractPackXZ([asset.to], self.javaexec)
  758. }
  759. if(asset.type === 'forge-hosted' || asset.type === 'forge'){
  760. AssetGuard._finalizeForgeAsset(asset, self.basePath)
  761. }
  762. }
  763. fulfill(serv)
  764. })
  765. })
  766. }
  767. /*//TODO The file should be hosted, the following code is for local testing.
  768. _chainValidateDistributionIndex(basePath){
  769. return new Promise(function(fulfill, reject){
  770. //const distroURL = 'http://mc.westeroscraft.com/WesterosCraftLauncher/westeroscraft.json'
  771. //const targetFile = path.join(basePath, 'westeroscraft.json')
  772. //TEMP WORKAROUND TO TEST WHILE THIS IS NOT HOSTED
  773. fs.readFile(path.join(__dirname, '..', 'westeroscraft.json'), 'utf-8', (err, data) => {
  774. fulfill(JSON.parse(data))
  775. })
  776. })
  777. }*/
  778. _parseDistroModules(modules, version){
  779. let alist = []
  780. let asize = 0;
  781. //This may be removed soon, considering the most efficient way to extract.
  782. let decompressqueue = []
  783. for(let i=0; i<modules.length; i++){
  784. let ob = modules[i]
  785. let obType = ob.type
  786. let obArtifact = ob.artifact
  787. let obPath = obArtifact.path == null ? AssetGuard._resolvePath(ob.id, obArtifact.extension) : obArtifact.path
  788. switch(obType){
  789. case 'forge-hosted':
  790. case 'forge':
  791. case 'library':
  792. obPath = path.join(this.basePath, 'libraries', obPath)
  793. break
  794. case 'forgemod':
  795. //obPath = path.join(this.basePath, 'mods', obPath)
  796. obPath = path.join(this.basePath, 'modstore', obPath)
  797. break
  798. case 'litemod':
  799. //obPath = path.join(this.basePath, 'mods', version, obPath)
  800. obPath = path.join(this.basePath, 'modstore', obPath)
  801. break
  802. case 'file':
  803. default:
  804. obPath = path.join(this.basePath, obPath)
  805. }
  806. let artifact = new DistroModule(ob.id, obArtifact.MD5, obArtifact.size, obArtifact.url, obPath, obType)
  807. const validationPath = obPath.toLowerCase().endsWith('.pack.xz') ? obPath.substring(0, obPath.toLowerCase().lastIndexOf('.pack.xz')) : obPath
  808. if(!AssetGuard._validateLocal(validationPath, 'MD5', artifact.hash)){
  809. asize += artifact.size*1
  810. alist.push(artifact)
  811. if(validationPath !== obPath) decompressqueue.push(obPath)
  812. }
  813. //Recursively process the submodules then combine the results.
  814. if(ob.sub_modules != null){
  815. let dltrack = this._parseDistroModules(ob.sub_modules, version)
  816. asize += dltrack.dlsize*1
  817. alist = alist.concat(dltrack.dlqueue)
  818. decompressqueue = decompressqueue.concat(dltrack.callback)
  819. }
  820. }
  821. //Since we have no callback at this point, we use this value to store the decompressqueue.
  822. return new DLTracker(alist, asize, decompressqueue)
  823. }
  824. /**
  825. * Loads Forge's version.json data into memory for the specified server id.
  826. *
  827. * @param {String} serverpack - The id of the server to load Forge data for.
  828. * @returns {Promise.<Object>} - A promise which resolves to Forge's version.json data.
  829. */
  830. loadForgeData(serverpack){
  831. const self = this
  832. return new Promise(async function(fulfill, reject){
  833. let distro = AssetGuard.retrieveDistributionDataSync(self.basePath)
  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(self.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, self.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. }