assetguard.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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 {todo finish later i'm tired ZZzzzz}
  245. *
  246. */
  247. function validateAssets(versionData, basePath, force = false){
  248. return new Promise(function(fulfill, reject){
  249. _assetChainIndexData(versionData, basePath, force).then(() => {
  250. fulfill()
  251. })
  252. })
  253. }
  254. //Chain the asset tasks to provide full async. The below functions are private.
  255. function _assetChainIndexData(versionData, basePath, force = false){
  256. return new Promise(function(fulfill, reject){
  257. //Asset index constants.
  258. const assetIndex = versionData.assetIndex
  259. const name = assetIndex.id + '.json'
  260. const indexPath = path.join(basePath, 'assets', 'indexes')
  261. const assetIndexLoc = path.join(indexPath, name)
  262. let data = null
  263. if(!fs.existsSync(assetIndexLoc) || force){
  264. console.log('Downloading ' + versionData.id + ' asset index.')
  265. mkpath.sync(indexPath)
  266. const stream = request(assetIndex.url).pipe(fs.createWriteStream(assetIndexLoc))
  267. stream.on('finish', function() {
  268. data = JSON.parse(fs.readFileSync(assetIndexLoc, 'utf-8'))
  269. _assetChainValidateAssets(versionData, basePath, data).then(() => {
  270. fulfill()
  271. })
  272. })
  273. } else {
  274. data = JSON.parse(fs.readFileSync(assetIndexLoc, 'utf-8'))
  275. _assetChainValidateAssets(versionData, basePath, data).then(() => {
  276. fulfill()
  277. })
  278. }
  279. })
  280. }
  281. function _assetChainValidateAssets(versionData, basePath, indexData){
  282. return new Promise(function(fulfill, reject){
  283. //Asset constants
  284. const resourceURL = 'http://resources.download.minecraft.net/'
  285. const localPath = path.join(basePath, 'assets')
  286. const indexPath = path.join(localPath, 'indexes')
  287. const objectPath = path.join(localPath, 'objects')
  288. const assetDlQueue = []
  289. let dlSize = 0;
  290. //const objKeys = Object.keys(data.objects)
  291. async.forEachOfLimit(indexData.objects, 10, function(value, key, cb){
  292. const hash = value.hash
  293. const assetName = path.join(hash.substring(0, 2), hash)
  294. const urlName = hash.substring(0, 2) + "/" + hash
  295. const ast = new Asset(key, hash, String(value.size), resourceURL + urlName, path.join(objectPath, assetName))
  296. if(!validateLocal(ast.to, 'sha1', ast.hash)){
  297. dlSize += (ast.size*1)
  298. assetDlQueue.push(ast)
  299. }
  300. cb()
  301. }, function(err){
  302. instance.assets = new DLTracker(assetDlQueue, dlSize)
  303. instance.totaldlsize += dlSize
  304. fulfill()
  305. })
  306. })
  307. }
  308. /**
  309. * Public library validation method.
  310. */
  311. function validateLibraries(versionData, basePath){
  312. return new Promise(function(fulfill, reject){
  313. const libArr = versionData.libraries
  314. const libPath = path.join(basePath, 'libraries')
  315. const libDlQueue = []
  316. let dlSize = 0
  317. //Check validity of each library. If the hashs don't match, download the library.
  318. async.eachLimit(libArr, 5, function(lib, cb){
  319. if(Library.validateRules(lib.rules)){
  320. let artifact = (lib.natives == null) ? lib.downloads.artifact : lib.downloads.classifiers[lib.natives[Library.mojangFriendlyOS()]]
  321. const libItm = new Library(lib.name, artifact.sha1, artifact.size, artifact.url, path.join(libPath, artifact.path))
  322. if(!validateLocal(libItm.to, 'sha1', libItm.hash)){
  323. dlSize += (libItm.size*1)
  324. libDlQueue.push(libItm)
  325. }
  326. }
  327. cb()
  328. }, function(err){
  329. instance.libraries = new DLTracker(libDlQueue, dlSize)
  330. instance.totaldlsize += dlSize
  331. fulfill()
  332. })
  333. })
  334. }
  335. /**
  336. * Public miscellaneous mojang file validation function.
  337. */
  338. function validateMiscellaneous(versionData, basePath){
  339. return new Promise(async function(fulfill, reject){
  340. await validateClient(versionData, basePath)
  341. await validateLogConfig(versionData, basePath)
  342. fulfill()
  343. })
  344. }
  345. //Validate client - artifact renamed from client.jar to '{version}'.jar.
  346. function validateClient(versionData, basePath, force = false){
  347. return new Promise(function(fulfill, reject){
  348. const clientData = versionData.downloads.client
  349. const version = versionData.id
  350. const targetPath = path.join(basePath, 'versions', version)
  351. const targetFile = version + '.jar'
  352. let client = new Asset(version + ' client', clientData.sha1, clientData.size, clientData.url, path.join(targetPath, targetFile))
  353. if(!validateLocal(client.to, 'sha1', client.hash) || force){
  354. instance.files.dlqueue.push(client)
  355. instance.files.dlsize += client.size*1
  356. fulfill()
  357. } else {
  358. fulfill()
  359. }
  360. })
  361. }
  362. //Validate log config.
  363. function validateLogConfig(versionData, basePath){
  364. return new Promise(function(fulfill, reject){
  365. const client = versionData.logging.client
  366. const file = client.file
  367. const targetPath = path.join(basePath, 'assets', 'log_configs')
  368. let logConfig = new Asset(file.id, file.sha1, file.size, file.url, path.join(targetPath, file.id))
  369. if(!validateLocal(logConfig.to, 'sha1', logConfig.hash)){
  370. instance.files.dlqueue.push(logConfig)
  371. instance.files.dlsize += client.size*1
  372. fulfill()
  373. } else {
  374. fulfill()
  375. }
  376. })
  377. }
  378. function processDlQueues(identifiers = [{id:'assets', limit:20}, {id:'libraries', limit:5}, {id:'files', limit:5}]){
  379. this.progress = 0;
  380. let win = remote.getCurrentWindow()
  381. let shouldFire = true
  382. for(let i=0; i<identifiers.length; i++){
  383. let iden = identifiers[i]
  384. let r = startAsyncProcess(iden.id, iden.limit)
  385. if(r) shouldFire = false
  386. }
  387. if(shouldFire){
  388. instance.emit('dlcomplete')
  389. }
  390. }
  391. module.exports = {
  392. loadVersionData,
  393. validateAssets,
  394. validateLibraries,
  395. validateMiscellaneous,
  396. processDlQueues,
  397. instance,
  398. Asset,
  399. Library
  400. }