player.js 30.5 KB
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 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
/*
 * ADOBE CONFIDENTIAL
 *
 * Copyright 2015 Adobe Systems Incorporated
 * All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Adobe Systems Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Adobe Systems Incorporated and its
 * suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Adobe Systems Incorporated.
 */
/* globals Promise */
define('screens/player/runtime/player', [
    'jquery',
    'underscore',
    'eventemitter',
    'window.io',
    'screens/player/shared/util',
    'screens/player/shared/csrf',
    'screens/player/firmware/core/datastore',
    'screens/player/ui/overlay',
    'screens/player/firmware/core/bridge',
    'screens/player/firmware/packagemanager/packagemanager',
    'screens/player/ui/connectivity',
    'screens/player/ui/osd/osd',
    'screens/player/ui/activity',
    'screens/player/runtime/orchestrator',
    'screens/player/shared/serviceadmin',
    'screens/player/firmware/preferences/preferences',
    'screens/player/firmware/update/update',
    'screens/player/store/store',
    'screens/player/firmware/core/config/config',
    'screens/player/firmware/core/statusmodel/statusmodel',
    'screens/player/firmware/command/command-handler',
    'screens/player/runtime/admin',
    'screens/player/runtime/impl/video-service',
    'screens/player/firmware/statusinfo/statusinfo'
], function($, _, EventEmitter, WindowIO, util, CSRFSupport, DataStore, Overlay, Bridge, PackageManager, Connectivity, OSD, Activity, Orchestrator, ServiceAdmin, Preferences, Update, Store, Config, StatusModel, CommandHandler, Admin, VideoService, StatusInfo) {
    'use strict';

    /**
     * Default options for the component.
     *
     * @typedef {Object} Player.PlayerOptions
     * @type {Object}
     * @property {Object} firmware              The firmware
     * @property {String} user                  The Username
     * @property {String} password              The Password
     * @property {Number} [pollingInterval]     Time between each check when polling urls (in ms)
     * @property {Number} [requestTimeout]      Time to wait before considering a request has timed out (in ms)
     * @property {Number} [longPressDuration]   Duration of a long press (in ms)
     */
    var DEFAULTS = {
        firmware: null,
        user: null,
        password: null,
        pollingInterval: 5000, // ms
        requestTimeout: 10000, // ms
        longPressDuration: 1000, // ms
        failedDownloadRetryInterval: 60000 // ms
    };

    var EVENTS = Object.freeze({

        /**
         * Trigger a channel switch.
         * @event switch-channel
         *
         * @param {String}  role   The role of the channel to switch to
         * @param {Boolean} forced Whether to force the channel or not
         */
        SWITCH_CHANNEL: 'switch-channel'

    });

    var PACKAGE_MANAGER_SYNC_STATUS = [
        'stopped',
        'downloading',
        'extracting',
        'complete'
    ];

    var _handleUpdateError = function(channel) {
        return function(errorPayload) {
            this._onPackageManagerError(errorPayload);
            var err = errorPayload.error;
            // INVALID_URL_ERR: just log the error as trying again won't solve the issue
            if (err.type === 1) {
                console.error('[Player] Invalid offline zip path', channel.offline.zipPath);
                return;
            }

            // UNZIP_ERR: just log the error as trying again will likely not solve the issue (zip is probably corrupt)
            if (err.type === 3) {
                console.error('[Player] Could not extract zip file', channel.offline.zipPath);
                return;
            }

            // CONNECTION_ERR: log the error and try to download again by invalidating the offline timestamp,
            // so the next ping triggers a new download
            if (err.type === 2) {
                console.warn('[Player] Network error while downloading zip file', channel.offline.zipPath);
                this.redownloadTiemout = window.setTimeout(function() {
                    // Invalidate the channel timestamp
                    var configSvc = ServiceAdmin.getService(Config.serviceName);
                    configSvc.invalidateChannelTimestamp(configSvc.getChannels(), channel);

                    // Force a config update
                    this.bridge.emit(Bridge.events.COMMAND, Config.COMMANDS.UPDATE);
                }.bind(this), this.options.failedDownloadRetryInterval);
                return;
            }

            console.error('[Player] Unknown sync error: ', err.message);
        };
    };

    /**
     * Prepare the channels: before being able to show a channel, some preparation might be required like downloading the
     * offline package, unzipping that package... This method contains all required operations.
     *
     * @param  {Object[]| Object} channels Channels to prepare: either an array of channels
     * or an object of channels (format like {role1: channel1, role2: channel2...})
     *
     * @return {Promise} A promise to prepare all the channels
     */
    var prepareChannels = function(channels) {
        var self = this;

        var packageManager = ServiceAdmin.getService(PackageManager.serviceName);

        if (!packageManager || this._offline) {
            // No preparation work required
            return Promise.resolve();
        }

        // Preparation step 1: cache offline channels
        var updatePromises = [];
        var channelIds = [];

        // construct a list of promises to be executed for each channel
        var _constructPromises = function(channel) {
            if (channel.offline && channel.offline.enabled && channel.offline.zipPath && channel.offline.local) {
                if (channelIds.indexOf(channel.offline.local.uid) === -1) {
                    updatePromises.push(
                        packageManager
                            .updatePackage(
                                channel.offline.zipPath,
                                channel.offline.local.destination,
                                channel.offline.timestamp,
                                channel.offline.local.mode,
                                channel.title + ' - ' + channel.offline.local.uid,
                                channel.offline.local.uid)
                            .then(function(payload) {
                                console.log('[Player] Completed sync of ' + payload.title);
                                self._onPackageManagerCompleted(payload);
                            })
                            .catch(_handleUpdateError(channel).bind(self))
                    );
                    channelIds.push(channel.offline.local.uid);
                }
            }
        };

        if (Array.isArray(channels)) {
            // channels is array
            channels.forEach(_constructPromises);
        } else {
            // channels is object of channels ({role1: channel1, role2: channel2...})
            for (var c in channels) {
                _constructPromises(channels[c]);
            }
        }

        // unwind channels sequentially and suppress errors
        return new Promise(function(resolve) {
            function next() {
                console.log('[Player] Preparing a channel...');
                var p = updatePromises.shift();
                if (p) {
                    p.then(next).catch(function(e) {
                        console.log('[Player] Error while preparing a channel ' + e);
                        next();
                    });
                } else {
                    console.log('[Player] All channels have been prepared.');
                    resolve();
                }
            }

            next();
        });
    };

    var getDisplayURL = function(device) {
        var firmwareLocation = window.location.href.substring(0, window.location.href.indexOf('.html'));
        var zoneTemplate = device.zoneTemplate ? device.zoneTemplate : '';
        if (zoneTemplate !== '') {
            return firmwareLocation + '/display.' + zoneTemplate + '.html';
        }
        return firmwareLocation + '/display.html';
    };

    var handleDisplayModified = function(newDisplay, oldDisplay) {
        if (oldDisplay &&
            newDisplay &&
            newDisplay.path === oldDisplay.path &&
            newDisplay.lastModified === oldDisplay.lastModified) {
            // if last modified data did not change, do nothing
            return;
        }

        if (_.isEmpty(newDisplay)) {
            // if new display is empty, stop the player
            this.stop();
        } else {
            // otherwise, just (re) start the player
            this.start();
        }
    };

    var handleDeviceModified = function(newDevice, oldDevice) {
        if (oldDevice &&
            newDevice &&
            newDevice.lastModified === oldDevice.lastModified &&
            newDevice.path === oldDevice.path &&
            newDevice.configPath === oldDevice.configPath &&
            newDevice.zoneTemplate === oldDevice.zoneTemplate &&
            _.isEqual(newDevice.zoneMapping, oldDevice.zoneMapping)) {
            // if key device properties (the ones with an impact on rendering) did not change, do nothing
            return;
        }

        if (_.isEmpty(newDevice) || (!newDevice.configPath && !newDevice.mockDevice)) {
            // if new device is empty or does not have a config path (happens when un-assigned, device is modified but no config path), stop the player
            this.stop();
        } else {
            // otherwise, just (re) start the player
            this.start();
        }
    };

    /**
     * Computes the modified channels and zones based on the ping data.
     * @private
     * @param {Map} device The device
     * @param {Map[]} oldChannels The old channel properties
     * @param {Map[]} newChannels The new channel properties
     * @returns {Map} a map containing the modified `channels` and `zones`
     */
    var _computeModifiedChannels = function(device, oldChannels, newChannels) {
        // compute if channels were modified
        var modifiedChannels = {};
        var modifiedZones = {};

        _.each(oldChannels, function(c) {
            modifiedChannels[c.role] = null;
            // for easier access
            oldChannels[c.role] = c;
        });

        _.each(newChannels, function(c) {
            newChannels[c.role] = c;
            var oldChannel = oldChannels && oldChannels[c.role];

            if (oldChannel) {
                // check for zone modifications
                _.each(c.subChannels, function(sc) { // eslint-disable-line max-nested-callbacks
                    var oldSc = oldChannel.subChannels[sc.name];

                    if (oldSc) {
                        if (oldSc.lastModified !== sc.lastModified) {

                            // check if zone is assigned
                            _.each(device.zoneMapping, function(z, key) { // eslint-disable-line max-nested-callbacks
                                // @todo find better place for doing this
                                var channelPath = z.replace('${display.channel}', c.path);

                                if (sc.path === channelPath) { // subchannel is used in a zone
                                    modifiedZones[sc.path] = _.extend({
                                        zone: key
                                    }, sc);
                                }
                            });
                        }
                    }
                });

                if (!_.isEqual(c.offline || {}, oldChannel.offline || {})) {
                    modifiedChannels[c.role] = c;
                }

                // if online, compare the last modifieds
                if ((!c.offline || !c.offline.enabled) && oldChannel.lastModified !== c.lastModified) {
                    modifiedChannels[c.role] = c;
                }

                // No change was detected
                if (modifiedChannels[c.role] === null) {
                    delete modifiedChannels[c.role];
                }

                delete oldChannels[c.role];
            } else { // new channel
                modifiedChannels[c.role] = c;
            }
        });

        return {
            channels: modifiedChannels,
            zones: modifiedZones
        };
    };

    var handleChannelsModified = function(newChannelsObj, oldChannelsObj) { // jshint unused:false
        oldChannelsObj = oldChannelsObj || {};
        if (newChannelsObj[Config.PROPERTIES.CHANNELS.LIST] === oldChannelsObj[Config.PROPERTIES.CHANNELS.LIST]) {
            return;
        }
        var newChannels = newChannelsObj[Config.PROPERTIES.CHANNELS.LIST];
        var oldChannels = oldChannelsObj[Config.PROPERTIES.CHANNELS.LIST];
        if (!newChannels) {
            return;
        }

        var configSvc = ServiceAdmin.getService(Config.serviceName);
        var device = configSvc.getDevice();
        var modified = _computeModifiedChannels(device, oldChannels, newChannels);

        if (!_.isEmpty(modified.channels)) {
            var currentChannel = configSvc.getCurrentChannel();
            // replace our cached channels
            var currentRole = currentChannel && currentChannel.role;
            var myOldChannels = oldChannels;
            if (myOldChannels) {
                _.each(modified.channels, function(c) {
                    if (c) {
                        for (var i = 0; i < myOldChannels.length; i++) {
                            if (myOldChannels[i].role === c.role) {
                                if (c.deleted) {
                                    myOldChannels.splice(i, 1);
                                } else {
                                    myOldChannels[i] = c;
                                }
                            }
                            if (c.role === currentRole) {
                                currentChannel = c;
                                configSvc.setCurrentChannel(currentChannel);
                            }
                        }
                    }
                });
                this.start();
            }
        }

        if (!_.isEmpty(modified.zones)) {
            var zones = modified.zones;
            // TODO review loaders concept
            _.each(this.orchestrator.loaders, function(l) {
                if (zones[l.$frame.data('channelPath')]) {
                    console.log('reload zone:', zones[l.$frame.data('channelPath')].zone);
                    l.reload();
                }
            });
        }
    };

    var handleBridgeCommand = function(command, payload) {
        var commandHandlerService = ServiceAdmin.getService(CommandHandler.serviceName);
        commandHandlerService.handleCommand(command, payload);
    };

    var handleBridgeDown = function() {
        this._offline = true;
    };

    var handleBridgeUp = function() {
        this._offline = false;
    };

    var handleBridgeAuthenticated = function() {
        console.log('bridge-authenticated');

        var statusModelSvc = ServiceAdmin.getService(StatusModel.serviceName);
        var commandHandlerService = ServiceAdmin.getService(CommandHandler.serviceName);
        var statusInfoService = ServiceAdmin.getService(StatusInfo.serviceName);

        // Don't send the preferences and statusinfo for the webplayer
        if (statusModelSvc.get('devicePostUrl')) {
            commandHandlerService.handleCommand(Preferences.COMMANDS.SEND);
            statusInfoService.send();
        }
    };

    var handleBridgeRegistered = function(info) {
        console.log('bridge-registered', info);

        // todo: move to firmware
        var preferencesService = ServiceAdmin.getService(Preferences.serviceName);
        if (preferencesService) {
            preferencesService.save({
                device: info.deviceId,
                user: info.user,
                password: info.password
            });
        }

        // todo: should also be handled by firmware
        if (!window.cordova) {
            window.location.hash = info.deviceId;
        }
    };

    var handleBridgeUnregistered = function(info) {
        console.log('bridge-unregistered', info);

        // reset experience
        this.$iframe && this.$iframe.empty();

        // todo: should also be handled by firmware
        if (!window.cordova) {
            window.location.hash = '';
        }

        // @todo once the bridge is a service, move this to admin-service
        var admin = ServiceAdmin.getService(Admin.serviceName);
        if (admin) {
            admin.show('registration');
        }
    };

    /**
     * This callback is only triggered when the Channel loads the `screens-core`
     * Clientlib.
     * @param  {JSON} data Display or Channel related data
     * @param  {String} key A key that specifies the Window where the Channel was executed in.
     */
    var _wio_DisplayInitialized = function(data, key) {
        console.log('[Player] Received display-initialized', key);

        var store = ServiceAdmin.getService(Store.serviceName);
        var state = store.getState();
        this.wio.postMessage('display-data', {
            device: state.device,
            display: state.display,
            channels: state.channels._list
        }, key);
    };

    // called when display iframe is loaded
    var handleIFrameLoaded = function() {
        // init orchestrator for all channel frames
        console.log('[Player] Display iframe has been loaded.');
        var $channelIframes = this.$iframe.contents().find('.screens-Channel');
        console.log('[Player] Found ' + $channelIframes.length + ' channel frames.');

        if ($channelIframes.length === 0) {
            // if no channel frame, do nothing
            return;
        }

        // TODO move wio to a service
        if (!this.wio) {
            this.wio = new WindowIO();
        }

        // Disable AdminUI
        var adminService = ServiceAdmin.getService(Admin.serviceName);
        adminService.hide();

        // Initialize messaging for the video service
        var videoService = ServiceAdmin.getService(VideoService.serviceName);
        if (videoService) {
            videoService.initMessaging(this.wio);
        }

        // Listen only once, since the Display is only loaded once per iframe
        this.wio.once('display-initialized', _wio_DisplayInitialized.bind(this));

        // Make sure to properly clean the previous orhestrator if any exist
        var destroyPromise;
        if (this.orchestrator) {
            destroyPromise = this.orchestrator.destroy().then(function() {
                delete this.orchestrator;
            }.bind(this));
        }
        else {
            destroyPromise = Promise.resolve();
        }

        // If we have the display info, we can start a new orchestrator
        destroyPromise.then(function() {
            this.orchestrator = new Orchestrator({
                player: this,
                $frames: $channelIframes
            });
        }.bind(this));
    };

    /**
     * Screens Player.
     *
     * @class Player
     *
     * @param {Player.PlayerOptions} [options]    Options for the component.
     */
    var Player = function(options) {
        this.options = _.assign({}, DEFAULTS, options);
        this.datastore = new DataStore();

        var storeSvc = ServiceAdmin.getService(Store.serviceName);
        var statusModelSvc = ServiceAdmin.getService(StatusModel.serviceName);
        var preferences = storeSvc.getState()[Preferences.NAMESPACE];

        // setup bridge
        var self = this;
        this.bridge = new Bridge({
            pollingInterval: self.options.pollingInterval,
            requestTimeout: self.options.requestTimeout,
            serverURL: preferences.server,
            deviceId: statusModelSvc.get('deviceId'),
            user: preferences.user,
            password: preferences.password,
            datastore: this.datastore
        });

        this.bridge.on(Bridge.events.LINK_UP, handleBridgeUp.bind(this));
        this.bridge.on(Bridge.events.LINK_DOWN, handleBridgeDown.bind(this));
        this.bridge.on(Bridge.events.REGISTERED, handleBridgeRegistered.bind(this));
        this.bridge.on(Bridge.events.UNREGISTERED, handleBridgeUnregistered.bind(this));
        this.bridge.on(Bridge.events.AUTHENTICATED, handleBridgeAuthenticated.bind(this));
        this.bridge.on(Bridge.events.COMMAND, handleBridgeCommand.bind(this));

        // init overlay and osd
        this.overlay = new Overlay();
        this.osd = new OSD({
            longPressDuration: this.options.longPressDuration,
            overlay: this.overlay,
            player: this,
            enableHiddenTrigger: typeof preferences.enableOSD === 'undefined' ? true : preferences.enableOSD
        });

        this.activity = new Activity();

        this.connectivity = new Connectivity({
            overlay: this.overlay,
            bridge: this.bridge
        });

        // init csrf support
        this.csrf = new CSRFSupport({
            serverURL: preferences.server
        });

        // start the command bridge
        self.bridge.start();
        self.bridge.setPingPayload({
            v: statusModelSvc.get('version'),
            t: statusModelSvc.get('timestamp')
        });

        // only start player after the bridge did the initial handshake
        this.bridge.on(Bridge.events.HANDSHAKE_COMPLETED, function() {
            self.start();
        });

        self._onPreferencesChangeListener = storeSvc.subscribe(this._onPreferencesChange.bind(this), Preferences.NAMESPACE);
        self._onPreferencesChange(preferences);
    };

    Player.prototype = _.create(EventEmitter.prototype, _.assign({
        _super: EventEmitter.prototype,
        constructor: Player
    }, /** @lends Orchestrator.prototype */ {

        /* The player events. */
        EVENTS: EVENTS,

        /**
         * Reload the Player.
         * @memberof Player
         */
        reload: function() {
            window.location.reload(true);
        },

        /**
         * Destroy the Player.
         * @memberof Player
         */
        destroy: function() {

            var store = ServiceAdmin.getService(Store.serviceName);
            if (store) {
                store.unsubscribe(this._onPreferencesChangeListener);
            }

            if (this.connectivity) {
                this.connectivity.destroy();
                this.connectivity = null;
            }

            if (this.overlay) {
                this.overlay.destroy();
                this.overlay = null;
            }

            if (this._displayConfigChangeListener) {
                store.unsubscribe(this._displayConfigChangeListener);
                this._displayConfigChangeListener = null;
            }
            if (this._deviceConfigChangeListener) {
                store.unsubscribe(this._deviceConfigChangeListener);
                this._deviceConfigChangeListener = null;
            }
            if (this._channelsConfigChangeListener) {
                store.unsubscribe(this._channelsConfigChangeListener);
                this._channelsConfigChangeListener = null;
            }

            if (this.redownloadTiemout) {
                window.clearTimeout(this.redownloadTiemout);
            }
        },

        init: function() {
            if (!this._initialized) {
                this._initialized = true;

                var store = ServiceAdmin.getService(Store.serviceName);
                this._displayConfigChangeListener = store.subscribe(handleDisplayModified.bind(this), Config.NAMESPACES.DISPLAY);
                this._deviceConfigChangeListener = store.subscribe(handleDeviceModified.bind(this), Config.NAMESPACES.DEVICE);
                this._channelsConfigChangeListener = store.subscribe(handleChannelsModified.bind(this), Config.NAMESPACES.CHANNELS);

                // Handle to the channel container div
                this.$iframe = $('.channel-container');
            }
        },

        /*
         * start() is the single point of responsibility for
         * 1) preparing the Channels (including downloading offline channels)
         * 2) setting the Display iFrame
         * on config-updates (Display, Device-Config, Channels) triggered via
         * command handler or bridge handshake.
         *
         * `start()` is following 2 strategies in order to prevent multiple
         * asynchronous calls that could lead to a corrupt file-system
         * due to wrong device infos, multiple downloads of offline channels
         * due to multiple simultaneously running config-updates and
         * black screens during config-updates.
         *
         * 1. Strategy:
         * debounce calls that appear in a very short time. This solves the problem
         * where `start()` accesses outdated state.
         *
         * 2. Strategy:
         * calls being done while `start()` is still operating are deferred and
         * executed immediately afterwards. This solves the problem of not
         * interrupting long-running config-updates.
         *
         * TODO: Move logic into ConfigService and introduce an async thunk action.
         */
        start: _.debounce(function() {
            this.init();

            console.log('[Player] Start config-update.');

            if (this._isStarting) {
                // 2. Strategy: Do not interrupt long-running config-updates.
                console.log('[Player] Received config-update request during a long running config-update.');
                this._deferredStartCall = true;
                return;
            }
            this._isStarting = true;

            var prefsSvc = ServiceAdmin.getService(Preferences.serviceName);
            var configSvc = ServiceAdmin.getService(Config.serviceName);
            var display = configSvc.getDisplay();
            var device = configSvc.getDevice();
            var channels = configSvc.getChannels();

            var self = this;

            var statusModelSvc = ServiceAdmin.getService(StatusModel.serviceName);
            if (device.path) {
                statusModelSvc.set('devicePath', device.path);
            }
            if (!prefsSvc.getPreferences().device) {
                console.log('[Player] Config-update interrupted due to missing Device-Infos.');
                this._deferredStartCall = false;
                this._isStarting = false;
                return;
            }
            else if (_.isEmpty(display)) {
                console.log('[Player] Config-update interrupted due to missing Display-Infos.');
                this._deferredStartCall = false;
                this._isStarting = false;
                this.stop();
                return;
            }

            statusModelSvc.set('displayPath', display.path);

            // on ipad, setting the iframe src several times in a row does not work as expected:
            // it only considers the first time, aka might be the wrong url after a set of changes.
            var loadDisplay = function() {
                return new Promise(function(resolve) {
                    var d = configSvc.getDevice();
                    var url = getDisplayURL(d);
                    console.log('[Player] Loading display', url);
                    self.$iframe.load(url, handleIFrameLoaded.bind(self));
                    resolve();
                });
            };

            prepareChannels.call(this, channels)
                .then(loadDisplay)
                .catch(function(e) {
                    console.error('[Player] Error while loading channels: ' + e);
                })
                .then(function() {
                    self._isStarting = false;
                    console.log('[Player] Config-update completed.');
                    if (self._deferredStartCall) {
                        self._deferredStartCall = false;
                        console.log('[Player] Re-starting again due to a deferred config-update request.');
                        self.start();
                    }
                });

        }, 1000),

        stop: function() {
            var statusModelSvc = ServiceAdmin.getService(StatusModel.serviceName);
            statusModelSvc.set('displayPath', '');
            this.$iframe && this.$iframe.empty();

            if (this.redownloadTiemout) {
                window.clearTimeout(this.redownloadTiemout);
            }
        },

        _onPackageManagerStarted: function(evt) {
            console.log('[Player] Syncing ' + evt.title + ' sourced from ' + evt.url);
            var msg = 'Syncing ' + evt.title;
            this.activity.show();
            this.activity.add(evt.title, msg);
        },

        _onPackageManagerProgress: function(evt) {
            var msg = '<b>' + evt.progress + '%</b> - (' + PACKAGE_MANAGER_SYNC_STATUS[evt.status] + ') ' + evt.title;
            this.activity.add(evt.title, msg);
        },

        _onPackageManagerCompleted: function(payload) {
            var msg = 'Synced ' + payload.title;
            this.activity.add(payload.title, msg).remove(2000);
        },

        _onPackageManagerError: function(payload) {
            var msg = 'Error ' + payload.error.type + ' syncing ' + payload.title + ' sourced from ' + payload.url;
            this.activity.add(payload.title, msg).remove(5000);
        },

        _onPreferencesChange: function(preferences, oldPreferences) {
            var packageManager = ServiceAdmin.getService(PackageManager.serviceName);

            if (!oldPreferences || preferences.enableActivityUI !== oldPreferences.enableActivityUI) {

                // TODO move ActivityUI logic into SPI because it's platform dependent.
                if (preferences.enableActivityUI) {
                    this.activity.show();
                } else {
                    this.activity.hide();
                }

                if (!packageManager) {
                    return;
                }

                if (preferences.enableActivityUI) {
                    packageManager.on(PackageManager.EVENTS.SYNC_STARTED, this._onPackageManagerStarted, this);
                    packageManager.on(PackageManager.EVENTS.SYNC_PROGRESS, this._onPackageManagerProgress, this);
                } else {
                    packageManager.off(PackageManager.EVENTS.SYNC_STARTED, this._onPackageManagerStarted, this);
                    packageManager.off(PackageManager.EVENTS.SYNC_PROGRESS, this._onPackageManagerProgress, this);
                }
            }
        }

    }));

    return Player;

});