assetguard.js 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456
  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. Download meta is
  6. * for several identifiers (categories) is stored inside of an AssetGuard object.
  7. * This meta data is initially empty until one of the module's processing functions
  8. * are called. That function will process the corresponding asset index and validate
  9. * any exisitng local files. If a file is missing or fails validation, it will be
  10. * placed into a download queue (array). 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 AssetGuard 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 AssetGuard
  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 AssetGuard 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 AdmZip = require('adm-zip')
  26. const async = require('async')
  27. const child_process = require('child_process')
  28. const crypto = require('crypto')
  29. const EventEmitter = require('events')
  30. const fs = require('fs')
  31. const mkpath = require('mkdirp');
  32. const path = require('path')
  33. const Registry = require('winreg')
  34. const request = require('request')
  35. const targz = require('targz')
  36. // Constants
  37. const PLATFORM_MAP = {
  38. win32: '-windows-x64.tar.gz',
  39. darwin: '-macosx-x64.tar.gz',
  40. linux: '-linux-x64.tar.gz'
  41. }
  42. // Classes
  43. /** Class representing a base asset. */
  44. class Asset {
  45. /**
  46. * Create an asset.
  47. *
  48. * @param {any} id The id of the asset.
  49. * @param {string} hash The hash value of the asset.
  50. * @param {number} size The size in bytes of the asset.
  51. * @param {string} from The url where the asset can be found.
  52. * @param {string} to The absolute local file path of the asset.
  53. */
  54. constructor(id, hash, size, from, to){
  55. this.id = id
  56. this.hash = hash
  57. this.size = size
  58. this.from = from
  59. this.to = to
  60. }
  61. }
  62. /** Class representing a mojang library. */
  63. class Library extends Asset {
  64. /**
  65. * Converts the process.platform OS names to match mojang's OS names.
  66. */
  67. static mojangFriendlyOS(){
  68. const opSys = process.platform
  69. if (opSys === 'darwin') {
  70. return 'osx';
  71. } else if (opSys === 'win32'){
  72. return 'windows';
  73. } else if (opSys === 'linux'){
  74. return 'linux';
  75. } else {
  76. return 'unknown_os';
  77. }
  78. }
  79. /**
  80. * Checks whether or not a library is valid for download on a particular OS, following
  81. * the rule format specified in the mojang version data index. If the allow property has
  82. * an OS specified, then the library can ONLY be downloaded on that OS. If the disallow
  83. * property has instead specified an OS, the library can be downloaded on any OS EXCLUDING
  84. * the one specified.
  85. *
  86. * @param {Object} rules The Library's download rules.
  87. * @returns {boolean} True if the Library follows the specified rules, otherwise false.
  88. */
  89. static validateRules(rules){
  90. if(rules == null) return true
  91. let result = true
  92. rules.forEach(function(rule){
  93. const action = rule['action']
  94. const osProp = rule['os']
  95. if(action != null){
  96. if(osProp != null){
  97. const osName = osProp['name']
  98. const osMoj = Library.mojangFriendlyOS()
  99. if(action === 'allow'){
  100. result = osName === osMoj
  101. return
  102. } else if(action === 'disallow'){
  103. result = osName !== osMoj
  104. return
  105. }
  106. }
  107. }
  108. })
  109. return result
  110. }
  111. }
  112. class DistroModule extends Asset {
  113. /**
  114. * Create a DistroModule. This is for processing,
  115. * not equivalent to the module objects in the
  116. * distro index.
  117. *
  118. * @param {any} id The id of the asset.
  119. * @param {string} hash The hash value of the asset.
  120. * @param {number} size The size in bytes of the asset.
  121. * @param {string} from The url where the asset can be found.
  122. * @param {string} to The absolute local file path of the asset.
  123. * @param {string} type The the module type.
  124. */
  125. constructor(id, hash, size, from, to, type){
  126. super(id, hash, size, from, to)
  127. this.type = type
  128. }
  129. }
  130. /**
  131. * Class representing a download tracker. This is used to store meta data
  132. * about a download queue, including the queue itself.
  133. */
  134. class DLTracker {
  135. /**
  136. * Create a DLTracker
  137. *
  138. * @param {Array.<Asset>} dlqueue An array containing assets queued for download.
  139. * @param {number} dlsize The combined size of each asset in the download queue array.
  140. * @param {function(Asset)} callback Optional callback which is called when an asset finishes downloading.
  141. */
  142. constructor(dlqueue, dlsize, callback = null){
  143. this.dlqueue = dlqueue
  144. this.dlsize = dlsize
  145. this.callback = callback
  146. }
  147. }
  148. let distributionData = null
  149. /**
  150. * Central object class used for control flow. This object stores data about
  151. * categories of downloads. Each category is assigned an identifier with a
  152. * DLTracker object as its value. Combined information is also stored, such as
  153. * the total size of all the queued files in each category. This event is used
  154. * to emit events so that external modules can listen into processing done in
  155. * this module.
  156. */
  157. class AssetGuard extends EventEmitter {
  158. /**
  159. * Create an instance of AssetGuard.
  160. * On creation the object's properties are never-null default
  161. * values. Each identifier is resolved to an empty DLTracker.
  162. *
  163. * @param {string} basePath The base path for asset validation (game root).
  164. * @param {string} javaexec The path to a java executable which will be used
  165. * to finalize installation.
  166. */
  167. constructor(basePath, javaexec){
  168. super()
  169. this.totaldlsize = 0
  170. this.progress = 0
  171. this.assets = new DLTracker([], 0)
  172. this.libraries = new DLTracker([], 0)
  173. this.files = new DLTracker([], 0)
  174. this.forge = new DLTracker([], 0)
  175. this.java = new DLTracker([], 0)
  176. this.basePath = basePath
  177. this.javaexec = javaexec
  178. }
  179. // Static Utility Functions
  180. // #region
  181. // Static General Resolve Functions
  182. // #region
  183. /**
  184. * Resolve an artifact id into a path. For example, on windows
  185. * 'net.minecraftforge:forge:1.11.2-13.20.0.2282', '.jar' becomes
  186. * net\minecraftforge\forge\1.11.2-13.20.0.2282\forge-1.11.2-13.20.0.2282.jar
  187. *
  188. * @param {string} artifactid The artifact id string.
  189. * @param {string} extension The extension of the file at the resolved path.
  190. * @returns {string} The resolved relative path from the artifact id.
  191. */
  192. static _resolvePath(artifactid, extension){
  193. let ps = artifactid.split(':')
  194. let cs = ps[0].split('.')
  195. cs.push(ps[1])
  196. cs.push(ps[2])
  197. cs.push(ps[1].concat('-').concat(ps[2]).concat(extension))
  198. return path.join.apply(path, cs)
  199. }
  200. /**
  201. * Resolve an artifact id into a URL. For example,
  202. * 'net.minecraftforge:forge:1.11.2-13.20.0.2282', '.jar' becomes
  203. * net/minecraftforge/forge/1.11.2-13.20.0.2282/forge-1.11.2-13.20.0.2282.jar
  204. *
  205. * @param {string} artifactid The artifact id string.
  206. * @param {string} extension The extension of the file at the resolved url.
  207. * @returns {string} The resolved relative URL from the artifact id.
  208. */
  209. static _resolveURL(artifactid, extension){
  210. let ps = artifactid.split(':')
  211. let cs = ps[0].split('.')
  212. cs.push(ps[1])
  213. cs.push(ps[2])
  214. cs.push(ps[1].concat('-').concat(ps[2]).concat(extension))
  215. return cs.join('/')
  216. }
  217. // #endregion
  218. // Static Hash Validation Functions
  219. // #region
  220. /**
  221. * Calculates the hash for a file using the specified algorithm.
  222. *
  223. * @param {Buffer} buf The buffer containing file data.
  224. * @param {string} algo The hash algorithm.
  225. * @returns {string} The calculated hash in hex.
  226. */
  227. static _calculateHash(buf, algo){
  228. return crypto.createHash(algo).update(buf).digest('hex')
  229. }
  230. /**
  231. * Used to parse a checksums file. This is specifically designed for
  232. * the checksums.sha1 files found inside the forge scala dependencies.
  233. *
  234. * @param {string} content The string content of the checksums file.
  235. * @returns {Object} An object with keys being the file names, and values being the hashes.
  236. */
  237. static _parseChecksumsFile(content){
  238. let finalContent = {}
  239. let lines = content.split('\n')
  240. for(let i=0; i<lines.length; i++){
  241. let bits = lines[i].split(' ')
  242. if(bits[1] == null) {
  243. continue
  244. }
  245. finalContent[bits[1]] = bits[0]
  246. }
  247. return finalContent
  248. }
  249. /**
  250. * Validate that a file exists and matches a given hash value.
  251. *
  252. * @param {string} filePath The path of the file to validate.
  253. * @param {string} algo The hash algorithm to check against.
  254. * @param {string} hash The existing hash to check against.
  255. * @returns {boolean} True if the file exists and calculated hash matches the given hash, otherwise false.
  256. */
  257. static _validateLocal(filePath, algo, hash){
  258. if(fs.existsSync(filePath)){
  259. //No hash provided, have to assume it's good.
  260. if(hash == null){
  261. return true
  262. }
  263. let fileName = path.basename(filePath)
  264. let buf = fs.readFileSync(filePath)
  265. let calcdhash = AssetGuard._calculateHash(buf, algo)
  266. return calcdhash === hash
  267. }
  268. return false;
  269. }
  270. /**
  271. * Validates a file in the style used by forge's version index.
  272. *
  273. * @param {string} filePath The path of the file to validate.
  274. * @param {Array.<string>} checksums The checksums listed in the forge version index.
  275. * @returns {boolean} True if the file exists and the hashes match, otherwise false.
  276. */
  277. static _validateForgeChecksum(filePath, checksums){
  278. if(fs.existsSync(filePath)){
  279. if(checksums == null || checksums.length === 0){
  280. return true
  281. }
  282. let buf = fs.readFileSync(filePath)
  283. let calcdhash = AssetGuard._calculateHash(buf, 'sha1')
  284. let valid = checksums.includes(calcdhash)
  285. if(!valid && filePath.endsWith('.jar')){
  286. valid = AssetGuard._validateForgeJar(filePath, checksums)
  287. }
  288. return valid
  289. }
  290. return false
  291. }
  292. /**
  293. * Validates a forge jar file dependency who declares a checksums.sha1 file.
  294. * This can be an expensive task as it usually requires that we calculate thousands
  295. * of hashes.
  296. *
  297. * @param {Buffer} buf The buffer of the jar file.
  298. * @param {Array.<string>} checksums The checksums listed in the forge version index.
  299. * @returns {boolean} True if all hashes declared in the checksums.sha1 file match the actual hashes.
  300. */
  301. static _validateForgeJar(buf, checksums){
  302. // Double pass method was the quickest I found. I tried a version where we store data
  303. // to only require a single pass, plus some quick cleanup but that seemed to take slightly more time.
  304. const hashes = {}
  305. let expected = {}
  306. const zip = new AdmZip(buf)
  307. const zipEntries = zip.getEntries()
  308. //First pass
  309. for(let i=0; i<zipEntries.length; i++){
  310. let entry = zipEntries[i]
  311. if(entry.entryName === 'checksums.sha1'){
  312. expected = AssetGuard._parseChecksumsFile(zip.readAsText(entry))
  313. }
  314. hashes[entry.entryName] = AssetGuard._calculateHash(entry.getData(), 'sha1')
  315. }
  316. if(!checksums.includes(hashes['checksums.sha1'])){
  317. return false
  318. }
  319. //Check against expected
  320. const expectedEntries = Object.keys(expected)
  321. for(let i=0; i<expectedEntries.length; i++){
  322. if(expected[expectedEntries[i]] !== hashes[expectedEntries[i]]){
  323. return false
  324. }
  325. }
  326. return true
  327. }
  328. // #endregion
  329. // Static Distribution Index Functions
  330. // #region
  331. /**
  332. * Statically retrieve the distribution data.
  333. *
  334. * @param {string} basePath The base path for asset validation (game root).
  335. * @param {boolean} cached Optional. False if the distro should be freshly downloaded, else
  336. * a cached copy will be returned.
  337. * @returns {Promise.<Object>} A promise which resolves to the distribution data object.
  338. */
  339. static retrieveDistributionData(basePath, cached = true){
  340. return new Promise(function(fulfill, reject){
  341. if(!cached || distributionData == null){
  342. // TODO Download file from upstream.
  343. //const distroURL = 'http://mc.westeroscraft.com/WesterosCraftLauncher/westeroscraft.json'
  344. // TODO Save file to path.join(basePath, 'westeroscraft.json')
  345. // TODO Fulfill with JSON.parse()
  346. // Workaround while file is not hosted.
  347. fs.readFile(path.join(__dirname, '..', 'westeroscraft.json'), 'utf-8', (err, data) => {
  348. distributionData = JSON.parse(data)
  349. fulfill(distributionData)
  350. })
  351. } else {
  352. fulfill(distributionData)
  353. }
  354. })
  355. }
  356. /**
  357. * Statically retrieve the distribution data.
  358. *
  359. * @param {string} basePath The base path for asset validation (game root).
  360. * @param {boolean} cached Optional. False if the distro should be freshly downloaded, else
  361. * a cached copy will be returned.
  362. * @returns {Object} The distribution data object.
  363. */
  364. static retrieveDistributionDataSync(basePath, cached = true){
  365. if(!cached || distributionData == null){
  366. distributionData = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'westeroscraft.json'), 'utf-8'))
  367. }
  368. return distributionData
  369. }
  370. /**
  371. * Resolve the default selected server from the distribution index.
  372. *
  373. * @param {string} basePath The base path for asset validation (game root).
  374. * @returns {Object} An object resolving to the default selected server.
  375. */
  376. static resolveSelectedServer(basePath){
  377. const distro = AssetGuard.retrieveDistributionDataSync(basePath)
  378. const servers = distro.servers
  379. for(let i=0; i<servers.length; i++){
  380. if(servers[i].default_selected){
  381. return servers[i].id
  382. }
  383. }
  384. // If no server declares default_selected, default to the first one declared.
  385. return (servers.length > 0) ? servers[0].id : null
  386. }
  387. /**
  388. * Gets a server from the distro index which maches the provided ID.
  389. * Returns null if the ID could not be found or the distro index has
  390. * not yet been loaded.
  391. *
  392. * @param {string} basePath The base path for asset validation (game root).
  393. * @param {string} serverID The id of the server to retrieve.
  394. * @returns {Object} The server object whose id matches the parameter.
  395. */
  396. static getServerById(basePath, serverID){
  397. if(distributionData == null){
  398. AssetGuard.retrieveDistributionDataSync(basePath, false)
  399. }
  400. const servers = distributionData.servers
  401. let serv = null
  402. for(let i=0; i<servers.length; i++){
  403. if(servers[i].id === serverID){
  404. serv = servers[i]
  405. }
  406. }
  407. return serv
  408. }
  409. // #endregion
  410. // Miscellaneous Static Functions
  411. // #region
  412. /**
  413. * Extracts and unpacks a file from .pack.xz format.
  414. *
  415. * @param {Array.<string>} filePaths The paths of the files to be extracted and unpacked.
  416. * @returns {Promise.<void>} An empty promise to indicate the extraction has completed.
  417. */
  418. static _extractPackXZ(filePaths, javaExecutable){
  419. return new Promise(function(fulfill, reject){
  420. const libPath = path.join(__dirname, '..', 'libraries', 'java', 'PackXZExtract.jar')
  421. const filePath = filePaths.join(',')
  422. const child = child_process.spawn(javaExecutable, ['-jar', libPath, '-packxz', filePath])
  423. child.stdout.on('data', (data) => {
  424. //console.log('PackXZExtract:', data.toString('utf8'))
  425. })
  426. child.stderr.on('data', (data) => {
  427. //console.log('PackXZExtract:', data.toString('utf8'))
  428. })
  429. child.on('close', (code, signal) => {
  430. //console.log('PackXZExtract: Exited with code', code)
  431. fulfill()
  432. })
  433. })
  434. }
  435. /**
  436. * Function which finalizes the forge installation process. This creates a 'version'
  437. * instance for forge and saves its version.json file into that instance. If that
  438. * instance already exists, the contents of the version.json file are read and returned
  439. * in a promise.
  440. *
  441. * @param {Asset} asset The Asset object representing Forge.
  442. * @param {string} basePath Base path for asset validation (game root).
  443. * @returns {Promise.<Object>} A promise which resolves to the contents of forge's version.json.
  444. */
  445. static _finalizeForgeAsset(asset, basePath){
  446. return new Promise(function(fulfill, reject){
  447. fs.readFile(asset.to, (err, data) => {
  448. const zip = new AdmZip(data)
  449. const zipEntries = zip.getEntries()
  450. for(let i=0; i<zipEntries.length; i++){
  451. if(zipEntries[i].entryName === 'version.json'){
  452. const forgeVersion = JSON.parse(zip.readAsText(zipEntries[i]))
  453. const versionPath = path.join(basePath, 'versions', forgeVersion.id)
  454. const versionFile = path.join(versionPath, forgeVersion.id + '.json')
  455. if(!fs.existsSync(versionFile)){
  456. mkpath.sync(versionPath)
  457. fs.writeFileSync(path.join(versionPath, forgeVersion.id + '.json'), zipEntries[i].getData())
  458. fulfill(forgeVersion)
  459. } else {
  460. //Read the saved file to allow for user modifications.
  461. fulfill(JSON.parse(fs.readFileSync(versionFile, 'utf-8')))
  462. }
  463. return
  464. }
  465. }
  466. //We didn't find forge's version.json.
  467. reject('Unable to finalize Forge processing, version.json not found! Has forge changed their format?')
  468. })
  469. })
  470. }
  471. // #endregion
  472. // Static Java Utility
  473. // #region
  474. /**
  475. * @typedef OracleJREData
  476. * @property {string} uri The base uri of the JRE.
  477. * @property {{major: string, update: string, build: string}} version Object containing version information.
  478. */
  479. /**
  480. * Resolves the latest version of Oracle's JRE and parses its download link.
  481. *
  482. * @returns {Promise.<OracleJREData>} Promise which resolved to an object containing the JRE download data.
  483. */
  484. static _latestJREOracle(){
  485. const url = 'http://www.oracle.com/technetwork/java/javase/downloads/jre8-downloads-2133155.html'
  486. const regex = /http:\/\/.+?(?=\/java)\/java\/jdk\/([0-9]+u[0-9]+)-(b[0-9]+)\/([a-f0-9]{32})?\/jre-\1/
  487. return new Promise((resolve, reject) => {
  488. request(url, (err, resp, body) => {
  489. if(!err){
  490. const arr = body.match(regex)
  491. const verSplit = arr[1].split('u')
  492. resolve({
  493. uri: arr[0],
  494. version: {
  495. major: verSplit[0],
  496. update: verSplit[1],
  497. build: arr[2]
  498. }
  499. })
  500. } else {
  501. resolve(null)
  502. }
  503. })
  504. })
  505. }
  506. /**
  507. * Load Mojang's launcher.json file.
  508. *
  509. * @returns {Promise.<Object>} Promise which resolves to Mojang's launcher.json object.
  510. */
  511. static loadMojangLauncherData(){
  512. return new Promise((resolve, reject) => {
  513. request.get('https://launchermeta.mojang.com/mc/launcher.json', (err, resp, body) => {
  514. if(err){
  515. resolve(null)
  516. } else {
  517. resolve(JSON.parse(body))
  518. }
  519. })
  520. })
  521. }
  522. /**
  523. * Validates that a Java binary is at least 64 bit. This makes use of the non-standard
  524. * command line option -XshowSettings:properties. The output of this contains a property,
  525. * sun.arch.data.model = ARCH, in which ARCH is either 32 or 64. This option is supported
  526. * in Java 8 and 9. Since this is a non-standard option. This will resolve to true if
  527. * the function's code throws errors. That would indicate that the option is changed or
  528. * removed.
  529. *
  530. * @param {string} binaryPath Path to the root of the java binary we wish to validate.
  531. *
  532. * @returns {Promise.<boolean>} Resolves to false only if the test is successful and the result
  533. * is less than 64.
  534. */
  535. static _validateJavaBinary(binaryPath){
  536. return new Promise((resolve, reject) => {
  537. let fBp = binaryPath
  538. if(!fBp.endsWith('.exe')){
  539. fBp = path.join(binaryPath, 'bin', 'java.exe')
  540. }
  541. if(fs.existsSync(fBp)){
  542. child_process.exec('"' + fBp + '" -XshowSettings:properties', (err, stdout, stderr) => {
  543. try {
  544. // Output is stored in stderr?
  545. const res = stderr
  546. const props = res.split('\n')
  547. for(let i=0; i<props.length; i++){
  548. if(props[i].indexOf('sun.arch.data.model') > -1){
  549. let arch = props[i].split('=')[1].trim()
  550. console.log(props[i].trim() + ' for ' + binaryPath)
  551. resolve(parseInt(arch) >= 64)
  552. }
  553. }
  554. // sun.arch.data.model not found?
  555. // Disregard this test.
  556. resolve(true)
  557. } catch (err){
  558. // Output format might have changed, validation cannot be completed.
  559. // Disregard this test in that case.
  560. resolve(true)
  561. }
  562. })
  563. } else {
  564. resolve(false)
  565. }
  566. })
  567. }
  568. /**
  569. * Checks for the presence of the environment variable JAVA_HOME. If it exits, we will check
  570. * to see if the value points to a path which exists. If the path exits, the path is returned.
  571. *
  572. * @returns {string} The path defined by JAVA_HOME, if it exists. Otherwise null.
  573. */
  574. static _scanJavaHome(){
  575. const jHome = process.env.JAVA_HOME
  576. try {
  577. let res = fs.existsSync(jHome)
  578. return res ? jHome : null
  579. } catch (err) {
  580. // Malformed JAVA_HOME property.
  581. return null
  582. }
  583. }
  584. /**
  585. * Scans the data folder's runtime directory for suitable JRE candidates.
  586. *
  587. * @param {string} dataDir The base launcher directory.
  588. * @returns {Promise.<Set.<string>>} A set containing suitable JRE candidates found
  589. * in the runtime directory.
  590. */
  591. static _scanDataFolder(dataDir){
  592. return new Promise((resolve, reject) => {
  593. const x64RuntimeDir = path.join(dataDir, 'runtime', 'x64')
  594. fs.exists(x64RuntimeDir, (e) => {
  595. let res = new Set()
  596. if(e){
  597. fs.readdir(x64RuntimeDir, (err, files) => {
  598. if(err){
  599. resolve(res)
  600. console.log(err)
  601. } else {
  602. for(let i=0; i<files.length; i++){
  603. res.add(path.join(x64RuntimeDir, files[i]))
  604. }
  605. resolve(res)
  606. }
  607. })
  608. } else {
  609. resolve(res)
  610. }
  611. })
  612. })
  613. }
  614. /**
  615. * Scans the registry for 64-bit Java entries. The paths of each entry are added to
  616. * a set and returned. Currently, only Java 8 (1.8) is supported.
  617. *
  618. * @returns {Promise.<Set.<string>>} A promise which resolves to a set of 64-bit Java root
  619. * paths found in the registry.
  620. */
  621. static _scanRegistry(){
  622. return new Promise((resolve, reject) => {
  623. // Keys for Java v9.0.0 and later:
  624. // 'SOFTWARE\\JavaSoft\\JRE'
  625. // 'SOFTWARE\\JavaSoft\\JDK'
  626. // Forge does not yet support Java 9, therefore we do not.
  627. let cbTracker = 0
  628. let cbAcc = 0
  629. // Keys for Java 1.8 and prior:
  630. const regKeys = [
  631. '\\SOFTWARE\\JavaSoft\\Java Runtime Environment',
  632. '\\SOFTWARE\\JavaSoft\\Java Development Kit'
  633. ]
  634. const candidates = new Set()
  635. for(let i=0; i<regKeys.length; i++){
  636. const key = new Registry({
  637. hive: Registry.HKLM,
  638. key: regKeys[i],
  639. arch: 'x64'
  640. })
  641. key.keyExists((err, exists) => {
  642. if(exists) {
  643. key.keys((err, javaVers) => {
  644. if(err){
  645. console.error(err)
  646. if(i === regKeys.length-1 && cbAcc === cbTracker){
  647. resolve(candidates)
  648. }
  649. } else {
  650. cbTracker += javaVers.length
  651. if(i === regKeys.length-1 && cbTracker === cbAcc){
  652. resolve(candidates)
  653. } else {
  654. for(let j=0; j<javaVers.length; j++){
  655. const javaVer = javaVers[j]
  656. const vKey = javaVer.key.substring(javaVer.key.lastIndexOf('\\')+1)
  657. // Only Java 8 is supported currently.
  658. if(parseFloat(vKey) === 1.8){
  659. javaVer.get('JavaHome', (err, res) => {
  660. const jHome = res.value
  661. if(jHome.indexOf('(x86)') === -1){
  662. candidates.add(jHome)
  663. }
  664. cbAcc++
  665. if(i === regKeys.length-1 && cbAcc === cbTracker){
  666. resolve(candidates)
  667. }
  668. })
  669. } else {
  670. cbAcc++
  671. if(i === regKeys.length-1 && cbAcc === cbTracker){
  672. resolve(candidates)
  673. }
  674. }
  675. }
  676. }
  677. }
  678. })
  679. } else {
  680. if(i === regKeys.length-1 && cbAcc === cbTracker){
  681. resolve(candidates)
  682. }
  683. }
  684. })
  685. }
  686. })
  687. }
  688. /**
  689. * Attempts to find a valid x64 installation of Java on Windows machines.
  690. * Possible paths will be pulled from the registry and the JAVA_HOME environment
  691. * variable. The paths will be sorted with higher versions preceeding lower, and
  692. * JREs preceeding JDKs. The binaries at the sorted paths will then be validated.
  693. * The first validated is returned.
  694. *
  695. * Higher versions > Lower versions
  696. * If versions are equal, JRE > JDK.
  697. *
  698. * @param {string} dataDir The base launcher directory.
  699. * @returns {Promise.<string>} A Promise which resolves to the root path of a valid
  700. * x64 Java installation. If none are found, null is returned.
  701. */
  702. static async _win32JavaValidate(dataDir){
  703. // Get possible paths from the registry.
  704. const pathSet = await AssetGuard._scanRegistry()
  705. //console.log(Array.from(pathSet)) // DEBUGGING
  706. // Get possible paths from the data directory.
  707. const pathSet2 = await AssetGuard._scanDataFolder(dataDir)
  708. // Validate JAVA_HOME
  709. const jHome = AssetGuard._scanJavaHome()
  710. if(jHome != null && jHome.indexOf('(x86)') === -1){
  711. pathSet.add(jHome)
  712. }
  713. const mergedSet = new Set([...pathSet, ...pathSet2])
  714. // Convert path set to an array for processing.
  715. let pathArr = Array.from(mergedSet)
  716. //console.log(pathArr) // DEBUGGING
  717. // Sorts array. Higher version numbers preceed lower. JRE preceeds JDK.
  718. pathArr = pathArr.sort((a, b) => {
  719. // Note that Java 9+ uses semver and that will need to be accounted for in
  720. // the future.
  721. const aVer = parseInt(a.split('_')[1])
  722. const bVer = parseInt(b.split('_')[1])
  723. if(bVer === aVer){
  724. return a.indexOf('jdk') > -1 ? 1 : 0
  725. } else {
  726. return bVer - aVer
  727. }
  728. })
  729. //console.log(pathArr) // DEBUGGING
  730. // Validate that the binary is actually x64.
  731. for(let i=0; i<pathArr.length; i++) {
  732. let res = await AssetGuard._validateJavaBinary(pathArr[i])
  733. if(res){
  734. return pathArr[i]
  735. }
  736. }
  737. // No suitable candidates found.
  738. return null;
  739. }
  740. /**
  741. * WIP -> get a valid x64 Java path on macOS.
  742. */
  743. static async _darwinJavaValidate(dataDir){
  744. return null
  745. }
  746. /**
  747. * WIP -> get a valid x64 Java path on linux.
  748. */
  749. static async _linuxJavaValidate(dataDir){
  750. return null
  751. }
  752. /**
  753. * Retrieve the path of a valid x64 Java installation.
  754. *
  755. * @param {string} dataDir The base launcher directory.
  756. * @returns {string} A path to a valid x64 Java installation, null if none found.
  757. */
  758. static async validateJava(dataDir){
  759. return await AssetGuard['_' + process.platform + 'JavaValidate'](dataDir)
  760. }
  761. // #endregion
  762. // #endregion
  763. // Validation Functions
  764. // #region
  765. /**
  766. * Loads the version data for a given minecraft version.
  767. *
  768. * @param {string} version The game version for which to load the index data.
  769. * @param {boolean} force Optional. If true, the version index will be downloaded even if it exists locally. Defaults to false.
  770. * @returns {Promise.<Object>} Promise which resolves to the version data object.
  771. */
  772. loadVersionData(version, force = false){
  773. const self = this
  774. return new Promise((resolve, reject) => {
  775. const name = version + '.json'
  776. const url = 'https://s3.amazonaws.com/Minecraft.Download/versions/' + version + '/' + name
  777. const versionPath = path.join(self.basePath, 'versions', version)
  778. const versionFile = path.join(versionPath, name)
  779. if(!fs.existsSync(versionFile) || force){
  780. //This download will never be tracked as it's essential and trivial.
  781. console.log('Preparing download of ' + version + ' assets.')
  782. mkpath.sync(versionPath)
  783. const stream = request(url).pipe(fs.createWriteStream(versionFile))
  784. stream.on('finish', () => {
  785. resolve(JSON.parse(fs.readFileSync(versionFile)))
  786. })
  787. } else {
  788. resolve(JSON.parse(fs.readFileSync(versionFile)))
  789. }
  790. })
  791. }
  792. // Asset (Category=''') Validation Functions
  793. // #region
  794. /**
  795. * Public asset validation function. This function will handle the validation of assets.
  796. * It will parse the asset index specified in the version data, analyzing each
  797. * asset entry. In this analysis it will check to see if the local file exists and is valid.
  798. * If not, it will be added to the download queue for the 'assets' identifier.
  799. *
  800. * @param {Object} versionData The version data for the assets.
  801. * @param {boolean} force Optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  802. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  803. */
  804. validateAssets(versionData, force = false){
  805. const self = this
  806. return new Promise(function(fulfill, reject){
  807. self._assetChainIndexData(versionData, force).then(() => {
  808. fulfill()
  809. })
  810. })
  811. }
  812. //Chain the asset tasks to provide full async. The below functions are private.
  813. /**
  814. * Private function used to chain the asset validation process. This function retrieves
  815. * the index data.
  816. * @param {Object} versionData
  817. * @param {boolean} force
  818. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  819. */
  820. _assetChainIndexData(versionData, force = false){
  821. const self = this
  822. return new Promise(function(fulfill, reject){
  823. //Asset index constants.
  824. const assetIndex = versionData.assetIndex
  825. const name = assetIndex.id + '.json'
  826. const indexPath = path.join(self.basePath, 'assets', 'indexes')
  827. const assetIndexLoc = path.join(indexPath, name)
  828. let data = null
  829. if(!fs.existsSync(assetIndexLoc) || force){
  830. console.log('Downloading ' + versionData.id + ' asset index.')
  831. mkpath.sync(indexPath)
  832. const stream = request(assetIndex.url).pipe(fs.createWriteStream(assetIndexLoc))
  833. stream.on('finish', function() {
  834. data = JSON.parse(fs.readFileSync(assetIndexLoc, 'utf-8'))
  835. self._assetChainValidateAssets(versionData, data).then(() => {
  836. fulfill()
  837. })
  838. })
  839. } else {
  840. data = JSON.parse(fs.readFileSync(assetIndexLoc, 'utf-8'))
  841. self._assetChainValidateAssets(versionData, data).then(() => {
  842. fulfill()
  843. })
  844. }
  845. })
  846. }
  847. /**
  848. * Private function used to chain the asset validation process. This function processes
  849. * the assets and enqueues missing or invalid files.
  850. * @param {Object} versionData
  851. * @param {boolean} force
  852. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  853. */
  854. _assetChainValidateAssets(versionData, indexData){
  855. const self = this
  856. return new Promise(function(fulfill, reject){
  857. //Asset constants
  858. const resourceURL = 'http://resources.download.minecraft.net/'
  859. const localPath = path.join(self.basePath, 'assets')
  860. const indexPath = path.join(localPath, 'indexes')
  861. const objectPath = path.join(localPath, 'objects')
  862. const assetDlQueue = []
  863. let dlSize = 0;
  864. //const objKeys = Object.keys(data.objects)
  865. async.forEachOfLimit(indexData.objects, 10, function(value, key, cb){
  866. const hash = value.hash
  867. const assetName = path.join(hash.substring(0, 2), hash)
  868. const urlName = hash.substring(0, 2) + "/" + hash
  869. const ast = new Asset(key, hash, String(value.size), resourceURL + urlName, path.join(objectPath, assetName))
  870. if(!AssetGuard._validateLocal(ast.to, 'sha1', ast.hash)){
  871. dlSize += (ast.size*1)
  872. assetDlQueue.push(ast)
  873. }
  874. cb()
  875. }, function(err){
  876. self.assets = new DLTracker(assetDlQueue, dlSize)
  877. fulfill()
  878. })
  879. })
  880. }
  881. // #endregion
  882. // Library (Category=''') Validation Functions
  883. // #region
  884. /**
  885. * Public library validation function. This function will handle the validation of libraries.
  886. * It will parse the version data, analyzing each library entry. In this analysis, it will
  887. * check to see if the local file exists and is valid. If not, it will be added to the download
  888. * queue for the 'libraries' identifier.
  889. *
  890. * @param {Object} versionData The version data for the assets.
  891. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  892. */
  893. validateLibraries(versionData){
  894. const self = this
  895. return new Promise(function(fulfill, reject){
  896. const libArr = versionData.libraries
  897. const libPath = path.join(self.basePath, 'libraries')
  898. const libDlQueue = []
  899. let dlSize = 0
  900. //Check validity of each library. If the hashs don't match, download the library.
  901. async.eachLimit(libArr, 5, function(lib, cb){
  902. if(Library.validateRules(lib.rules)){
  903. let artifact = (lib.natives == null) ? lib.downloads.artifact : lib.downloads.classifiers[lib.natives[Library.mojangFriendlyOS()]]
  904. const libItm = new Library(lib.name, artifact.sha1, artifact.size, artifact.url, path.join(libPath, artifact.path))
  905. if(!AssetGuard._validateLocal(libItm.to, 'sha1', libItm.hash)){
  906. dlSize += (libItm.size*1)
  907. libDlQueue.push(libItm)
  908. }
  909. }
  910. cb()
  911. }, function(err){
  912. self.libraries = new DLTracker(libDlQueue, dlSize)
  913. fulfill()
  914. })
  915. })
  916. }
  917. // #endregion
  918. // Miscellaneous (Category=files) Validation Functions
  919. // #region
  920. /**
  921. * Public miscellaneous mojang file validation function. These files will be enqueued under
  922. * the 'files' identifier.
  923. *
  924. * @param {Object} versionData The version data for the assets.
  925. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  926. */
  927. validateMiscellaneous(versionData){
  928. const self = this
  929. return new Promise(async function(fulfill, reject){
  930. await self.validateClient(versionData)
  931. await self.validateLogConfig(versionData)
  932. fulfill()
  933. })
  934. }
  935. /**
  936. * Validate client file - artifact renamed from client.jar to '{version}'.jar.
  937. *
  938. * @param {Object} versionData The version data for the assets.
  939. * @param {boolean} force Optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  940. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  941. */
  942. validateClient(versionData, force = false){
  943. const self = this
  944. return new Promise(function(fulfill, reject){
  945. const clientData = versionData.downloads.client
  946. const version = versionData.id
  947. const targetPath = path.join(self.basePath, 'versions', version)
  948. const targetFile = version + '.jar'
  949. let client = new Asset(version + ' client', clientData.sha1, clientData.size, clientData.url, path.join(targetPath, targetFile))
  950. if(!AssetGuard._validateLocal(client.to, 'sha1', client.hash) || force){
  951. self.files.dlqueue.push(client)
  952. self.files.dlsize += client.size*1
  953. fulfill()
  954. } else {
  955. fulfill()
  956. }
  957. })
  958. }
  959. /**
  960. * Validate log config.
  961. *
  962. * @param {Object} versionData The version data for the assets.
  963. * @param {boolean} force Optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  964. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  965. */
  966. validateLogConfig(versionData){
  967. const self = this
  968. return new Promise(function(fulfill, reject){
  969. const client = versionData.logging.client
  970. const file = client.file
  971. const targetPath = path.join(self.basePath, 'assets', 'log_configs')
  972. let logConfig = new Asset(file.id, file.sha1, file.size, file.url, path.join(targetPath, file.id))
  973. if(!AssetGuard._validateLocal(logConfig.to, 'sha1', logConfig.hash)){
  974. self.files.dlqueue.push(logConfig)
  975. self.files.dlsize += logConfig.size*1
  976. fulfill()
  977. } else {
  978. fulfill()
  979. }
  980. })
  981. }
  982. // #endregion
  983. // Distribution (Category=forge) Validation Functions
  984. // #region
  985. /**
  986. * Validate the distribution.
  987. *
  988. * @param {string} serverpackid The id of the server to validate.
  989. * @returns {Promise.<Object>} A promise which resolves to the server distribution object.
  990. */
  991. validateDistribution(serverpackid){
  992. const self = this
  993. return new Promise(function(fulfill, reject){
  994. AssetGuard.retrieveDistributionData(self.basePath, false).then((value) => {
  995. /*const servers = value.servers
  996. let serv = null
  997. for(let i=0; i<servers.length; i++){
  998. if(servers[i].id === serverpackid){
  999. serv = servers[i]
  1000. break
  1001. }
  1002. }*/
  1003. const serv = AssetGuard.getServerById(self.basePath, serverpackid)
  1004. if(serv == null) {
  1005. console.error('Invalid server pack id:', serverpackid)
  1006. }
  1007. self.forge = self._parseDistroModules(serv.modules, serv.mc_version)
  1008. //Correct our workaround here.
  1009. let decompressqueue = self.forge.callback
  1010. self.forge.callback = function(asset){
  1011. if(asset.to.toLowerCase().endsWith('.pack.xz')){
  1012. AssetGuard._extractPackXZ([asset.to], self.javaexec)
  1013. }
  1014. if(asset.type === 'forge-hosted' || asset.type === 'forge'){
  1015. AssetGuard._finalizeForgeAsset(asset, self.basePath)
  1016. }
  1017. }
  1018. fulfill(serv)
  1019. })
  1020. })
  1021. }
  1022. /*//TODO The file should be hosted, the following code is for local testing.
  1023. _chainValidateDistributionIndex(basePath){
  1024. return new Promise(function(fulfill, reject){
  1025. //const distroURL = 'http://mc.westeroscraft.com/WesterosCraftLauncher/westeroscraft.json'
  1026. //const targetFile = path.join(basePath, 'westeroscraft.json')
  1027. //TEMP WORKAROUND TO TEST WHILE THIS IS NOT HOSTED
  1028. fs.readFile(path.join(__dirname, '..', 'westeroscraft.json'), 'utf-8', (err, data) => {
  1029. fulfill(JSON.parse(data))
  1030. })
  1031. })
  1032. }*/
  1033. _parseDistroModules(modules, version){
  1034. let alist = []
  1035. let asize = 0;
  1036. //This may be removed soon, considering the most efficient way to extract.
  1037. let decompressqueue = []
  1038. for(let i=0; i<modules.length; i++){
  1039. let ob = modules[i]
  1040. let obType = ob.type
  1041. let obArtifact = ob.artifact
  1042. let obPath = obArtifact.path == null ? AssetGuard._resolvePath(ob.id, obArtifact.extension) : obArtifact.path
  1043. switch(obType){
  1044. case 'forge-hosted':
  1045. case 'forge':
  1046. case 'library':
  1047. obPath = path.join(this.basePath, 'libraries', obPath)
  1048. break
  1049. case 'forgemod':
  1050. //obPath = path.join(this.basePath, 'mods', obPath)
  1051. obPath = path.join(this.basePath, 'modstore', obPath)
  1052. break
  1053. case 'litemod':
  1054. //obPath = path.join(this.basePath, 'mods', version, obPath)
  1055. obPath = path.join(this.basePath, 'modstore', obPath)
  1056. break
  1057. case 'file':
  1058. default:
  1059. obPath = path.join(this.basePath, obPath)
  1060. }
  1061. let artifact = new DistroModule(ob.id, obArtifact.MD5, obArtifact.size, obArtifact.url, obPath, obType)
  1062. const validationPath = obPath.toLowerCase().endsWith('.pack.xz') ? obPath.substring(0, obPath.toLowerCase().lastIndexOf('.pack.xz')) : obPath
  1063. if(!AssetGuard._validateLocal(validationPath, 'MD5', artifact.hash)){
  1064. asize += artifact.size*1
  1065. alist.push(artifact)
  1066. if(validationPath !== obPath) decompressqueue.push(obPath)
  1067. }
  1068. //Recursively process the submodules then combine the results.
  1069. if(ob.sub_modules != null){
  1070. let dltrack = this._parseDistroModules(ob.sub_modules, version)
  1071. asize += dltrack.dlsize*1
  1072. alist = alist.concat(dltrack.dlqueue)
  1073. decompressqueue = decompressqueue.concat(dltrack.callback)
  1074. }
  1075. }
  1076. //Since we have no callback at this point, we use this value to store the decompressqueue.
  1077. return new DLTracker(alist, asize, decompressqueue)
  1078. }
  1079. /**
  1080. * Loads Forge's version.json data into memory for the specified server id.
  1081. *
  1082. * @param {string} serverpack The id of the server to load Forge data for.
  1083. * @returns {Promise.<Object>} A promise which resolves to Forge's version.json data.
  1084. */
  1085. loadForgeData(serverpack){
  1086. const self = this
  1087. return new Promise(async function(fulfill, reject){
  1088. let distro = AssetGuard.retrieveDistributionDataSync(self.basePath)
  1089. const servers = distro.servers
  1090. let serv = null
  1091. for(let i=0; i<servers.length; i++){
  1092. if(servers[i].id === serverpack){
  1093. serv = servers[i]
  1094. break
  1095. }
  1096. }
  1097. const modules = serv.modules
  1098. for(let i=0; i<modules.length; i++){
  1099. const ob = modules[i]
  1100. if(ob.type === 'forge-hosted' || ob.type === 'forge'){
  1101. let obArtifact = ob.artifact
  1102. let obPath = obArtifact.path == null ? path.join(self.basePath, 'libraries', AssetGuard._resolvePath(ob.id, obArtifact.extension)) : obArtifact.path
  1103. let asset = new DistroModule(ob.id, obArtifact.MD5, obArtifact.size, obArtifact.url, obPath, ob.type)
  1104. let forgeData = await AssetGuard._finalizeForgeAsset(asset, self.basePath)
  1105. fulfill(forgeData)
  1106. return
  1107. }
  1108. }
  1109. reject('No forge module found!')
  1110. })
  1111. }
  1112. _parseForgeLibraries(){
  1113. /* TODO
  1114. * Forge asset validations are already implemented. When there's nothing much
  1115. * to work on, implement forge downloads using forge's version.json. This is to
  1116. * have the code on standby if we ever need it (since it's half implemented already).
  1117. */
  1118. }
  1119. // #endregion
  1120. // Java (Category=''') Validation (download) Functions
  1121. // #region
  1122. _enqueueOracleJRE(dir){
  1123. return new Promise((resolve, reject) => {
  1124. AssetGuard._latestJREOracle().then(verData => {
  1125. if(verData != null){
  1126. const combined = verData.uri + PLATFORM_MAP[process.platform]
  1127. const opts = {
  1128. url: combined,
  1129. headers: {
  1130. 'Cookie': 'oraclelicense=accept-securebackup-cookie'
  1131. }
  1132. }
  1133. request.head(opts, (err, resp, body) => {
  1134. if(err){
  1135. resolve(false)
  1136. } else {
  1137. const name = combined.substring(combined.lastIndexOf('/')+1)
  1138. const fDir = path.join(dir, name)
  1139. const jre = new Asset(name, null, resp.headers['content-length'], opts, fDir)
  1140. this.java = new DLTracker([jre], jre.size, a => {
  1141. targz.decompress({
  1142. src: a.to,
  1143. dest: dir
  1144. }, err => {
  1145. if(err){
  1146. console.log(err)
  1147. } else {
  1148. fs.unlink(a.to, err => {
  1149. if(err){
  1150. console.log(err)
  1151. }
  1152. })
  1153. }
  1154. })
  1155. })
  1156. resolve(true)
  1157. }
  1158. })
  1159. } else {
  1160. resolve(false)
  1161. }
  1162. })
  1163. })
  1164. }
  1165. /*_enqueueMojangJRE(dir){
  1166. return new Promise((resolve, reject) => {
  1167. // Mojang does not host the JRE for linux.
  1168. if(process.platform === 'linux'){
  1169. resolve(false)
  1170. }
  1171. AssetGuard.loadMojangLauncherData().then(data => {
  1172. if(data != null) {
  1173. try {
  1174. const mJRE = data[Library.mojangFriendlyOS()]['64'].jre
  1175. const url = mJRE.url
  1176. request.head(url, (err, resp, body) => {
  1177. if(err){
  1178. resolve(false)
  1179. } else {
  1180. const name = url.substring(url.lastIndexOf('/')+1)
  1181. const fDir = path.join(dir, name)
  1182. const jre = new Asset('jre' + mJRE.version, mJRE.sha1, resp.headers['content-length'], url, fDir)
  1183. this.java = new DLTracker([jre], jre.size, a => {
  1184. fs.readFile(a.to, (err, data) => {
  1185. // Data buffer needs to be decompressed from lzma,
  1186. // not really possible using node.js
  1187. })
  1188. })
  1189. }
  1190. })
  1191. } catch (err){
  1192. resolve(false)
  1193. }
  1194. }
  1195. })
  1196. })
  1197. }*/
  1198. // #endregion
  1199. // #endregion
  1200. // Control Flow Functions
  1201. // #region
  1202. /**
  1203. * Initiate an async download process for an AssetGuard DLTracker.
  1204. *
  1205. * @param {string} identifier The identifier of the AssetGuard DLTracker.
  1206. * @param {number} limit Optional. The number of async processes to run in parallel.
  1207. * @returns {boolean} True if the process began, otherwise false.
  1208. */
  1209. startAsyncProcess(identifier, limit = 5){
  1210. const self = this
  1211. let acc = 0
  1212. const concurrentDlTracker = this[identifier]
  1213. const concurrentDlQueue = concurrentDlTracker.dlqueue.slice(0)
  1214. if(concurrentDlQueue.length === 0){
  1215. return false
  1216. } else {
  1217. async.eachLimit(concurrentDlQueue, limit, function(asset, cb){
  1218. let count = 0;
  1219. mkpath.sync(path.join(asset.to, ".."))
  1220. let req = request(asset.from)
  1221. req.pause()
  1222. req.on('response', (resp) => {
  1223. if(resp.statusCode === 200){
  1224. let writeStream = fs.createWriteStream(asset.to)
  1225. writeStream.on('close', () => {
  1226. //console.log('DLResults ' + asset.size + ' ' + count + ' ', asset.size === count)
  1227. if(concurrentDlTracker.callback != null){
  1228. concurrentDlTracker.callback.apply(concurrentDlTracker, [asset])
  1229. }
  1230. cb()
  1231. })
  1232. req.pipe(writeStream)
  1233. req.resume()
  1234. } else {
  1235. req.abort()
  1236. const realFrom = typeof asset.from === 'object' ? asset.from.url : asset.from
  1237. console.log('Failed to download ' + realFrom + '. Response code', resp.statusCode)
  1238. self.progress += asset.size*1
  1239. self.emit('totaldlprogress', {acc: self.progress, total: self.totaldlsize})
  1240. cb()
  1241. }
  1242. })
  1243. req.on('data', function(chunk){
  1244. count += chunk.length
  1245. self.progress += chunk.length
  1246. acc += chunk.length
  1247. self.emit(identifier + 'dlprogress', acc)
  1248. self.emit('totaldlprogress', {acc: self.progress, total: self.totaldlsize})
  1249. })
  1250. }, function(err){
  1251. if(err){
  1252. self.emit(identifier + 'dlerror')
  1253. console.log('An item in ' + identifier + ' failed to process');
  1254. } else {
  1255. self.emit(identifier + 'dlcomplete')
  1256. console.log('All ' + identifier + ' have been processed successfully')
  1257. }
  1258. self.totaldlsize -= self[identifier].dlsize
  1259. self.progress -= self[identifier].dlsize
  1260. self[identifier] = new DLTracker([], 0)
  1261. if(self.totaldlsize === 0) {
  1262. self.emit('dlcomplete')
  1263. }
  1264. })
  1265. return true
  1266. }
  1267. }
  1268. /**
  1269. * This function will initiate the download processed for the specified identifiers. If no argument is
  1270. * given, all identifiers will be initiated. Note that in order for files to be processed you need to run
  1271. * the processing function corresponding to that identifier. If you run this function without processing
  1272. * the files, it is likely nothing will be enqueued in the object and processing will complete
  1273. * immediately. Once all downloads are complete, this function will fire the 'dlcomplete' event on the
  1274. * global object instance.
  1275. *
  1276. * @param {Array.<{id: string, limit: number}>} identifiers Optional. The identifiers to process and corresponding parallel async task limit.
  1277. */
  1278. processDlQueues(identifiers = [{id:'assets', limit:20}, {id:'libraries', limit:5}, {id:'files', limit:5}, {id:'forge', limit:5}]){
  1279. this.progress = 0;
  1280. let shouldFire = true
  1281. // Assign dltracking variables.
  1282. this.totaldlsize = 0
  1283. this.progress = 0
  1284. for(let i=0; i<identifiers.length; i++){
  1285. this.totaldlsize += this[identifiers[i].id].dlsize
  1286. }
  1287. for(let i=0; i<identifiers.length; i++){
  1288. let iden = identifiers[i]
  1289. let r = this.startAsyncProcess(iden.id, iden.limit)
  1290. if(r) shouldFire = false
  1291. }
  1292. if(shouldFire){
  1293. this.emit('dlcomplete')
  1294. }
  1295. }
  1296. // #endregion
  1297. }
  1298. module.exports = {
  1299. AssetGuard,
  1300. Asset,
  1301. Library
  1302. }