assetguard.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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 EventEmitter = require('events');
  32. const {remote} = require('electron')
  33. // Classes
  34. /** Class representing a base asset. */
  35. class Asset{
  36. /**
  37. * Create an asset.
  38. *
  39. * @param {any} id - id of the asset.
  40. * @param {String} hash - hash value of the asset.
  41. * @param {Number} size - size in bytes of the asset.
  42. * @param {String} from - url where the asset can be found.
  43. * @param {String} to - absolute local file path of the asset.
  44. */
  45. constructor(id, hash, size, from, to){
  46. this.id = id
  47. this.hash = hash
  48. this.size = size
  49. this.from = from
  50. this.to = to
  51. }
  52. }
  53. /** Class representing a mojang library. */
  54. class Library extends Asset{
  55. /**
  56. * Converts the process.platform OS names to match mojang's OS names.
  57. */
  58. static mojangFriendlyOS(){
  59. const opSys = process.platform
  60. if (opSys === 'darwin') {
  61. return 'osx';
  62. } else if (opSys === 'win32'){
  63. return 'windows';
  64. } else if (opSys === 'linux'){
  65. return 'linux';
  66. } else {
  67. return 'unknown_os';
  68. }
  69. }
  70. /**
  71. * Checks whether or not a library is valid for download on a particular OS, following
  72. * the rule format specified in the mojang version data index. If the allow property has
  73. * an OS specified, then the library can ONLY be downloaded on that OS. If the disallow
  74. * property has instead specified an OS, the library can be downloaded on any OS EXCLUDING
  75. * the one specified.
  76. *
  77. * @param {Object} rules - the Library's download rules.
  78. * @returns {Boolean} - true if the Library follows the specified rules, otherwise false.
  79. */
  80. static validateRules(rules){
  81. if(rules == null) return true
  82. let result = true
  83. rules.forEach(function(rule){
  84. const action = rule['action']
  85. const osProp = rule['os']
  86. if(action != null){
  87. if(osProp != null){
  88. const osName = osProp['name']
  89. const osMoj = Library.mojangFriendlyOS()
  90. if(action === 'allow'){
  91. result = osName === osMoj
  92. return
  93. } else if(action === 'disallow'){
  94. result = osName !== osMoj
  95. return
  96. }
  97. }
  98. }
  99. })
  100. return result
  101. }
  102. }
  103. /**
  104. * Class representing a download tracker. This is used to store meta data
  105. * about a download queue, including the queue itself.
  106. */
  107. class DLTracker {
  108. /**
  109. * Create a DLTracker
  110. *
  111. * @param {Array.<Asset>} dlqueue - an array containing assets queued for download.
  112. * @param {Number} dlsize - the combined size of each asset in the download queue array.
  113. */
  114. constructor(dlqueue, dlsize){
  115. this.dlqueue = dlqueue
  116. this.dlsize = dlsize
  117. }
  118. }
  119. /**
  120. * Central object class used for control flow. This object stores data about
  121. * categories of downloads. Each category is assigned an identifier with a
  122. * DLTracker object as its value. Combined information is also stored, such as
  123. * the total size of all the queued files in each category. This event is used
  124. * to emit events so that external modules can listen into processing done in
  125. * this module.
  126. */
  127. class AssetGuard extends EventEmitter{
  128. /**
  129. * AssetGuard class should only ever have one instance which is defined in
  130. * this module. On creation the object's properties are never-null default
  131. * values. Each identifier is resolved to an empty DLTracker.
  132. */
  133. constructor(){
  134. super()
  135. this.totaldlsize = 0;
  136. this.progress = 0;
  137. this.assets = new DLTracker([], 0)
  138. this.libraries = new DLTracker([], 0)
  139. this.files = new DLTracker([], 0)
  140. }
  141. }
  142. /**
  143. * Global static final instance of AssetGuard
  144. */
  145. const instance = new AssetGuard()
  146. // Utility Functions
  147. /**
  148. * Validate that a file exists and matches a given hash value.
  149. *
  150. * @param {String} filePath - the path of the file to validate.
  151. * @param {String} algo - the hash algorithm to check against.
  152. * @param {String} hash - the existing hash to check against.
  153. * @returns {Boolean} - true if the file exists and calculated hash matches the given hash, otherwise false.
  154. */
  155. function validateLocal(filePath, algo, hash){
  156. if(fs.existsSync(filePath)){
  157. let fileName = path.basename(filePath)
  158. let shasum = crypto.createHash(algo)
  159. let content = fs.readFileSync(filePath)
  160. shasum.update(content)
  161. let calcdhash = shasum.digest('hex')
  162. return calcdhash === hash
  163. }
  164. return false;
  165. }
  166. /**
  167. * Initiate an async download process for an AssetGuard DLTracker.
  168. *
  169. * @param {String} identifier - the identifier of the AssetGuard DLTracker.
  170. * @param {Number} limit - optional. The number of async processes to run in parallel.
  171. * @returns {Boolean} - true if the process began, otherwise false.
  172. */
  173. function startAsyncProcess(identifier, limit = 5){
  174. let win = remote.getCurrentWindow()
  175. let acc = 0
  176. const concurrentDlQueue = instance[identifier].dlqueue.slice(0)
  177. if(concurrentDlQueue.length === 0){
  178. return false
  179. } else {
  180. async.eachLimit(concurrentDlQueue, limit, function(asset, cb){
  181. mkpath.sync(path.join(asset.to, ".."))
  182. let req = request(asset.from)
  183. let writeStream = fs.createWriteStream(asset.to)
  184. req.pipe(writeStream)
  185. req.on('data', function(chunk){
  186. instance.progress += chunk.length
  187. acc += chunk.length
  188. instance.emit(identifier + 'dlprogress', acc)
  189. //console.log(identifier + ' Progress', acc/instance[identifier].dlsize)
  190. win.setProgressBar(instance.progress/instance.totaldlsize)
  191. })
  192. writeStream.on('close', cb)
  193. }, function(err){
  194. if(err){
  195. instance.emit(identifier + 'dlerror')
  196. console.log('An item in ' + identifier + ' failed to process');
  197. } else {
  198. instance.emit(identifier + 'dlcomplete')
  199. console.log('All ' + identifier + ' have been processed successfully')
  200. }
  201. instance.totaldlsize -= instance[identifier].dlsize
  202. instance[identifier] = new DLTracker([], 0)
  203. if(instance.totaldlsize === 0) {
  204. win.setProgressBar(-1)
  205. instance.emit('dlcomplete')
  206. }
  207. })
  208. return true
  209. }
  210. }
  211. // Validation Functions
  212. /**
  213. * Loads the version data for a given minecraft version.
  214. *
  215. * @param {String} version - the game version for which to load the index data.
  216. * @param {String} basePath - the absolute file path which will be prepended to the given relative paths.
  217. * @param {Boolean} force - optional. If true, the version index will be downloaded even if it exists locally. Defaults to false.
  218. * @returns {Promise.<Object>} - Promise which resolves to the version data object.
  219. */
  220. function loadVersionData(version, basePath, force = false){
  221. return new Promise(function(fulfill, reject){
  222. const name = version + '.json'
  223. const url = 'https://s3.amazonaws.com/Minecraft.Download/versions/' + version + '/' + name
  224. const versionPath = path.join(basePath, 'versions', version)
  225. const versionFile = path.join(versionPath, name)
  226. if(!fs.existsSync(versionFile) || force){
  227. //This download will never be tracked as it's essential and trivial.
  228. request.head(url, function(err, res, body){
  229. console.log('Preparing download of ' + version + ' assets.')
  230. mkpath.sync(versionPath)
  231. const stream = request(url).pipe(fs.createWriteStream(versionFile))
  232. stream.on('finish', function(){
  233. fulfill(JSON.parse(fs.readFileSync(versionFile)))
  234. })
  235. })
  236. } else {
  237. fulfill(JSON.parse(fs.readFileSync(versionFile)))
  238. }
  239. })
  240. }
  241. /**
  242. * Public asset validation function. This function will handle the validation of assets.
  243. * It will parse the asset index specified in the version data, analyzing each
  244. * asset entry. In this analysis it will check to see if the local file exists and is valid.
  245. * If not, it will be added to the download queue for the 'assets' identifier.
  246. *
  247. * @param {Object} versionData - the version data for the assets.
  248. * @param {String} basePath - the absolute file path which will be prepended to the given relative paths.
  249. * @param {Boolean} force - optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  250. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  251. */
  252. function validateAssets(versionData, basePath, force = false){
  253. return new Promise(function(fulfill, reject){
  254. _assetChainIndexData(versionData, basePath, force).then(() => {
  255. fulfill()
  256. })
  257. })
  258. }
  259. //Chain the asset tasks to provide full async. The below functions are private.
  260. /**
  261. * Private function used to chain the asset validation process. This function retrieves
  262. * the index data.
  263. * @param {Object} versionData
  264. * @param {String} basePath
  265. * @param {Boolean} force
  266. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  267. */
  268. function _assetChainIndexData(versionData, basePath, force = false){
  269. return new Promise(function(fulfill, reject){
  270. //Asset index constants.
  271. const assetIndex = versionData.assetIndex
  272. const name = assetIndex.id + '.json'
  273. const indexPath = path.join(basePath, 'assets', 'indexes')
  274. const assetIndexLoc = path.join(indexPath, name)
  275. let data = null
  276. if(!fs.existsSync(assetIndexLoc) || force){
  277. console.log('Downloading ' + versionData.id + ' asset index.')
  278. mkpath.sync(indexPath)
  279. const stream = request(assetIndex.url).pipe(fs.createWriteStream(assetIndexLoc))
  280. stream.on('finish', function() {
  281. data = JSON.parse(fs.readFileSync(assetIndexLoc, 'utf-8'))
  282. _assetChainValidateAssets(versionData, basePath, data).then(() => {
  283. fulfill()
  284. })
  285. })
  286. } else {
  287. data = JSON.parse(fs.readFileSync(assetIndexLoc, 'utf-8'))
  288. _assetChainValidateAssets(versionData, basePath, data).then(() => {
  289. fulfill()
  290. })
  291. }
  292. })
  293. }
  294. /**
  295. * Private function used to chain the asset validation process. This function processes
  296. * the assets and enqueues missing or invalid files.
  297. * @param {Object} versionData
  298. * @param {String} basePath
  299. * @param {Boolean} force
  300. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  301. */
  302. function _assetChainValidateAssets(versionData, basePath, indexData){
  303. return new Promise(function(fulfill, reject){
  304. //Asset constants
  305. const resourceURL = 'http://resources.download.minecraft.net/'
  306. const localPath = path.join(basePath, 'assets')
  307. const indexPath = path.join(localPath, 'indexes')
  308. const objectPath = path.join(localPath, 'objects')
  309. const assetDlQueue = []
  310. let dlSize = 0;
  311. //const objKeys = Object.keys(data.objects)
  312. async.forEachOfLimit(indexData.objects, 10, function(value, key, cb){
  313. const hash = value.hash
  314. const assetName = path.join(hash.substring(0, 2), hash)
  315. const urlName = hash.substring(0, 2) + "/" + hash
  316. const ast = new Asset(key, hash, String(value.size), resourceURL + urlName, path.join(objectPath, assetName))
  317. if(!validateLocal(ast.to, 'sha1', ast.hash)){
  318. dlSize += (ast.size*1)
  319. assetDlQueue.push(ast)
  320. }
  321. cb()
  322. }, function(err){
  323. instance.assets = new DLTracker(assetDlQueue, dlSize)
  324. instance.totaldlsize += dlSize
  325. fulfill()
  326. })
  327. })
  328. }
  329. /**
  330. * Public library validation function. This function will handle the validation of libraries.
  331. * It will parse the version data, analyzing each library entry. In this analysis, it will
  332. * check to see if the local file exists and is valid. If not, it will be added to the download
  333. * queue for the 'libraries' identifier.
  334. *
  335. * @param {Object} versionData - the version data for the assets.
  336. * @param {String} basePath - the absolute file path which will be prepended to the given relative paths.
  337. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  338. */
  339. function validateLibraries(versionData, basePath){
  340. return new Promise(function(fulfill, reject){
  341. const libArr = versionData.libraries
  342. const libPath = path.join(basePath, 'libraries')
  343. const libDlQueue = []
  344. let dlSize = 0
  345. //Check validity of each library. If the hashs don't match, download the library.
  346. async.eachLimit(libArr, 5, function(lib, cb){
  347. if(Library.validateRules(lib.rules)){
  348. let artifact = (lib.natives == null) ? lib.downloads.artifact : lib.downloads.classifiers[lib.natives[Library.mojangFriendlyOS()]]
  349. const libItm = new Library(lib.name, artifact.sha1, artifact.size, artifact.url, path.join(libPath, artifact.path))
  350. if(!validateLocal(libItm.to, 'sha1', libItm.hash)){
  351. dlSize += (libItm.size*1)
  352. libDlQueue.push(libItm)
  353. }
  354. }
  355. cb()
  356. }, function(err){
  357. instance.libraries = new DLTracker(libDlQueue, dlSize)
  358. instance.totaldlsize += dlSize
  359. fulfill()
  360. })
  361. })
  362. }
  363. /**
  364. * Public miscellaneous mojang file validation function. These files will be enqueued under
  365. * the 'files' identifier.
  366. *
  367. * @param {Object} versionData - the version data for the assets.
  368. * @param {String} basePath - the absolute file path which will be prepended to the given relative paths.
  369. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  370. */
  371. function validateMiscellaneous(versionData, basePath){
  372. return new Promise(async function(fulfill, reject){
  373. await validateClient(versionData, basePath)
  374. await validateLogConfig(versionData, basePath)
  375. fulfill()
  376. })
  377. }
  378. /**
  379. * Validate client file - artifact renamed from client.jar to '{version}'.jar.
  380. *
  381. * @param {Object} versionData - the version data for the assets.
  382. * @param {String} basePath - the absolute file path which will be prepended to the given relative paths.
  383. * @param {Boolean} force - optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  384. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  385. */
  386. function validateClient(versionData, basePath, force = false){
  387. return new Promise(function(fulfill, reject){
  388. const clientData = versionData.downloads.client
  389. const version = versionData.id
  390. const targetPath = path.join(basePath, 'versions', version)
  391. const targetFile = version + '.jar'
  392. let client = new Asset(version + ' client', clientData.sha1, clientData.size, clientData.url, path.join(targetPath, targetFile))
  393. if(!validateLocal(client.to, 'sha1', client.hash) || force){
  394. instance.files.dlqueue.push(client)
  395. instance.files.dlsize += client.size*1
  396. fulfill()
  397. } else {
  398. fulfill()
  399. }
  400. })
  401. }
  402. /**
  403. * Validate log config.
  404. *
  405. * @param {Object} versionData - the version data for the assets.
  406. * @param {String} basePath - the absolute file path which will be prepended to the given relative paths.
  407. * @param {Boolean} force - optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  408. * @returns {Promise.<Void>} - An empty promise to indicate the async processing has completed.
  409. */
  410. function validateLogConfig(versionData, basePath){
  411. return new Promise(function(fulfill, reject){
  412. const client = versionData.logging.client
  413. const file = client.file
  414. const targetPath = path.join(basePath, 'assets', 'log_configs')
  415. let logConfig = new Asset(file.id, file.sha1, file.size, file.url, path.join(targetPath, file.id))
  416. if(!validateLocal(logConfig.to, 'sha1', logConfig.hash)){
  417. instance.files.dlqueue.push(logConfig)
  418. instance.files.dlsize += client.size*1
  419. fulfill()
  420. } else {
  421. fulfill()
  422. }
  423. })
  424. }
  425. /**
  426. * This function will initiate the download processed for the specified identifiers. If no argument is
  427. * given, all identifiers will be initiated. Note that in order for files to be processed you need to run
  428. * the processing function corresponding to that identifier. If you run this function without processing
  429. * the files, it is likely nothing will be enqueued in the global object and processing will complete
  430. * immediately. Once all downloads are complete, this function will fire the 'dlcomplete' event on the
  431. * global object instance.
  432. *
  433. * @param {Array.<{id: string, limit: number}>} identifiers - optional. The identifiers to process and corresponding parallel async task limit.
  434. */
  435. function processDlQueues(identifiers = [{id:'assets', limit:20}, {id:'libraries', limit:5}, {id:'files', limit:5}]){
  436. this.progress = 0;
  437. let win = remote.getCurrentWindow()
  438. let shouldFire = true
  439. for(let i=0; i<identifiers.length; i++){
  440. let iden = identifiers[i]
  441. let r = startAsyncProcess(iden.id, iden.limit)
  442. if(r) shouldFire = false
  443. }
  444. if(shouldFire){
  445. instance.emit('dlcomplete')
  446. }
  447. }
  448. module.exports = {
  449. loadVersionData,
  450. validateAssets,
  451. validateLibraries,
  452. validateMiscellaneous,
  453. processDlQueues,
  454. instance,
  455. Asset,
  456. Library
  457. }