assetguard.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. /**
  2. * AssetGuard
  3. *
  4. * This module aims to provide a comprehensive and stable method for processing
  5. * and downloading game assets for the WesterosCraft server. A central object
  6. * stores download meta for several identifiers (categories). This meta data
  7. * is initially empty until one of the module's processing functions are called.
  8. * That function will process the corresponding asset index and validate any exisitng
  9. * local files. If a file is missing or fails validation, it will be placed into an
  10. * array which acts as a queue. This queue is wrapped in a download tracker object
  11. * so that essential information can be cached. The download tracker object is then
  12. * assigned as the value of the identifier in the central object. These download
  13. * trackers will remain idle until an async process is started to process them.
  14. *
  15. * Once the async process is started, any enqueued assets will be downloaded. The central
  16. * object will emit events throughout the download whose name correspond to the identifier
  17. * being processed. For example, if the 'assets' identifier was being processed, whenever
  18. * the download stream recieves data, the event 'assetsdlprogress' will be emitted off of
  19. * the central object instance. This can be listened to by external modules allowing for
  20. * categorical tracking of the downloading process.
  21. *
  22. * @module assetguard
  23. */
  24. // Requirements
  25. const fs = require('fs')
  26. const request = require('request')
  27. const path = require('path')
  28. const mkpath = require('mkdirp');
  29. const async = require('async')
  30. const crypto = require('crypto')
  31. const AdmZip = require('adm-zip')
  32. const child_process = require('child_process')
  33. const EventEmitter = require('events')
  34. const {remote} = require('electron')
  35. // Classes
  36. /** Class representing a base asset. */
  37. class Asset{
  38. /**
  39. * Create an asset.
  40. *
  41. * @param {any} id - id of the asset.
  42. * @param {String} hash - hash value of the asset.
  43. * @param {Number} size - size in bytes of the asset.
  44. * @param {String} from - url where the asset can be found.
  45. * @param {String} to - absolute local file path of the asset.
  46. */
  47. constructor(id, hash, size, from, to){
  48. this.id = id
  49. this.hash = hash
  50. this.size = size
  51. this.from = from
  52. this.to = to
  53. }
  54. }
  55. /** Class representing a mojang library. */
  56. class Library extends Asset{
  57. /**
  58. * Converts the process.platform OS names to match mojang's OS names.
  59. */
  60. static mojangFriendlyOS(){
  61. const opSys = process.platform
  62. if (opSys === 'darwin') {
  63. return 'osx';
  64. } else if (opSys === 'win32'){
  65. return 'windows';
  66. } else if (opSys === 'linux'){
  67. return 'linux';
  68. } else {
  69. return 'unknown_os';
  70. }
  71. }
  72. /**
  73. * Checks whether or not a library is valid for download on a particular OS, following
  74. * the rule format specified in the mojang version data index. If the allow property has
  75. * an OS specified, then the library can ONLY be downloaded on that OS. If the disallow
  76. * property has instead specified an OS, the library can be downloaded on any OS EXCLUDING
  77. * the one specified.
  78. *
  79. * @param {Object} rules - the Library's download rules.
  80. * @returns {Boolean} - true if the Library follows the specified rules, otherwise false.
  81. */
  82. static validateRules(rules){
  83. if(rules == null) return true
  84. let result = true
  85. rules.forEach(function(rule){
  86. const action = rule['action']
  87. const osProp = rule['os']
  88. if(action != null){
  89. if(osProp != null){
  90. const osName = osProp['name']
  91. const osMoj = Library.mojangFriendlyOS()
  92. if(action === 'allow'){
  93. result = osName === osMoj
  94. return
  95. } else if(action === 'disallow'){
  96. result = osName !== osMoj
  97. return
  98. }
  99. }
  100. }
  101. })
  102. return result
  103. }
  104. }
  105. /**
  106. * Class representing a download tracker. This is used to store meta data
  107. * about a download queue, including the queue itself.
  108. */
  109. class DLTracker {
  110. /**
  111. * Create a DLTracker
  112. *
  113. * @param {Array.<Asset>} dlqueue - an array containing assets queued for download.
  114. * @param {Number} dlsize - the combined size of each asset in the download queue array.
  115. */
  116. constructor(dlqueue, dlsize){
  117. this.dlqueue = dlqueue
  118. this.dlsize = dlsize
  119. }
  120. }
  121. /**
  122. * Central object class used for control flow. This object stores data about
  123. * categories of downloads. Each category is assigned an identifier with a
  124. * DLTracker object as its value. Combined information is also stored, such as
  125. * the total size of all the queued files in each category. This event is used
  126. * to emit events so that external modules can listen into processing done in
  127. * this module.
  128. */
  129. class AssetGuard extends EventEmitter{
  130. /**
  131. * AssetGuard class should only ever have one instance which is defined in
  132. * this module. On creation the object's properties are never-null default
  133. * values. Each identifier is resolved to an empty DLTracker.
  134. */
  135. constructor(){
  136. super()
  137. this.totaldlsize = 0;
  138. this.progress = 0;
  139. this.assets = new DLTracker([], 0)
  140. this.libraries = new DLTracker([], 0)
  141. this.files = new DLTracker([], 0)
  142. this.forge = new DLTracker([], 0)
  143. }
  144. }
  145. /**
  146. * Global static final instance of AssetGuard
  147. */
  148. const instance = new AssetGuard()
  149. // Utility Functions
  150. /**
  151. * Calculates the hash for a file using the specified algorithm.
  152. *
  153. * @param {Buffer} buf - the buffer containing file data.
  154. * @param {String} algo - the hash algorithm.
  155. * @returns {String} - the calculated hash in hex.
  156. */
  157. function _calculateHash(buf, algo){
  158. return crypto.createHash(algo).update(buf).digest('hex')
  159. }
  160. /**
  161. * Used to parse a checksums file. This is specifically designed for
  162. * the checksums.sha1 files found inside the forge scala dependencies.
  163. *
  164. * @param {String} content - the string content of the checksums file.
  165. * @returns {Object} - an object with keys being the file names, and values being the hashes.
  166. */
  167. function _parseChecksumsFile(content){
  168. let finalContent = {}
  169. let lines = content.split('\n')
  170. for(let i=0; i<lines.length; i++){
  171. let bits = lines[i].split(' ')
  172. if(bits[1] == null) {
  173. continue
  174. }
  175. finalContent[bits[1]] = bits[0]
  176. }
  177. return finalContent
  178. }
  179. /**
  180. * Validate that a file exists and matches a given hash value.
  181. *
  182. * @param {String} filePath - the path of the file to validate.
  183. * @param {String} algo - the hash algorithm to check against.
  184. * @param {String} hash - the existing hash to check against.
  185. * @returns {Boolean} - true if the file exists and calculated hash matches the given hash, otherwise false.
  186. */
  187. function _validateLocal(filePath, algo, hash){
  188. if(fs.existsSync(filePath)){
  189. let fileName = path.basename(filePath)
  190. let buf = fs.readFileSync(filePath)
  191. let calcdhash = _calculateHash(buf, algo)
  192. return calcdhash === hash
  193. }
  194. return false;
  195. }
  196. /**
  197. * Validates a file in the style used by forge's version index.
  198. *
  199. * @param {String} filePath - the path of the file to validate.
  200. * @param {Array.<String>} checksums - the checksums listed in the forge version index.
  201. * @returns {Boolean} - true if the file exists and the hashes match, otherwise false.
  202. */
  203. function _validateForgeChecksum(filePath, checksums){
  204. if(fs.existsSync(filePath)){
  205. if(checksums == null || checksums.length === 0){
  206. return true
  207. }
  208. let buf = fs.readFileSync(filePath)
  209. let calcdhash = _calculateHash(buf, 'sha1')
  210. let valid = checksums.includes(calcdhash)
  211. if(!valid && filePath.endsWith('.jar')){
  212. valid = _validateForgeJar(filePath, checksums)
  213. }
  214. return valid
  215. }
  216. return false
  217. }
  218. /**
  219. * Validates a forge jar file dependency who declares a checksums.sha1 file.
  220. * This can be an expensive task as it usually requires that we calculate thousands
  221. * of hashes.
  222. *
  223. * @param {Buffer} buf - the buffer of the jar file.
  224. * @param {Array.<String>} checksums - the checksums listed in the forge version index.
  225. * @returns {Boolean} - true if all hashes declared in the checksums.sha1 file match the actual hashes.
  226. */
  227. function _validateForgeJar(buf, checksums){
  228. const hashes = {}
  229. let expected = {}
  230. const zip = new AdmZip(buf)
  231. const zipEntries = zip.getEntries()
  232. //First pass
  233. for(let i=0; i<zipEntries.length; i++){
  234. let entry = zipEntries[i]
  235. if(entry.entryName === 'checksums.sha1'){
  236. expected = _parseChecksumsFile(zip.readAsText(entry))
  237. }
  238. hashes[entry.entryName] = _calculateHash(entry.getData(), 'sha1')
  239. }
  240. if(!checksums.includes(hashes['checksums.sha1'])){
  241. return false
  242. }
  243. //Check against expected
  244. const expectedEntries = Object.keys(expected)
  245. for(let i=0; i<expectedEntries.length; i++){
  246. if(expected[expectedEntries[i]] !== hashes[expectedEntries[i]]){
  247. return false
  248. }
  249. }
  250. return true
  251. }
  252. function _extractPackXZ(filePath){
  253. const libPath = path.join(__dirname, '..', 'libraries', 'java', 'PackXZExtract.jar')
  254. console.log(libPath)
  255. const child = child_process.spawn('C:\\Program Files\\Java\\jre1.8.0_131\\bin\\javaw.exe', ['-jar', libPath, '-packxz', filePath])
  256. child.stdout.on('data', (data) => {
  257. console.log('minecraft:', data.toString('utf8'))
  258. })
  259. child.stderr.on('data', (data) => {
  260. console.log('minecraft:', data.toString('utf8'))
  261. })
  262. child.on('close', (code, signal) => {
  263. console.log('exited with code', code)
  264. })
  265. }
  266. /**
  267. * Initiate an async download process for an AssetGuard DLTracker.
  268. *
  269. * @param {String} identifier - the identifier of the AssetGuard DLTracker.
  270. * @param {Number} limit - optional. The number of async processes to run in parallel.
  271. * @returns {Boolean} - true if the process began, otherwise false.
  272. */
  273. function startAsyncProcess(identifier, limit = 5){
  274. let win = remote.getCurrentWindow()
  275. let acc = 0
  276. const concurrentDlQueue = instance[identifier].dlqueue.slice(0)
  277. if(concurrentDlQueue.length === 0){
  278. return false
  279. } else {
  280. async.eachLimit(concurrentDlQueue, limit, function(asset, cb){
  281. mkpath.sync(path.join(asset.to, ".."))
  282. let req = request(asset.from)
  283. let writeStream = fs.createWriteStream(asset.to)
  284. req.pipe(writeStream)
  285. req.on('data', function(chunk){
  286. instance.progress += chunk.length
  287. acc += chunk.length
  288. instance.emit(identifier + 'dlprogress', acc)
  289. //console.log(identifier + ' Progress', acc/instance[identifier].dlsize)
  290. win.setProgressBar(instance.progress/instance.totaldlsize)
  291. })
  292. writeStream.on('close', cb)
  293. }, function(err){
  294. if(err){
  295. instance.emit(identifier + 'dlerror')
  296. console.log('An item in ' + identifier + ' failed to process');
  297. } else {
  298. instance.emit(identifier + 'dlcomplete')
  299. console.log('All ' + identifier + ' have been processed successfully')
  300. }
  301. instance.totaldlsize -= instance[identifier].dlsize
  302. instance[identifier] = new DLTracker([], 0)
  303. if(instance.totaldlsize === 0) {
  304. win.setProgressBar(-1)
  305. instance.emit('dlcomplete')
  306. }
  307. })
  308. return true
  309. }
  310. }
  311. // Validation Functions
  312. /**
  313. * Loads the version data for a given minecraft version.
  314. *
  315. * @param {String} version - the game version for which to load the index data.
  316. * @param {String} basePath - the absolute file path which will be prepended to the given relative paths.
  317. * @param {Boolean} force - optional. If true, the version index will be downloaded even if it exists locally. Defaults to false.
  318. * @returns {Promise.<Object>} - Promise which resolves to the version data object.
  319. */
  320. function loadVersionData(version, basePath, force = false){
  321. return new Promise(function(fulfill, reject){
  322. const name = version + '.json'
  323. const url = 'https://s3.amazonaws.com/Minecraft.Download/versions/' + version + '/' + name
  324. const versionPath = path.join(basePath, 'versions', version)
  325. const versionFile = path.join(versionPath, name)
  326. if(!fs.existsSync(versionFile) || force){
  327. //This download will never be tracked as it's essential and trivial.
  328. request.head(url, function(err, res, body){
  329. console.log('Preparing download of ' + version + ' assets.')
  330. mkpath.sync(versionPath)
  331. const stream = request(url).pipe(fs.createWriteStream(versionFile))
  332. stream.on('finish', function(){
  333. fulfill(JSON.parse(fs.readFileSync(versionFile)))
  334. })
  335. })
  336. } else {
  337. fulfill(JSON.parse(fs.readFileSync(versionFile)))
  338. }
  339. })
  340. }
  341. /**
  342. * Public asset validation function. This function will handle the validation of assets.
  343. * It will parse the asset index specified in the version data, analyzing each
  344. * asset entry. In this analysis it will check to see if the local file exists and is valid.
  345. * If not, it will be added to the download queue for the 'assets' identifier.
  346. *
  347. * @param {Object} versionData - the version data for the assets.
  348. * @param {String} basePath - the absolute file path which will be prepended to the given relative paths.
  349. * @param {Boolean} force - optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  350. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  351. */
  352. function validateAssets(versionData, basePath, force = false){
  353. return new Promise(function(fulfill, reject){
  354. _assetChainIndexData(versionData, basePath, force).then(() => {
  355. fulfill()
  356. })
  357. })
  358. }
  359. //Chain the asset tasks to provide full async. The below functions are private.
  360. /**
  361. * Private function used to chain the asset validation process. This function retrieves
  362. * the index data.
  363. * @param {Object} versionData
  364. * @param {String} basePath
  365. * @param {Boolean} force
  366. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  367. */
  368. function _assetChainIndexData(versionData, basePath, force = false){
  369. return new Promise(function(fulfill, reject){
  370. //Asset index constants.
  371. const assetIndex = versionData.assetIndex
  372. const name = assetIndex.id + '.json'
  373. const indexPath = path.join(basePath, 'assets', 'indexes')
  374. const assetIndexLoc = path.join(indexPath, name)
  375. let data = null
  376. if(!fs.existsSync(assetIndexLoc) || force){
  377. console.log('Downloading ' + versionData.id + ' asset index.')
  378. mkpath.sync(indexPath)
  379. const stream = request(assetIndex.url).pipe(fs.createWriteStream(assetIndexLoc))
  380. stream.on('finish', function() {
  381. data = JSON.parse(fs.readFileSync(assetIndexLoc, 'utf-8'))
  382. _assetChainValidateAssets(versionData, basePath, data).then(() => {
  383. fulfill()
  384. })
  385. })
  386. } else {
  387. data = JSON.parse(fs.readFileSync(assetIndexLoc, 'utf-8'))
  388. _assetChainValidateAssets(versionData, basePath, data).then(() => {
  389. fulfill()
  390. })
  391. }
  392. })
  393. }
  394. /**
  395. * Private function used to chain the asset validation process. This function processes
  396. * the assets and enqueues missing or invalid files.
  397. * @param {Object} versionData
  398. * @param {String} basePath
  399. * @param {Boolean} force
  400. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  401. */
  402. function _assetChainValidateAssets(versionData, basePath, indexData){
  403. return new Promise(function(fulfill, reject){
  404. //Asset constants
  405. const resourceURL = 'http://resources.download.minecraft.net/'
  406. const localPath = path.join(basePath, 'assets')
  407. const indexPath = path.join(localPath, 'indexes')
  408. const objectPath = path.join(localPath, 'objects')
  409. const assetDlQueue = []
  410. let dlSize = 0;
  411. //const objKeys = Object.keys(data.objects)
  412. async.forEachOfLimit(indexData.objects, 10, function(value, key, cb){
  413. const hash = value.hash
  414. const assetName = path.join(hash.substring(0, 2), hash)
  415. const urlName = hash.substring(0, 2) + "/" + hash
  416. const ast = new Asset(key, hash, String(value.size), resourceURL + urlName, path.join(objectPath, assetName))
  417. if(!_validateLocal(ast.to, 'sha1', ast.hash)){
  418. dlSize += (ast.size*1)
  419. assetDlQueue.push(ast)
  420. }
  421. cb()
  422. }, function(err){
  423. instance.assets = new DLTracker(assetDlQueue, dlSize)
  424. instance.totaldlsize += dlSize
  425. fulfill()
  426. })
  427. })
  428. }
  429. /**
  430. * Public library validation function. This function will handle the validation of libraries.
  431. * It will parse the version data, analyzing each library entry. In this analysis, it will
  432. * check to see if the local file exists and is valid. If not, it will be added to the download
  433. * queue for the 'libraries' identifier.
  434. *
  435. * @param {Object} versionData - the version data for the assets.
  436. * @param {String} basePath - the absolute file path which will be prepended to the given relative paths.
  437. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  438. */
  439. function validateLibraries(versionData, basePath){
  440. return new Promise(function(fulfill, reject){
  441. const libArr = versionData.libraries
  442. const libPath = path.join(basePath, 'libraries')
  443. const libDlQueue = []
  444. let dlSize = 0
  445. //Check validity of each library. If the hashs don't match, download the library.
  446. async.eachLimit(libArr, 5, function(lib, cb){
  447. if(Library.validateRules(lib.rules)){
  448. let artifact = (lib.natives == null) ? lib.downloads.artifact : lib.downloads.classifiers[lib.natives[Library.mojangFriendlyOS()]]
  449. const libItm = new Library(lib.name, artifact.sha1, artifact.size, artifact.url, path.join(libPath, artifact.path))
  450. if(!_validateLocal(libItm.to, 'sha1', libItm.hash)){
  451. dlSize += (libItm.size*1)
  452. libDlQueue.push(libItm)
  453. }
  454. }
  455. cb()
  456. }, function(err){
  457. instance.libraries = new DLTracker(libDlQueue, dlSize)
  458. instance.totaldlsize += dlSize
  459. fulfill()
  460. })
  461. })
  462. }
  463. /**
  464. * Public miscellaneous mojang file validation function. These files will be enqueued under
  465. * the 'files' identifier.
  466. *
  467. * @param {Object} versionData - the version data for the assets.
  468. * @param {String} basePath - the absolute file path which will be prepended to the given relative paths.
  469. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  470. */
  471. function validateMiscellaneous(versionData, basePath){
  472. return new Promise(async function(fulfill, reject){
  473. await validateClient(versionData, basePath)
  474. await validateLogConfig(versionData, basePath)
  475. fulfill()
  476. })
  477. }
  478. /**
  479. * Validate client file - artifact renamed from client.jar to '{version}'.jar.
  480. *
  481. * @param {Object} versionData - the version data for the assets.
  482. * @param {String} basePath - the absolute file path which will be prepended to the given relative paths.
  483. * @param {Boolean} force - optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  484. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  485. */
  486. function validateClient(versionData, basePath, force = false){
  487. return new Promise(function(fulfill, reject){
  488. const clientData = versionData.downloads.client
  489. const version = versionData.id
  490. const targetPath = path.join(basePath, 'versions', version)
  491. const targetFile = version + '.jar'
  492. let client = new Asset(version + ' client', clientData.sha1, clientData.size, clientData.url, path.join(targetPath, targetFile))
  493. if(!_validateLocal(client.to, 'sha1', client.hash) || force){
  494. instance.files.dlqueue.push(client)
  495. instance.files.dlsize += client.size*1
  496. fulfill()
  497. } else {
  498. fulfill()
  499. }
  500. })
  501. }
  502. /**
  503. * Validate log config.
  504. *
  505. * @param {Object} versionData - the version data for the assets.
  506. * @param {String} basePath - the absolute file path which will be prepended to the given relative paths.
  507. * @param {Boolean} force - optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  508. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  509. */
  510. function validateLogConfig(versionData, basePath){
  511. return new Promise(function(fulfill, reject){
  512. const client = versionData.logging.client
  513. const file = client.file
  514. const targetPath = path.join(basePath, 'assets', 'log_configs')
  515. let logConfig = new Asset(file.id, file.sha1, file.size, file.url, path.join(targetPath, file.id))
  516. if(!_validateLocal(logConfig.to, 'sha1', logConfig.hash)){
  517. instance.files.dlqueue.push(logConfig)
  518. instance.files.dlsize += client.size*1
  519. fulfill()
  520. } else {
  521. fulfill()
  522. }
  523. })
  524. }
  525. function validateForge(){
  526. }
  527. function _validateForgeAssets(forgePath){
  528. }
  529. /**
  530. * This function will initiate the download processed for the specified identifiers. If no argument is
  531. * given, all identifiers will be initiated. Note that in order for files to be processed you need to run
  532. * the processing function corresponding to that identifier. If you run this function without processing
  533. * the files, it is likely nothing will be enqueued in the global object and processing will complete
  534. * immediately. Once all downloads are complete, this function will fire the 'dlcomplete' event on the
  535. * global object instance.
  536. *
  537. * @param {Array.<{id: string, limit: number}>} identifiers - optional. The identifiers to process and corresponding parallel async task limit.
  538. */
  539. function processDlQueues(identifiers = [{id:'assets', limit:20}, {id:'libraries', limit:5}, {id:'files', limit:5}]){
  540. this.progress = 0;
  541. let win = remote.getCurrentWindow()
  542. let shouldFire = true
  543. for(let i=0; i<identifiers.length; i++){
  544. let iden = identifiers[i]
  545. let r = startAsyncProcess(iden.id, iden.limit)
  546. if(r) shouldFire = false
  547. }
  548. if(shouldFire){
  549. instance.emit('dlcomplete')
  550. }
  551. }
  552. module.exports = {
  553. loadVersionData,
  554. validateAssets,
  555. validateLibraries,
  556. validateMiscellaneous,
  557. processDlQueues,
  558. instance,
  559. Asset,
  560. Library,
  561. _extractPackXZ
  562. }