assetguard.js 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415
  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. const fBp = path.join(binaryPath, 'bin', 'java.exe')
  538. if(fs.existsSync(fBp)){
  539. child_process.exec('"' + fBp + '" -XshowSettings:properties', (err, stdout, stderr) => {
  540. try {
  541. // Output is stored in stderr?
  542. const res = stderr
  543. const props = res.split('\n')
  544. for(let i=0; i<props.length; i++){
  545. if(props[i].indexOf('sun.arch.data.model') > -1){
  546. let arch = props[i].split('=')[1].trim()
  547. console.log(props[i].trim() + ' for ' + binaryPath)
  548. resolve(parseInt(arch) >= 64)
  549. }
  550. }
  551. // sun.arch.data.model not found?
  552. // Disregard this test.
  553. resolve(true)
  554. } catch (err){
  555. // Output format might have changed, validation cannot be completed.
  556. // Disregard this test in that case.
  557. resolve(true)
  558. }
  559. })
  560. } else {
  561. resolve(false)
  562. }
  563. })
  564. }
  565. /**
  566. * Checks for the presence of the environment variable JAVA_HOME. If it exits, we will check
  567. * to see if the value points to a path which exists. If the path exits, the path is returned.
  568. *
  569. * @returns {string} The path defined by JAVA_HOME, if it exists. Otherwise null.
  570. */
  571. static _scanJavaHome(){
  572. const jHome = process.env.JAVA_HOME
  573. try {
  574. let res = fs.existsSync(jHome)
  575. return res ? jHome : null
  576. } catch (err) {
  577. // Malformed JAVA_HOME property.
  578. return null
  579. }
  580. }
  581. /**
  582. * Scans the registry for 64-bit Java entries. The paths of each entry are added to
  583. * a set and returned. Currently, only Java 8 (1.8) is supported.
  584. *
  585. * @returns {Promise.<Set.<string>>} A promise which resolves to a set of 64-bit Java root
  586. * paths found in the registry.
  587. */
  588. static _scanRegistry(){
  589. return new Promise((resolve, reject) => {
  590. // Keys for Java v9.0.0 and later:
  591. // 'SOFTWARE\\JavaSoft\\JRE'
  592. // 'SOFTWARE\\JavaSoft\\JDK'
  593. // Forge does not yet support Java 9, therefore we do not.
  594. let cbTracker = 0
  595. let cbAcc = 0
  596. // Keys for Java 1.8 and prior:
  597. const regKeys = [
  598. '\\SOFTWARE\\JavaSoft\\Java Runtime Environment',
  599. '\\SOFTWARE\\JavaSoft\\Java Development Kit'
  600. ]
  601. const candidates = new Set()
  602. for(let i=0; i<regKeys.length; i++){
  603. const key = new Registry({
  604. hive: Registry.HKLM,
  605. key: regKeys[i],
  606. arch: 'x64'
  607. })
  608. key.keyExists((err, exists) => {
  609. if(exists) {
  610. key.keys((err, javaVers) => {
  611. if(err){
  612. console.error(err)
  613. if(i === regKeys.length-1 && cbAcc === cbTracker){
  614. resolve(candidates)
  615. }
  616. } else {
  617. cbTracker += javaVers.length
  618. if(i === regKeys.length-1 && cbTracker === cbAcc){
  619. resolve(candidates)
  620. } else {
  621. for(let j=0; j<javaVers.length; j++){
  622. const javaVer = javaVers[j]
  623. const vKey = javaVer.key.substring(javaVer.key.lastIndexOf('\\')+1)
  624. // Only Java 8 is supported currently.
  625. if(parseFloat(vKey) === 1.8){
  626. javaVer.get('JavaHome', (err, res) => {
  627. const jHome = res.value
  628. if(jHome.indexOf('(x86)') === -1){
  629. candidates.add(jHome)
  630. }
  631. cbAcc++
  632. if(i === regKeys.length-1 && cbAcc === cbTracker){
  633. resolve(candidates)
  634. }
  635. })
  636. } else {
  637. cbAcc++
  638. if(i === regKeys.length-1 && cbAcc === cbTracker){
  639. resolve(candidates)
  640. }
  641. }
  642. }
  643. }
  644. }
  645. })
  646. } else {
  647. if(i === regKeys.length-1 && cbAcc === cbTracker){
  648. resolve(candidates)
  649. }
  650. }
  651. })
  652. }
  653. })
  654. }
  655. /**
  656. * Attempts to find a valid x64 installation of Java on Windows machines.
  657. * Possible paths will be pulled from the registry and the JAVA_HOME environment
  658. * variable. The paths will be sorted with higher versions preceeding lower, and
  659. * JREs preceeding JDKs. The binaries at the sorted paths will then be validated.
  660. * The first validated is returned.
  661. *
  662. * Higher versions > Lower versions
  663. * If versions are equal, JRE > JDK.
  664. *
  665. * @returns {Promise.<string>} A Promise which resolves to the root path of a valid
  666. * x64 Java installation. If none are found, null is returned.
  667. */
  668. static async _win32JavaValidate(){
  669. // Get possible paths from the registry.
  670. const pathSet = await AssetGuard._scanRegistry()
  671. //console.log(Array.from(pathSet)) // DEBUGGING
  672. // Validate JAVA_HOME
  673. const jHome = AssetGuard._scanJavaHome()
  674. if(jHome != null && jHome.indexOf('(x86)') === -1){
  675. pathSet.add(jHome)
  676. }
  677. // Convert path set to an array for processing.
  678. let pathArr = Array.from(pathSet)
  679. //console.log(pathArr) // DEBUGGING
  680. // Sorts array. Higher version numbers preceed lower. JRE preceeds JDK.
  681. pathArr = pathArr.sort((a, b) => {
  682. // Note that Java 9+ uses semver and that will need to be accounted for in
  683. // the future.
  684. const aVer = parseInt(a.split('_')[1])
  685. const bVer = parseInt(b.split('_')[1])
  686. if(bVer === aVer){
  687. return a.indexOf('jdk') > -1 ? 1 : 0
  688. } else {
  689. return bVer - aVer
  690. }
  691. })
  692. //console.log(pathArr) // DEBUGGING
  693. // Validate that the binary is actually x64.
  694. for(let i=0; i<pathArr.length; i++) {
  695. let res = await AssetGuard._validateJavaBinary(pathArr[i])
  696. if(res){
  697. return pathArr[i]
  698. }
  699. }
  700. // No suitable candidates found.
  701. return null;
  702. }
  703. /**
  704. * WIP -> get a valid x64 Java path on macOS.
  705. */
  706. static async _darwinJavaValidate(){
  707. return null
  708. }
  709. /**
  710. * WIP -> get a valid x64 Java path on linux.
  711. */
  712. static async _linuxJavaValidate(){
  713. return null
  714. }
  715. /**
  716. * Retrieve the path of a valid x64 Java installation.
  717. *
  718. * @returns {string} A path to a valid x64 Java installation, null if none found.
  719. */
  720. static async validateJava(){
  721. return await AssetGuard['_' + process.platform + 'JavaValidate']()
  722. }
  723. // #endregion
  724. // #endregion
  725. // Validation Functions
  726. // #region
  727. /**
  728. * Loads the version data for a given minecraft version.
  729. *
  730. * @param {string} version The game version for which to load the index data.
  731. * @param {boolean} force Optional. If true, the version index will be downloaded even if it exists locally. Defaults to false.
  732. * @returns {Promise.<Object>} Promise which resolves to the version data object.
  733. */
  734. loadVersionData(version, force = false){
  735. const self = this
  736. return new Promise((resolve, reject) => {
  737. const name = version + '.json'
  738. const url = 'https://s3.amazonaws.com/Minecraft.Download/versions/' + version + '/' + name
  739. const versionPath = path.join(self.basePath, 'versions', version)
  740. const versionFile = path.join(versionPath, name)
  741. if(!fs.existsSync(versionFile) || force){
  742. //This download will never be tracked as it's essential and trivial.
  743. console.log('Preparing download of ' + version + ' assets.')
  744. mkpath.sync(versionPath)
  745. const stream = request(url).pipe(fs.createWriteStream(versionFile))
  746. stream.on('finish', () => {
  747. resolve(JSON.parse(fs.readFileSync(versionFile)))
  748. })
  749. } else {
  750. resolve(JSON.parse(fs.readFileSync(versionFile)))
  751. }
  752. })
  753. }
  754. // Asset (Category=''') Validation Functions
  755. // #region
  756. /**
  757. * Public asset validation function. This function will handle the validation of assets.
  758. * It will parse the asset index specified in the version data, analyzing each
  759. * asset entry. In this analysis it will check to see if the local file exists and is valid.
  760. * If not, it will be added to the download queue for the 'assets' identifier.
  761. *
  762. * @param {Object} versionData The version data for the assets.
  763. * @param {boolean} force Optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  764. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  765. */
  766. validateAssets(versionData, force = false){
  767. const self = this
  768. return new Promise(function(fulfill, reject){
  769. self._assetChainIndexData(versionData, force).then(() => {
  770. fulfill()
  771. })
  772. })
  773. }
  774. //Chain the asset tasks to provide full async. The below functions are private.
  775. /**
  776. * Private function used to chain the asset validation process. This function retrieves
  777. * the index data.
  778. * @param {Object} versionData
  779. * @param {boolean} force
  780. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  781. */
  782. _assetChainIndexData(versionData, force = false){
  783. const self = this
  784. return new Promise(function(fulfill, reject){
  785. //Asset index constants.
  786. const assetIndex = versionData.assetIndex
  787. const name = assetIndex.id + '.json'
  788. const indexPath = path.join(self.basePath, 'assets', 'indexes')
  789. const assetIndexLoc = path.join(indexPath, name)
  790. let data = null
  791. if(!fs.existsSync(assetIndexLoc) || force){
  792. console.log('Downloading ' + versionData.id + ' asset index.')
  793. mkpath.sync(indexPath)
  794. const stream = request(assetIndex.url).pipe(fs.createWriteStream(assetIndexLoc))
  795. stream.on('finish', function() {
  796. data = JSON.parse(fs.readFileSync(assetIndexLoc, 'utf-8'))
  797. self._assetChainValidateAssets(versionData, data).then(() => {
  798. fulfill()
  799. })
  800. })
  801. } else {
  802. data = JSON.parse(fs.readFileSync(assetIndexLoc, 'utf-8'))
  803. self._assetChainValidateAssets(versionData, data).then(() => {
  804. fulfill()
  805. })
  806. }
  807. })
  808. }
  809. /**
  810. * Private function used to chain the asset validation process. This function processes
  811. * the assets and enqueues missing or invalid files.
  812. * @param {Object} versionData
  813. * @param {boolean} force
  814. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  815. */
  816. _assetChainValidateAssets(versionData, indexData){
  817. const self = this
  818. return new Promise(function(fulfill, reject){
  819. //Asset constants
  820. const resourceURL = 'http://resources.download.minecraft.net/'
  821. const localPath = path.join(self.basePath, 'assets')
  822. const indexPath = path.join(localPath, 'indexes')
  823. const objectPath = path.join(localPath, 'objects')
  824. const assetDlQueue = []
  825. let dlSize = 0;
  826. //const objKeys = Object.keys(data.objects)
  827. async.forEachOfLimit(indexData.objects, 10, function(value, key, cb){
  828. const hash = value.hash
  829. const assetName = path.join(hash.substring(0, 2), hash)
  830. const urlName = hash.substring(0, 2) + "/" + hash
  831. const ast = new Asset(key, hash, String(value.size), resourceURL + urlName, path.join(objectPath, assetName))
  832. if(!AssetGuard._validateLocal(ast.to, 'sha1', ast.hash)){
  833. dlSize += (ast.size*1)
  834. assetDlQueue.push(ast)
  835. }
  836. cb()
  837. }, function(err){
  838. self.assets = new DLTracker(assetDlQueue, dlSize)
  839. fulfill()
  840. })
  841. })
  842. }
  843. // #endregion
  844. // Library (Category=''') Validation Functions
  845. // #region
  846. /**
  847. * Public library validation function. This function will handle the validation of libraries.
  848. * It will parse the version data, analyzing each library entry. In this analysis, it will
  849. * check to see if the local file exists and is valid. If not, it will be added to the download
  850. * queue for the 'libraries' identifier.
  851. *
  852. * @param {Object} versionData The version data for the assets.
  853. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  854. */
  855. validateLibraries(versionData){
  856. const self = this
  857. return new Promise(function(fulfill, reject){
  858. const libArr = versionData.libraries
  859. const libPath = path.join(self.basePath, 'libraries')
  860. const libDlQueue = []
  861. let dlSize = 0
  862. //Check validity of each library. If the hashs don't match, download the library.
  863. async.eachLimit(libArr, 5, function(lib, cb){
  864. if(Library.validateRules(lib.rules)){
  865. let artifact = (lib.natives == null) ? lib.downloads.artifact : lib.downloads.classifiers[lib.natives[Library.mojangFriendlyOS()]]
  866. const libItm = new Library(lib.name, artifact.sha1, artifact.size, artifact.url, path.join(libPath, artifact.path))
  867. if(!AssetGuard._validateLocal(libItm.to, 'sha1', libItm.hash)){
  868. dlSize += (libItm.size*1)
  869. libDlQueue.push(libItm)
  870. }
  871. }
  872. cb()
  873. }, function(err){
  874. self.libraries = new DLTracker(libDlQueue, dlSize)
  875. fulfill()
  876. })
  877. })
  878. }
  879. // #endregion
  880. // Miscellaneous (Category=files) Validation Functions
  881. // #region
  882. /**
  883. * Public miscellaneous mojang file validation function. These files will be enqueued under
  884. * the 'files' identifier.
  885. *
  886. * @param {Object} versionData The version data for the assets.
  887. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  888. */
  889. validateMiscellaneous(versionData){
  890. const self = this
  891. return new Promise(async function(fulfill, reject){
  892. await self.validateClient(versionData)
  893. await self.validateLogConfig(versionData)
  894. fulfill()
  895. })
  896. }
  897. /**
  898. * Validate client file - artifact renamed from client.jar to '{version}'.jar.
  899. *
  900. * @param {Object} versionData The version data for the assets.
  901. * @param {boolean} force Optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  902. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  903. */
  904. validateClient(versionData, force = false){
  905. const self = this
  906. return new Promise(function(fulfill, reject){
  907. const clientData = versionData.downloads.client
  908. const version = versionData.id
  909. const targetPath = path.join(self.basePath, 'versions', version)
  910. const targetFile = version + '.jar'
  911. let client = new Asset(version + ' client', clientData.sha1, clientData.size, clientData.url, path.join(targetPath, targetFile))
  912. if(!AssetGuard._validateLocal(client.to, 'sha1', client.hash) || force){
  913. self.files.dlqueue.push(client)
  914. self.files.dlsize += client.size*1
  915. fulfill()
  916. } else {
  917. fulfill()
  918. }
  919. })
  920. }
  921. /**
  922. * Validate log config.
  923. *
  924. * @param {Object} versionData The version data for the assets.
  925. * @param {boolean} force Optional. If true, the asset index will be downloaded even if it exists locally. Defaults to false.
  926. * @returns {Promise.<void>} An empty promise to indicate the async processing has completed.
  927. */
  928. validateLogConfig(versionData){
  929. const self = this
  930. return new Promise(function(fulfill, reject){
  931. const client = versionData.logging.client
  932. const file = client.file
  933. const targetPath = path.join(self.basePath, 'assets', 'log_configs')
  934. let logConfig = new Asset(file.id, file.sha1, file.size, file.url, path.join(targetPath, file.id))
  935. if(!AssetGuard._validateLocal(logConfig.to, 'sha1', logConfig.hash)){
  936. self.files.dlqueue.push(logConfig)
  937. self.files.dlsize += logConfig.size*1
  938. fulfill()
  939. } else {
  940. fulfill()
  941. }
  942. })
  943. }
  944. // #endregion
  945. // Distribution (Category=forge) Validation Functions
  946. // #region
  947. /**
  948. * Validate the distribution.
  949. *
  950. * @param {string} serverpackid The id of the server to validate.
  951. * @returns {Promise.<Object>} A promise which resolves to the server distribution object.
  952. */
  953. validateDistribution(serverpackid){
  954. const self = this
  955. return new Promise(function(fulfill, reject){
  956. AssetGuard.retrieveDistributionData(self.basePath, false).then((value) => {
  957. /*const servers = value.servers
  958. let serv = null
  959. for(let i=0; i<servers.length; i++){
  960. if(servers[i].id === serverpackid){
  961. serv = servers[i]
  962. break
  963. }
  964. }*/
  965. const serv = AssetGuard.getServerById(self.basePath, serverpackid)
  966. if(serv == null) {
  967. console.error('Invalid server pack id:', serverpackid)
  968. }
  969. self.forge = self._parseDistroModules(serv.modules, serv.mc_version)
  970. //Correct our workaround here.
  971. let decompressqueue = self.forge.callback
  972. self.forge.callback = function(asset){
  973. if(asset.to.toLowerCase().endsWith('.pack.xz')){
  974. AssetGuard._extractPackXZ([asset.to], self.javaexec)
  975. }
  976. if(asset.type === 'forge-hosted' || asset.type === 'forge'){
  977. AssetGuard._finalizeForgeAsset(asset, self.basePath)
  978. }
  979. }
  980. fulfill(serv)
  981. })
  982. })
  983. }
  984. /*//TODO The file should be hosted, the following code is for local testing.
  985. _chainValidateDistributionIndex(basePath){
  986. return new Promise(function(fulfill, reject){
  987. //const distroURL = 'http://mc.westeroscraft.com/WesterosCraftLauncher/westeroscraft.json'
  988. //const targetFile = path.join(basePath, 'westeroscraft.json')
  989. //TEMP WORKAROUND TO TEST WHILE THIS IS NOT HOSTED
  990. fs.readFile(path.join(__dirname, '..', 'westeroscraft.json'), 'utf-8', (err, data) => {
  991. fulfill(JSON.parse(data))
  992. })
  993. })
  994. }*/
  995. _parseDistroModules(modules, version){
  996. let alist = []
  997. let asize = 0;
  998. //This may be removed soon, considering the most efficient way to extract.
  999. let decompressqueue = []
  1000. for(let i=0; i<modules.length; i++){
  1001. let ob = modules[i]
  1002. let obType = ob.type
  1003. let obArtifact = ob.artifact
  1004. let obPath = obArtifact.path == null ? AssetGuard._resolvePath(ob.id, obArtifact.extension) : obArtifact.path
  1005. switch(obType){
  1006. case 'forge-hosted':
  1007. case 'forge':
  1008. case 'library':
  1009. obPath = path.join(this.basePath, 'libraries', obPath)
  1010. break
  1011. case 'forgemod':
  1012. //obPath = path.join(this.basePath, 'mods', obPath)
  1013. obPath = path.join(this.basePath, 'modstore', obPath)
  1014. break
  1015. case 'litemod':
  1016. //obPath = path.join(this.basePath, 'mods', version, obPath)
  1017. obPath = path.join(this.basePath, 'modstore', obPath)
  1018. break
  1019. case 'file':
  1020. default:
  1021. obPath = path.join(this.basePath, obPath)
  1022. }
  1023. let artifact = new DistroModule(ob.id, obArtifact.MD5, obArtifact.size, obArtifact.url, obPath, obType)
  1024. const validationPath = obPath.toLowerCase().endsWith('.pack.xz') ? obPath.substring(0, obPath.toLowerCase().lastIndexOf('.pack.xz')) : obPath
  1025. if(!AssetGuard._validateLocal(validationPath, 'MD5', artifact.hash)){
  1026. asize += artifact.size*1
  1027. alist.push(artifact)
  1028. if(validationPath !== obPath) decompressqueue.push(obPath)
  1029. }
  1030. //Recursively process the submodules then combine the results.
  1031. if(ob.sub_modules != null){
  1032. let dltrack = this._parseDistroModules(ob.sub_modules, version)
  1033. asize += dltrack.dlsize*1
  1034. alist = alist.concat(dltrack.dlqueue)
  1035. decompressqueue = decompressqueue.concat(dltrack.callback)
  1036. }
  1037. }
  1038. //Since we have no callback at this point, we use this value to store the decompressqueue.
  1039. return new DLTracker(alist, asize, decompressqueue)
  1040. }
  1041. /**
  1042. * Loads Forge's version.json data into memory for the specified server id.
  1043. *
  1044. * @param {string} serverpack The id of the server to load Forge data for.
  1045. * @returns {Promise.<Object>} A promise which resolves to Forge's version.json data.
  1046. */
  1047. loadForgeData(serverpack){
  1048. const self = this
  1049. return new Promise(async function(fulfill, reject){
  1050. let distro = AssetGuard.retrieveDistributionDataSync(self.basePath)
  1051. const servers = distro.servers
  1052. let serv = null
  1053. for(let i=0; i<servers.length; i++){
  1054. if(servers[i].id === serverpack){
  1055. serv = servers[i]
  1056. break
  1057. }
  1058. }
  1059. const modules = serv.modules
  1060. for(let i=0; i<modules.length; i++){
  1061. const ob = modules[i]
  1062. if(ob.type === 'forge-hosted' || ob.type === 'forge'){
  1063. let obArtifact = ob.artifact
  1064. let obPath = obArtifact.path == null ? path.join(self.basePath, 'libraries', AssetGuard._resolvePath(ob.id, obArtifact.extension)) : obArtifact.path
  1065. let asset = new DistroModule(ob.id, obArtifact.MD5, obArtifact.size, obArtifact.url, obPath, ob.type)
  1066. let forgeData = await AssetGuard._finalizeForgeAsset(asset, self.basePath)
  1067. fulfill(forgeData)
  1068. return
  1069. }
  1070. }
  1071. reject('No forge module found!')
  1072. })
  1073. }
  1074. _parseForgeLibraries(){
  1075. /* TODO
  1076. * Forge asset validations are already implemented. When there's nothing much
  1077. * to work on, implement forge downloads using forge's version.json. This is to
  1078. * have the code on standby if we ever need it (since it's half implemented already).
  1079. */
  1080. }
  1081. // #endregion
  1082. // Java (Category=''') Validation (download) Functions
  1083. // #region
  1084. _enqueueOracleJRE(dir){
  1085. return new Promise((resolve, reject) => {
  1086. AssetGuard._latestJREOracle().then(verData => {
  1087. if(verData != null){
  1088. const combined = verData.uri + PLATFORM_MAP[process.platform]
  1089. const opts = {
  1090. url: combined,
  1091. headers: {
  1092. 'Cookie': 'oraclelicense=accept-securebackup-cookie'
  1093. }
  1094. }
  1095. request.head(opts, (err, resp, body) => {
  1096. if(err){
  1097. resolve(false)
  1098. } else {
  1099. const name = combined.substring(combined.lastIndexOf('/')+1)
  1100. const fDir = path.join(dir, name)
  1101. const jre = new Asset(name, null, resp.headers['content-length'], opts, fDir)
  1102. this.java = new DLTracker([jre], jre.size, a => {
  1103. targz.decompress({
  1104. src: a.to,
  1105. dest: dir
  1106. }, err => {
  1107. if(err){
  1108. console.log(err)
  1109. } else {
  1110. fs.unlink(a.to, err => {
  1111. if(err){
  1112. console.log(err)
  1113. }
  1114. })
  1115. }
  1116. })
  1117. })
  1118. resolve(true)
  1119. }
  1120. })
  1121. } else {
  1122. resolve(false)
  1123. }
  1124. })
  1125. })
  1126. }
  1127. /*_enqueueMojangJRE(dir){
  1128. return new Promise((resolve, reject) => {
  1129. // Mojang does not host the JRE for linux.
  1130. if(process.platform === 'linux'){
  1131. resolve(false)
  1132. }
  1133. AssetGuard.loadMojangLauncherData().then(data => {
  1134. if(data != null) {
  1135. try {
  1136. const mJRE = data[Library.mojangFriendlyOS()]['64'].jre
  1137. const url = mJRE.url
  1138. request.head(url, (err, resp, body) => {
  1139. if(err){
  1140. resolve(false)
  1141. } else {
  1142. const name = url.substring(url.lastIndexOf('/')+1)
  1143. const fDir = path.join(dir, name)
  1144. const jre = new Asset('jre' + mJRE.version, mJRE.sha1, resp.headers['content-length'], url, fDir)
  1145. this.java = new DLTracker([jre], jre.size, a => {
  1146. fs.readFile(a.to, (err, data) => {
  1147. // Data buffer needs to be decompressed from lzma,
  1148. // not really possible using node.js
  1149. })
  1150. })
  1151. }
  1152. })
  1153. } catch (err){
  1154. resolve(false)
  1155. }
  1156. }
  1157. })
  1158. })
  1159. }*/
  1160. // #endregion
  1161. // #endregion
  1162. // Control Flow Functions
  1163. // #region
  1164. /**
  1165. * Initiate an async download process for an AssetGuard DLTracker.
  1166. *
  1167. * @param {string} identifier The identifier of the AssetGuard DLTracker.
  1168. * @param {number} limit Optional. The number of async processes to run in parallel.
  1169. * @returns {boolean} True if the process began, otherwise false.
  1170. */
  1171. startAsyncProcess(identifier, limit = 5){
  1172. const self = this
  1173. let acc = 0
  1174. const concurrentDlTracker = this[identifier]
  1175. const concurrentDlQueue = concurrentDlTracker.dlqueue.slice(0)
  1176. if(concurrentDlQueue.length === 0){
  1177. return false
  1178. } else {
  1179. async.eachLimit(concurrentDlQueue, limit, function(asset, cb){
  1180. let count = 0;
  1181. mkpath.sync(path.join(asset.to, ".."))
  1182. let req = request(asset.from)
  1183. req.pause()
  1184. req.on('response', (resp) => {
  1185. if(resp.statusCode === 200){
  1186. let writeStream = fs.createWriteStream(asset.to)
  1187. writeStream.on('close', () => {
  1188. //console.log('DLResults ' + asset.size + ' ' + count + ' ', asset.size === count)
  1189. if(concurrentDlTracker.callback != null){
  1190. concurrentDlTracker.callback.apply(concurrentDlTracker, [asset])
  1191. }
  1192. cb()
  1193. })
  1194. req.pipe(writeStream)
  1195. req.resume()
  1196. } else {
  1197. req.abort()
  1198. const realFrom = typeof asset.from === 'object' ? asset.from.url : asset.from
  1199. console.log('Failed to download ' + realFrom + '. Response code', resp.statusCode)
  1200. self.progress += asset.size*1
  1201. self.emit('totaldlprogress', {acc: self.progress, total: self.totaldlsize})
  1202. cb()
  1203. }
  1204. })
  1205. req.on('data', function(chunk){
  1206. count += chunk.length
  1207. self.progress += chunk.length
  1208. acc += chunk.length
  1209. self.emit(identifier + 'dlprogress', acc)
  1210. self.emit('totaldlprogress', {acc: self.progress, total: self.totaldlsize})
  1211. })
  1212. }, function(err){
  1213. if(err){
  1214. self.emit(identifier + 'dlerror')
  1215. console.log('An item in ' + identifier + ' failed to process');
  1216. } else {
  1217. self.emit(identifier + 'dlcomplete')
  1218. console.log('All ' + identifier + ' have been processed successfully')
  1219. }
  1220. self.totaldlsize -= self[identifier].dlsize
  1221. self.progress -= self[identifier].dlsize
  1222. self[identifier] = new DLTracker([], 0)
  1223. if(self.totaldlsize === 0) {
  1224. self.emit('dlcomplete')
  1225. }
  1226. })
  1227. return true
  1228. }
  1229. }
  1230. /**
  1231. * This function will initiate the download processed for the specified identifiers. If no argument is
  1232. * given, all identifiers will be initiated. Note that in order for files to be processed you need to run
  1233. * the processing function corresponding to that identifier. If you run this function without processing
  1234. * the files, it is likely nothing will be enqueued in the object and processing will complete
  1235. * immediately. Once all downloads are complete, this function will fire the 'dlcomplete' event on the
  1236. * global object instance.
  1237. *
  1238. * @param {Array.<{id: string, limit: number}>} identifiers Optional. The identifiers to process and corresponding parallel async task limit.
  1239. */
  1240. processDlQueues(identifiers = [{id:'assets', limit:20}, {id:'libraries', limit:5}, {id:'files', limit:5}, {id:'forge', limit:5}]){
  1241. this.progress = 0;
  1242. let shouldFire = true
  1243. // Assign dltracking variables.
  1244. this.totaldlsize = 0
  1245. this.progress = 0
  1246. for(let i=0; i<identifiers.length; i++){
  1247. this.totaldlsize += this[identifiers[i].id].dlsize
  1248. }
  1249. for(let i=0; i<identifiers.length; i++){
  1250. let iden = identifiers[i]
  1251. let r = this.startAsyncProcess(iden.id, iden.limit)
  1252. if(r) shouldFire = false
  1253. }
  1254. if(shouldFire){
  1255. this.emit('dlcomplete')
  1256. }
  1257. }
  1258. // #endregion
  1259. }
  1260. module.exports = {
  1261. AssetGuard,
  1262. Asset,
  1263. Library
  1264. }