assetguard.js 22 KB

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