assetguard.js 22 KB

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