All files / skeleton/modules/autoupdate assetBundleDownloader.js

89.09% Statements 98/110
74.07% Branches 40/54
85.71% Functions 12/14
89.91% Lines 98/109
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                                                                                                      48x 48x   48x 48x 48x 48x 48x   48x   48x 48x 48x 48x 48x   48x                                 48x 48x             48x   48x                                           194x 194x   194x 194x   4x 4x     190x     190x 34x 34x 34x     34x     156x                   190x 48x 48x 48x 48x   10x 10x         180x   180x   180x 34x         34x 34x         48x 194x 194x 194x 194x 194x     194x 194x       194x         48x             14x 14x                     194x       194x 194x     194x         194x 146x     194x                       194x 2x             192x   192x 106x   106x 106x   106x 106x   106x 2x       104x                                             14x   14x   14x 14x 14x                     48x 48x   48x 48x 2x           46x 2x     44x   44x 44x   44x 2x           42x 2x     40x   40x 2x               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/AssetBundleDownloader.java
 
 */
 
import fs from 'fs';
import originalFs from 'original-fs';
import url from 'url';
// TODO: maybe use node-fetch?
import request from 'request';
import queue from 'queue';
import IsDesktopInjector from './isDesktopInjector';
 
export default class AssetBundleDownloader {
    /**
     * Assets downloader - responsible for downloading an asset version.
     *
     * @param {object}      log           - Winston reference.
     * @param {object}      configuration - Configuration object.
     * @param {AssetBundle} assetBundle   - Parent asset bundle.
     * @param {string}      baseUrl       - Url of the meteor server.
     * @param {[Asset]}     missingAssets - Array of assets to download.
     * @constructor
     */
    constructor(log, configuration, assetBundle, baseUrl, missingAssets) {
        this.log = log.getLoggerFor('AssetBundleDownloader');
        this.log.debug(`downloader created for ${assetBundle.directoryUri}`);
 
        this.configuration = configuration;
        this.assetBundle = assetBundle;
        this.baseUrl = baseUrl;
        this.injector = new IsDesktopInjector();
        this.httpClient = request;
 
        this.eTagWithSha1HashPattern = new RegExp('"([0-9a-f]{40})"');
 
        this.missingAssets = missingAssets;
        this.assetsDownloading = [];
        this.onFinished = null;
        this.onFailure = null;
        this.cancelInvoked = false;
 
        this.queue = queue();
    }
 
    /**
     * Asset bundle getter.
     */
    getAssetBundle() {
        return this.assetBundle;
    }
 
    /**
     * Stores callbacks.
     *
     * @param {function} onFinished - Callback for success.
     * @param {function} onFailure  - Callback for failure.
     */
    setCallbacks(onFinished, onFailure) {
        this.onFinished = onFinished;
        this.onFailure = onFailure;
    }
 
    /**
     * Starts the download.
     */
    resume() {
        const self = this;
 
        this.log.verbose(
            `started downloading assets from bundle with version: ${this.assetBundle.getVersion()}`
        );
 
        /**
         * @param {Asset} asset  - Asset whose downloading failed.
         * @param {string} cause - The cause.
         */
        function onFailure(asset, cause) {
            self.assetsDownloading.splice(self.assetsDownloading.indexOf(asset), 1);
 
            if (!self.cancelInvoked) {
                self.didFail(`error downloading asset: ${asset.filePath}: ${cause}`);
            }
        }
 
        /**
         * @param {Asset} asset - Asset that was downloaded.
         * @param {Object} response - Response object from `request`.
         * @param {Buffer} body - Body of downloaded the file.
         */
        function onResponse(asset, response, body) {
            const fileContents = body;
            self.assetsDownloading.splice(self.assetsDownloading.indexOf(asset), 1);
 
            try {
                self.verifyResponse(response, asset, fileContents);
            } catch (e) {
                self.didFail(`failed at verifyResponse: ${e.message}`);
                return;
            }
 
            try {
                // Unfortunately on every hot code push we need to ensure that we will not loose
                // `Meteor.isDesktop`. Here we will inject it into the code that arrived from HCP.
                if (asset.fileType === 'js') {
                    const fileContentsString = fileContents.toString('UTF-8');
                    const result = self.injector.processFileContents(fileContentsString);
                    Iif (result.injected || result.injectedStartupDidComplete) {
                        fs.writeFileSync(asset.getFile(), result.fileContents, 'UTF-8');
                    } else {
                        fs.writeFileSync(asset.getFile(), fileContents);
                    }
                } else {
                    originalFs.writeFileSync(asset.getFile(), fileContents);
                }
            } catch (e) {
                self.didFail(`failed at injecting isDesktop and writing to disk: ${e.message}`);
                return;
            }
 
            // We don't have a hash for the index page, so we have to parse the runtime config
            // and compare autoupdateVersionCordova to the version in the manifest to verify
            // if we downloaded the expected version.
            if (asset.filePath === 'index.html') {
                const runtimeConfig = self.assetBundle.getRuntimeConfig();
                Eif (runtimeConfig !== null) {
                    try {
                        self.verifyRuntimeConfig(runtimeConfig);
                    } catch (e) {
                        self.didFail(`fail at verifyRuntimeConfig: ${e}`);
                        return;
                    }
                }
            }
 
            self.log.verbose(`saving ${asset.urlPath}`);
 
            self.missingAssets.splice(self.missingAssets.indexOf(asset), 1);
 
            if (self.missingAssets.length === 0) {
                self.log.verbose(
                    'finished downloading new asset bundle version:' +
                    `${self.assetBundle.getVersion()}`
                );
 
                Eif (self.onFinished) {
                    self.onFinished();
                }
            }
        }
 
        this.missingAssets.forEach((asset) => {
            Eif (!~self.assetsDownloading.indexOf(asset)) {
                self.assetsDownloading.push(asset);
                const downloadUrl = self.downloadUrlForAsset(asset);
                self.queue.push((callback) => {
                    self.httpClient(
                        { uri: downloadUrl, encoding: null },
                        (error, response, body) => {
                            Eif (!error) {
                                onResponse(asset, response, body);
                            } else {
                                onFailure(asset, error);
                            }
                            callback();
                        });
                });
            }
        });
        self.queue.start();
    }
 
    /**
     * Cancels downloading.
     */
    cancel() {
        this.cancelInvoked = true;
        this.queue.end();
    }
 
    /**
     * Computes a download url for asset.
     *
     * @param {Asset} asset - Asset for which the url is created.
     * @returns {string}
     * @private
     */
    downloadUrlForAsset(asset) {
        let urlPath = asset.urlPath;
 
        // Remove leading / from URL path because the path should be
        // interpreted relative to the base URL.
        Eif (urlPath[0] === '/') {
            urlPath = urlPath.substring(1);
        }
 
        const builder = url.parse(url.resolve(this.baseUrl, urlPath));
 
        // To avoid inadvertently downloading the default index page when an asset
        // is not found, we add meteor_dont_serve_index=true to the URL unless we
        // are actually downloading the index page.
        if (asset.filePath !== 'index.html') {
            builder.query = { meteor_dont_serve_index: 'true' };
        }
 
        return url.format(builder);
    }
 
    /**
     * Verifies response from the server.
     *
     * @param {Object} response - Http response object.
     * @param {Asset}  asset    - Asset which was downloaded.
     * @param {Buffer} body     - Body of the file as a Buffer.
     * @private
     */
    verifyResponse(response, asset, body) {
        if (response.statusCode !== 200) {
            throw new Error(
                `non-success status code ${response.statusCode} for asset: ${asset.filePath}`
            );
        }
 
        // If we have a hash for the asset, and the ETag header also specifies
        // a hash, we compare these to verify if we received the expected asset version.
        const expectedHash = asset.hash;
 
        if (expectedHash !== null) {
            const eTag = response.headers.etag;
 
            Eif (eTag !== null) {
                const matches = eTag.match(this.eTagWithSha1HashPattern);
 
                Eif (this.eTagWithSha1HashPattern.test(eTag)) {
                    const actualHash = matches[1];
 
                    if (actualHash !== expectedHash) {
                        throw new Error(
                            `hash mismatch for asset: ${asset.filePath} - expected hash:` +
                            `${expectedHash} != ${actualHash}`
                        );
                    } else Iif (asset.entrySize !== body.length) {
                        // This check is specific to this integration. It is not present in
                        // Cordova integration.
                        // For now will not throw here as it is accepted on Cordova.
                        this.log.debug(`wrong size for: ${asset.filePath} - expected: ` +
                            `${asset.entrySize} != ${body.length}`);
                    }
                } else {
                    this.log.warn(`invalid etag format for ${asset.urlPath}: ${eTag}`);
                }
            } else {
                this.log.warn(`no eTag served for ${asset.urlPath}`);
            }
        }
    }
 
    /**
     * Fail handler.
     *
     * @param {string} cause - Error message;
     * @private
     */
    didFail(cause) {
        Iif (this.cancelInvoked) return;
 
        this.cancel();
 
        this.log.debug(`failure: ${cause}`);
        Eif (this.onFailure !== null) {
            this.onFailure(cause);
        }
    }
 
    /**
     * Verifies runtime config.
     *
     * @param {Object} runtimeConfig - Runtime config.
     * @private
     */
    verifyRuntimeConfig(runtimeConfig) {
        const expectedVersion = this.assetBundle.getVersion();
        const actualVersion = runtimeConfig.autoupdateVersionCordova;
 
        Eif (actualVersion) {
            if (actualVersion !== expectedVersion) {
                throw new Error(
                    `version mismatch for index page, expected: ${expectedVersion}` +
                    `, actual: ${actualVersion}`);
            }
        }
 
        if (!('ROOT_URL' in runtimeConfig)) {
            throw new Error('could not find ROOT_URL in downloaded asset bundle');
        }
 
        const rootUrlString = runtimeConfig.ROOT_URL;
 
        const rootUrl = url.parse(rootUrlString);
        const previousRootUrl = url.parse(this.configuration.rootUrlString);
 
        if (previousRootUrl.hostname !== 'localhost' && rootUrl.hostname === 'localhost') {
            throw new Error(
                'ROOT_URL in downloaded asset bundle would change current ROOT_URL ' +
                'to localhost. Make sure ROOT_URL has been configured correctly on the server.'
            );
        }
 
        if (!('appId' in runtimeConfig)) {
            throw new Error('could not find appId in downloaded asset bundle.');
        }
 
        const appId = runtimeConfig.appId;
 
        if (appId !== this.configuration.appId) {
            throw new Error(
                'appId in downloaded asset bundle does not match current appId. Make sure the' +
                ` server at ${rootUrlString} is serving the right app.`
            );
        }
    }
}
 
module.exports = AssetBundleDownloader;