All files / skeleton/modules/autoupdate assetBundleManager.js

65.37% Statements 134/205
48.72% Branches 38/78
92.59% Functions 25/27
65.37% Lines 134/205
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581                                                                                        48x 48x     48x                               62x   62x 62x 62x   62x 62x   62x 62x   62x 62x   62x 62x   62x   62x                 62x                 24x 21x   3x                 57x                                             57x                     59x 59x   59x   59x 59x       59x             59x 59x   2x 2x     57x   57x   57x                 57x   57x       3x       54x     54x     54x 6x 6x 6x         48x                   48x     48x           48x 48x         48x   48x 48x 48x                       48x                     18x 18x   19x 19x 19x 2x 2x 2x                           2x 2x 2x                         48x 48x 48x 48x 48x   48x       48x                     62x 20x 20x       20x 20x           20x 20x                             16x 16x   16x 16x                     40x 40x 40x 40x                 40x                                                                 200x   32x 32x           200x 32x 32x   200x 6x     194x                           194x                     48x   48x   200x   200x 200x   38x 38x 38x         38x         200x   200x 6x 6x 6x       6x         6x     194x         48x         48x               48x   34x 34x 34x 34x         14x   48x                   34x 34x 34x 34x 34x                     48x   48x                                                             48x     1x  
/**
 This is a slightly modified JS port of hot code push android client from here:
 https://github.com/meteor/cordova-plugin-meteor-webapp
 
 The MIT License (MIT)
 
 Copyright (c) 2015 Meteor Development Group
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in all
 copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
 
 This file is based on:
 /cordova-plugin-meteor-webapp/blob/master/src/android/AssetBundleManager.java
 
 */
 
import path from 'path';
import fs from 'fs-plus';
import rimraf from 'rimraf';
import originalFs from 'original-fs';
import url from 'url';
import request from 'request';
import shell from 'shelljs';
 
import AssetBundle from './assetBundle';
import AssetBundleDownloader from './assetBundleDownloader';
import AssetManifest from './assetManifest';
 
function exists(checkPath) {
    try {
        fs.accessSync(checkPath);
        return true;
    } catch (e) {
        return false;
    }
}
class AssetBundleManager {
 
    /**
     * @param {object}      log                - Winston reference.
     * @param {object}      configuration      - Configuration object.
     * @param {AssetBundle} initialAssetBundle - Parent asset bundle.
     * @param {string}      versionsDirectory  - Path to versions dir.
     * @param {string}      desktopBundlePath  - Path to dir with desktop bundles.
     * @param {Object}      appSettings        - Settings from desktop.json.
     * @constructor
     */
    constructor(
        log, configuration, initialAssetBundle, versionsDirectory, desktopBundlePath, appSettings) {
        this.log = log.getLoggerFor('AssetBundleManager');
 
        this.appSettings = appSettings;
        this.configuration = configuration;
        this.initialAssetBundle = initialAssetBundle;
 
        this.versionsDirectory = versionsDirectory;
        this.desktopBundlePath = desktopBundlePath;
 
        this.downloadDirectory = path.join(versionsDirectory, 'Downloading');
        this.partialDownloadDirectory = path.join(versionsDirectory, 'PartialDownload');
 
        this.downloadedAssetBundlesByVersion = {};
        this.partiallyDownloadedAssetBundle = null;
 
        this.callback = null;
        this.assetBundleDownloader = null;
 
        this.httpClient = request;
 
        this.loadDownloadedAssetBundles();
    }
 
    /**
     * Callback setter.
     *
     * @param {Object} callback
     */
    setCallback(callback) {
        this.callback = callback;
    }
 
    /**
     * Returns a bundle searched by version.
     * @param {string} version - Version to get.
     * @returns {AssetBundle|null}
     */
    downloadedAssetBundleWithVersion(version) {
        if (version in this.downloadedAssetBundlesByVersion) {
            return this.downloadedAssetBundlesByVersion[version];
        }
        return null;
    }
 
    /**
     * Tries to download the desktop version manifest.
     * @param {string} desktopVersionUrl - The url to the version.desktop.json
     * @param {function} callback - Function to run after.
     */
    getDesktopVersion(desktopVersionUrl, callback) {
        Iif ('desktopHCP' in this.appSettings && this.appSettings.desktopHCP) {
            this.httpClient(desktopVersionUrl, (error, response, body) => {
                let desktopVersion = {};
                if (error) {
                    this.didFail(`error downloading version.desktop.json: ${error}`);
                    return;
                }
                if (response.statusCode !== 200) {
                    this.didFail(
                        `non-success status code ${response.statusCode} for version.desktop.json`
                    );
                    return;
                }
 
                try {
                    desktopVersion = JSON.parse(body);
                } catch (e) {
                    this.didFail(`error parsing version.desktop.json: ${e.message}`);
                    return;
                }
                callback(desktopVersion);
            });
        } else {
            callback(null);
        }
    }
 
    /**
     * Starts checking for available update.
     *
     * @param {string} baseUrl - Url of meteor server.
     */
    checkForUpdates(baseUrl) {
        let manifest;
        const manifestUrl = url.resolve(baseUrl, 'manifest.json');
        const desktopVersionUrl = url.resolve(baseUrl, 'version.desktop.json?meteor_dont_serve_index=true');
 
        this.log.info(`trying to query ${manifestUrl}`);
 
        this.httpClient(manifestUrl, (error, response, body) => {
            Iif (error) {
                this.didFail(`error downloading asset manifest: ${error}`);
                return;
            }
            Iif (response.statusCode !== 200) {
                this.didFail(
                    `non-success status code ${response.statusCode} for asset manifest`
                );
                return;
            }
 
            try {
                manifest = new AssetManifest(this.log, body);
            } catch (e) {
                this.didFail(e.message);
                return;
            }
 
            const version = manifest.version;
 
            this.log.debug(`downloaded asset manifest for version: ${version}`);
 
            Iif (
                this.assetBundleDownloader !== null &&
                this.assetBundleDownloader.getAssetBundle().getVersion() === version
            ) {
                this.log.info(`already downloading asset bundle version: ${version}`);
                return;
            }
 
            // At this point we will check if we need to download the desktop version information.
            this.getDesktopVersion(desktopVersionUrl, (desktopVersion) => {
                // Give the callback a chance to decide whether the version should be downloaded.
                if (
                    this.callback !== null &&
                    !this.callback.shouldDownloadBundleForManifest(manifest, desktopVersion)
                ) {
                    return;
                }
 
                // Cancel download in progress if there is one.
                Iif (this.assetBundleDownloader !== null) {
                    this.assetBundleDownloader.cancel();
                }
                this.assetBundleDownloader = null;
 
                // There is no need to redownload the initial version.
                if (this.initialAssetBundle.getVersion() === version) {
                    this.log.debug('No redownload of initial version.');
                    this.didFinishDownloadingAssetBundle(this.initialAssetBundle);
                    return;
                }
 
                // If there is a previously downloaded asset bundle with the requested
                // version, use that.
                Iif (version in this.downloadedAssetBundlesByVersion) {
                    const downloadedAssetBundle = this.downloadedAssetBundlesByVersion[version];
                    downloadedAssetBundle.desktopVersion = desktopVersion;
                    if (downloadedAssetBundle !== null) {
                        this.didFinishDownloadingAssetBundle(downloadedAssetBundle);
                        return;
                    }
                }
 
                // Else, get ready to download the new asset bundle
                this.moveExistingDownloadDirectoryIfNeeded();
 
                // Create download directory
                Iif (!this.makeDownloadDirectory()) {
                    this.didFail('could not create download directory');
                    return;
                }
 
                // Copy downloaded asset manifest to file.
                try {
                    fs.writeFileSync(path.join(this.downloadDirectory, 'program.json'), body);
                } catch (e) {
                    this.didFail(e.message);
                    return;
                }
                this.log.debug('manifest copied to new Download dir');
 
                let assetBundle = null;
                try {
                    assetBundle = new AssetBundle(
                        this.log,
                        this.downloadDirectory,
                        manifest,
                        this.initialAssetBundle,
                        desktopVersion === null ? undefined : desktopVersion
                    );
                } catch (e) {
                    this.didFail(e.message);
                    return;
                }
 
                this.downloadAssetBundle(assetBundle, baseUrl);
            });
        });
    }
 
    /**
     * Removes unnecessary versions.
     *
     * @param {AssetBundle} assetBundleToKeep
     */
    removeAllDownloadedAssetBundlesExceptForVersion(assetBundleToKeep) {
        const desktopVersionToKeep = assetBundleToKeep.desktopVersion;
        Object.keys(this.downloadedAssetBundlesByVersion).forEach(
            (assetVersion) => {
                const assetBundle = this.downloadedAssetBundlesByVersion[assetVersion];
                const version = assetBundle.getVersion();
                if (version !== assetBundleToKeep.getVersion()) {
                    const desktopVersion = assetBundle.desktopVersion;
                    console.log('version desktop to delete', desktopVersion);
                    Iif (desktopVersion.version && desktopVersionToKeep.version &&
                        desktopVersion.version !== desktopVersionToKeep.version) {
                        this.log.info(`pruned old ${desktopVersion.version}_desktop.asar`);
 
                        try {
                            originalFs.unlinkSync(path.join(this.desktopBundlePath, `${desktopVersion.version}_desktop.asar`));
                        } catch (e) {
                            // Theoretically no harm if we could not delete it...
                        }
                    }
                    // Using rimraf specifically instead of shelljs.rm because despite using
                    // process.noAsar shelljs tried to remove files inside asar instead of just
                    // deleting the archive. `del` also could not delete asar archive. Rimraf is ok
                    // because it accepts custom fs object.
                    rimraf.sync(path.join(this.versionsDirectory, version), originalFs);
                    delete this.downloadedAssetBundlesByVersion[version];
                    this.log.info(`pruned old version dir ${version}`);
                }
            });
    }
 
    /**
     * Creates Download directory.
     *
     * @returns {boolean}
     * @private
     */
    makeDownloadDirectory() {
        // Make shellJs throw on failure.
        shell.config.fatal = true;
        try {
            Eif (!fs.existsSync(this.downloadDirectory)) {
                this.log.info('created download dir.');
                shell.mkdir(this.downloadDirectory);
            }
            return true;
        } catch (e) {
            this.log.debug(`creating download dir failed: ${e.message}`);
        } finally {
            shell.config.fatal = false;
        }
        return false;
    }
 
    /**
     * Loads all downloaded asset bundles.
     *
     * @private
     */
    loadDownloadedAssetBundles() {
        shell.ls(this.versionsDirectory).forEach((file) => {
            const directory = path.join(this.versionsDirectory, file);
            Eif (this.downloadDirectory !== directory
                && this.partialDownloadDirectory !== directory
                && originalFs.lstatSync(directory).isDirectory()
            ) {
                try {
                    const assetBundle = new AssetBundle(
                        this.log,
                        directory,
                        undefined,
                        this.initialAssetBundle
                    );
                    this.log.info(`got version: ${assetBundle.getVersion()} in ${file}`);
                    this.downloadedAssetBundlesByVersion[assetBundle.getVersion()] = assetBundle;
                } catch (e) {
                    this.log.info(`broken version in directory: ${directory}`);
                }
            }
        });
    }
 
    /**
     * Failure handler.
     *
     * @param {string} cause - Error message.
     * @private
     */
    didFail(cause) {
        this.assetBundleDownloader = null;
        this.log.debug(`fail: ${cause}`);
 
        Eif (this.callback !== null) {
            this.callback.onError(cause);
        }
    }
 
    /**
     * Success handler.
     *
     * @param {AssetBundle} assetBundle - Asset bundle which was downloaded.
     * @private
     */
    didFinishDownloadingAssetBundle(assetBundle) {
        this.assetBundleDownloader = null;
        this.handleDesktopBundle(assetBundle);
        Eif (this.callback !== null) {
            this.callback.onFinishedDownloadingAssetBundle(assetBundle);
        }
    }
 
 
    /**
     * @param {AssetBundle} assetBundle - Asset bundle which was downloaded.
     */
    handleDesktopBundle(assetBundle) {
        Iif (assetBundle.desktopVersion.version) {
            assetBundle.writeDesktopVersion();
            // If there is a new version of desktop.asar copy it with a name changed so it
            // will contain the version.
            const desktopPath = path.join(
                this.desktopBundlePath,
                `${assetBundle.desktopVersion.version}_desktop.asar`
            );
 
            if (assetBundle.desktopVersion.version !== this.appSettings.desktopVersion &&
                !exists(desktopPath)
            ) {
                assetBundle.getOwnAssets().some((asset) => {
                    if (~asset.filePath.indexOf('desktop.asar')) {
                        // TODO: need more efficient way of copying asar archive
                        originalFs.writeFileSync(
                            desktopPath, originalFs.readFileSync(asset.getFile()));
                        return true;
                    }
                    return false;
                });
            }
        }
    }
 
    /**
     * Searches for a cached asset in all available bundles.
     *
     * @param {Asset} asset - Asset we are searching for.
     * @returns {Asset|null}
     * @private
     */
    cachedAssetForAsset(asset) {
        const bundles = Object.keys(this.downloadedAssetBundlesByVersion).reduce(
            (arr, key) => {
                arr.push(this.downloadedAssetBundlesByVersion[key]);
                return arr;
            },
            []
        );
 
        let cachedAsset;
        const assetFound = bundles.some((assetBundle) => {
            cachedAsset = assetBundle.cachedAssetForUrlPath(asset.urlPath, asset.hash);
            return cachedAsset;
        });
        if (assetFound) {
            return cachedAsset;
        }
 
        Iif (this.partiallyDownloadedAssetBundle !== null) {
            cachedAsset =
                this.partiallyDownloadedAssetBundle
                    .cachedAssetForUrlPath(asset.urlPath, asset.hash);
 
            // Make sure the asset has been downloaded.
            try {
                if (cachedAsset !== null && fs.accessSync(cachedAsset.getFile())) {
                    return cachedAsset;
                }
            } catch (e) {
                return null;
            }
        }
        return null;
    }
 
    /**
     * Prepares asset bundle downloader.
     *
     * @param {AssetBundle} assetBundle - Asset bundle to download.
     * @param {string}      baseUrl     - Url to meteor server.
     * @private
     */
    downloadAssetBundle(assetBundle, baseUrl) {
        const missingAssets = [];
 
        assetBundle.getOwnAssets().forEach((asset) => {
            // Create containing directories for the asset if necessary
            const containingDirectory = path.dirname(asset.getFile());
 
            try {
                fs.lstatSync(containingDirectory);
            } catch (e) {
                shell.config.fatal = true;
                try {
                    shell.mkdir('-p', containingDirectory);
                } catch (shellError) {
                    this.didFail(`could not create containing directory: ${containingDirectory}`);
                    return;
                } finally {
                    shell.config.fatal = false;
                }
            }
 
            // If we find a cached asset, we copy it.
            const cachedAsset = this.cachedAssetForAsset(asset);
 
            if (cachedAsset !== null) {
                shell.config.fatal = true;
                try {
                    Iif (~cachedAsset.getFile().indexOf('desktop.asar')) {
                        originalFs.createReadStream(cachedAsset.getFile())
                            .pipe(originalFs.createWriteStream(asset.getFile()));
                    } else {
                        shell.cp(cachedAsset.getFile(), asset.getFile());
                    }
                } catch (e) {
                    this.didFail(e.message);
                } finally {
                    shell.config.fatal = false;
                }
            } else {
                missingAssets.push(asset);
            }
        });
 
        // If all assets were cached, there is no need to start a download.
        Iif (missingAssets.length === 0) {
            this.didFinishDownloadingAssetBundle(assetBundle);
            return;
        }
 
        let assetBundleDownloader = new AssetBundleDownloader(
            this.log,
            this.configuration,
            assetBundle,
            baseUrl,
            missingAssets
        );
 
        assetBundleDownloader.setCallbacks(
            () => {
                assetBundleDownloader = null;
                try {
                    this.moveDownloadedAssetBundleIntoPlace(assetBundle);
                    this.didFinishDownloadingAssetBundle(assetBundle);
                } catch (e) {
                    this.didFail(e);
                }
            },
            cause => this.didFail(cause)
        );
        assetBundleDownloader.resume();
    }
 
    /**
     * Move the downloaded asset bundle to a new directory named after the version.
     *
     * @param {AssetBundle} assetBundle - Asset bundle to move.
     * @private
     */
    moveDownloadedAssetBundleIntoPlace(assetBundle) {
        const version = assetBundle.getVersion();
        const versionDirectory = path.join(this.versionsDirectory, version);
        originalFs.renameSync(this.downloadDirectory, versionDirectory);
        assetBundle.didMoveToDirectoryAtUri(versionDirectory);
        this.downloadedAssetBundlesByVersion[version] = assetBundle;
    }
 
    /**
     * If there is an existing Downloading directory, move it
     * to PartialDownload and load the partiallyDownloadedAssetBundle so we
     * won't unnecessarily redownload assets.
     *
     * @private
     */
    moveExistingDownloadDirectoryIfNeeded() {
        shell.config.fatal = true;
 
        Iif (exists(this.downloadDirectory)) {
            if (exists(this.partialDownloadDirectory)) {
                try {
                    rimraf.sync(this.partialDownloadDirectory, originalFs);
                } catch (e) {
                    this.log.error('could not delete partial download directory.');
                }
            }
 
            this.partiallyDownloadedAssetBundle = null;
 
            try {
                originalFs.renameSync(this.downloadDirectory, this.partialDownloadDirectory);
            } catch (e) {
                this.log.error('could not rename existing download directory');
                shell.config.fatal = false;
                return;
            }
 
            try {
                this.partiallyDownloadedAssetBundle =
                    new AssetBundle(
                        this.log,
                        this.partialDownloadDirectory,
                        undefined,
                        this.initialAssetBundle
                    );
            } catch (e) {
                this.log.warn('could not load partially downloaded asset bundle.');
            }
        }
        shell.config.fatal = false;
    }
}
module.exports = AssetBundleManager;