assetguard.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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. //Instance of AssetGuard
  143. const instance = new AssetGuard()
  144. // Utility Functions
  145. /**
  146. * Validate that a file exists and matches a given hash value.
  147. *
  148. * @param {String} filePath - the path of the file to validate.
  149. * @param {String} algo - the hash algorithm to check against.
  150. * @param {String} hash - the existing hash to check against.
  151. * @returns {Boolean} - true if the file exists and calculated hash matches the given hash, otherwise false.
  152. */
  153. validateLocal = function(filePath, algo, hash){
  154. if(fs.existsSync(filePath)){
  155. let fileName = path.basename(filePath)
  156. let shasum = crypto.createHash(algo)
  157. let content = fs.readFileSync(filePath)
  158. shasum.update(content)
  159. let calcdhash = shasum.digest('hex')
  160. return calcdhash === hash
  161. }
  162. return false;
  163. }
  164. /**
  165. * Initiate an async download process for an AssetGuard DLTracker.
  166. *
  167. * @param {String} identifier - the identifier of the AssetGuard DLTracker.
  168. * @param {Number} limit - optional. The number of async processes to run in parallel.
  169. * @returns {Boolean} - true if the process began, otherwise false.
  170. */
  171. function startAsyncProcess(identifier, limit = 5){
  172. let win = remote.getCurrentWindow()
  173. let acc = 0
  174. const concurrentDlQueue = instance[identifier].dlqueue.slice(0)
  175. if(concurrentDlQueue.length === 0){
  176. return false
  177. } else {
  178. async.eachLimit(concurrentDlQueue, limit, function(asset, cb){
  179. mkpath.sync(path.join(asset.to, ".."))
  180. let req = request(asset.from)
  181. let writeStream = fs.createWriteStream(asset.to)
  182. req.pipe(writeStream)
  183. req.on('data', function(chunk){
  184. instance.progress += chunk.length
  185. acc += chunk.length
  186. instance.emit(identifier + 'dlprogress', acc)
  187. //console.log(identifier + ' Progress', acc/instance[identifier].dlsize)
  188. win.setProgressBar(instance.progress/instance.totaldlsize)
  189. })
  190. writeStream.on('close', cb)
  191. }, function(err){
  192. if(err){
  193. instance.emit(identifier + 'dlerror')
  194. console.log('An item in ' + identifier + ' failed to process');
  195. } else {
  196. instance.emit(identifier + 'dlcomplete')
  197. console.log('All ' + identifier + ' have been processed successfully')
  198. }
  199. instance.totaldlsize -= instance[identifier].dlsize
  200. instance[identifier] = new DLTracker([], 0)
  201. if(instance.totaldlsize === 0) {
  202. win.setProgressBar(-1)
  203. instance.emit('dlcomplete')
  204. }
  205. })
  206. return true
  207. }
  208. }
  209. /* Validation Functions */
  210. /**
  211. * Loads the version data for a given minecraft version.
  212. *
  213. * @param {String} version - the game version for which to load the index data.
  214. * @param {String} basePath - the absolute file path which will be prepended to the given relative paths.
  215. * @param {Boolean} force - optional. If true, the version index will be downloaded even if it exists locally. Defaults to false.
  216. * @returns {Promise.<Object>} - Promise which resolves to the version data object.
  217. */
  218. function loadVersionData(version, basePath, force = false){
  219. return new Promise(function(fulfill, reject){
  220. const name = version + '.json'
  221. const url = 'https://s3.amazonaws.com/Minecraft.Download/versions/' + version + '/' + name
  222. const versionPath = path.join(basePath, 'versions', version)
  223. const versionFile = path.join(versionPath, name)
  224. if(!fs.existsSync(versionFile) || force){
  225. //This download will never be tracked as it's essential and trivial.
  226. request.head(url, function(err, res, body){
  227. console.log('Preparing download of ' + version + ' assets.')
  228. mkpath.sync(versionPath)
  229. const stream = request(url).pipe(fs.createWriteStream(versionFile))
  230. stream.on('finish', function(){
  231. fulfill(JSON.parse(fs.readFileSync(versionFile)))
  232. })
  233. })
  234. } else {
  235. fulfill(JSON.parse(fs.readFileSync(versionFile)))
  236. }
  237. })
  238. }
  239. /**
  240. * Public asset validation function. This function will handle the validation of assets.
  241. * It will parse the asset index specified in the version data, analyzing each
  242. * asset entry. In this analysis it will check {todo finish later i'm tired ZZzzzz}
  243. *
  244. */
  245. function validateAssets(versionData, basePath, force = false){
  246. return new Promise(function(fulfill, reject){
  247. _assetChainIndexData(versionData, basePath, force).then(() => {
  248. fulfill()
  249. })
  250. })
  251. }
  252. //Chain the asset tasks to provide full async. The below functions are private.
  253. function _assetChainIndexData(versionData, basePath, force = false){
  254. return new Promise(function(fulfill, reject){
  255. //Asset index constants.
  256. const assetIndex = versionData.assetIndex
  257. const name = assetIndex.id + '.json'
  258. const indexPath = path.join(basePath, 'assets', 'indexes')
  259. const assetIndexLoc = path.join(indexPath, name)
  260. let data = null
  261. if(!fs.existsSync(assetIndexLoc) || force){
  262. console.log('Downloading ' + versionData.id + ' asset index.')
  263. mkpath.sync(indexPath)
  264. const stream = request(assetIndex.url).pipe(fs.createWriteStream(assetIndexLoc))
  265. stream.on('finish', function() {
  266. data = JSON.parse(fs.readFileSync(assetIndexLoc, 'utf-8'))
  267. _assetChainValidateAssets(versionData, basePath, data).then(() => {
  268. fulfill()
  269. })
  270. })
  271. } else {
  272. data = JSON.parse(fs.readFileSync(assetIndexLoc, 'utf-8'))
  273. _assetChainValidateAssets(versionData, basePath, data).then(() => {
  274. fulfill()
  275. })
  276. }
  277. })
  278. }
  279. _assetChainValidateAssets = function(versionData, basePath, indexData){
  280. return new Promise(function(fulfill, reject){
  281. //Asset constants
  282. const resourceURL = 'http://resources.download.minecraft.net/'
  283. const localPath = path.join(basePath, 'assets')
  284. const indexPath = path.join(localPath, 'indexes')
  285. const objectPath = path.join(localPath, 'objects')
  286. const assetDlQueue = []
  287. let dlSize = 0;
  288. //const objKeys = Object.keys(data.objects)
  289. async.forEachOfLimit(indexData.objects, 10, function(value, key, cb){
  290. const hash = value.hash
  291. const assetName = path.join(hash.substring(0, 2), hash)
  292. const urlName = hash.substring(0, 2) + "/" + hash
  293. const ast = new Asset(key, hash, String(value.size), resourceURL + urlName, path.join(objectPath, assetName))
  294. if(!validateLocal(ast.to, 'sha1', ast.hash)){
  295. dlSize += (ast.size*1)
  296. assetDlQueue.push(ast)
  297. }
  298. cb()
  299. }, function(err){
  300. instance.assets = new DLTracker(assetDlQueue, dlSize)
  301. instance.totaldlsize += dlSize
  302. fulfill()
  303. })
  304. })
  305. }
  306. /**
  307. * Public library validation method.
  308. */
  309. validateLibraries = function(versionData, basePath){
  310. return new Promise(function(fulfill, reject){
  311. const libArr = versionData.libraries
  312. const libPath = path.join(basePath, 'libraries')
  313. const libDlQueue = []
  314. let dlSize = 0
  315. //Check validity of each library. If the hashs don't match, download the library.
  316. async.eachLimit(libArr, 5, function(lib, cb){
  317. if(Library.validateRules(lib.rules)){
  318. let artifact = (lib.natives == null) ? lib.downloads.artifact : lib.downloads.classifiers[lib.natives[Library.mojangFriendlyOS()]]
  319. const libItm = new Library(lib.name, artifact.sha1, artifact.size, artifact.url, path.join(libPath, artifact.path))
  320. if(!validateLocal(libItm.to, 'sha1', libItm.hash)){
  321. dlSize += (libItm.size*1)
  322. libDlQueue.push(libItm)
  323. }
  324. }
  325. cb()
  326. }, function(err){
  327. instance.libraries = new DLTracker(libDlQueue, dlSize)
  328. instance.totaldlsize += dlSize
  329. fulfill()
  330. })
  331. })
  332. }
  333. /**
  334. * Public miscellaneous mojang file validation function.
  335. */
  336. validateMiscellaneous = function(versionData, basePath){
  337. return new Promise(async function(fulfill, reject){
  338. await validateClient(versionData, basePath)
  339. await validateLogConfig(versionData, basePath)
  340. fulfill()
  341. })
  342. }
  343. //Validate client - artifact renamed from client.jar to '{version}'.jar.
  344. validateClient = function(versionData, basePath, force = false){
  345. return new Promise(function(fulfill, reject){
  346. const clientData = versionData.downloads.client
  347. const version = versionData.id
  348. const targetPath = path.join(basePath, 'versions', version)
  349. const targetFile = version + '.jar'
  350. let client = new Asset(version + ' client', clientData.sha1, clientData.size, clientData.url, path.join(targetPath, targetFile))
  351. if(!validateLocal(client.to, 'sha1', client.hash) || force){
  352. instance.files.dlqueue.push(client)
  353. instance.files.dlsize += client.size*1
  354. fulfill()
  355. } else {
  356. fulfill()
  357. }
  358. })
  359. }
  360. //Validate log config.
  361. validateLogConfig = function(versionData, basePath){
  362. return new Promise(function(fulfill, reject){
  363. const client = versionData.logging.client
  364. const file = client.file
  365. const targetPath = path.join(basePath, 'assets', 'log_configs')
  366. let logConfig = new Asset(file.id, file.sha1, file.size, file.url, path.join(targetPath, file.id))
  367. if(!validateLocal(logConfig.to, 'sha1', logConfig.hash)){
  368. instance.files.dlqueue.push(logConfig)
  369. instance.files.dlsize += client.size*1
  370. fulfill()
  371. } else {
  372. fulfill()
  373. }
  374. })
  375. }
  376. processDlQueues = function(identifiers = [{id:'assets', limit:20}, {id:'libraries', limit:5}, {id:'files', limit:5}]){
  377. this.progress = 0;
  378. let win = remote.getCurrentWindow()
  379. let shouldFire = true
  380. for(let i=0; i<identifiers.length; i++){
  381. let iden = identifiers[i]
  382. let r = startAsyncProcess(iden.id, iden.limit)
  383. if(r) shouldFire = false
  384. }
  385. if(shouldFire){
  386. instance.emit('dlcomplete')
  387. }
  388. }
  389. module.exports = {
  390. loadVersionData,
  391. validateAssets,
  392. validateLibraries,
  393. validateMiscellaneous,
  394. processDlQueues,
  395. instance,
  396. Asset,
  397. Library
  398. }