<commit_before>/**
 * @fileOverview Requirejs module containing device modifier to launch native external media players
 *
 * @preserve Copyright (c) 2014 British Broadcasting Corporation
 * (http://www.bbc.co.uk) and TAL Contributors (1)
 *
 * (1) TAL Contributors are listed in the AUTHORS file and at
 *     https://github.com/fmtvp/TAL/AUTHORS - please extend this file,
 *     not this notice.
 *
 * @license Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * All rights reserved
 * Please contact us for an alternative licence
 */

require.def(
    "antie/devices/mediaplayer/html5",
    [
        "antie/runtimecontext",
        "antie/devices/device",
        "antie/devices/mediaplayer/mediaplayer"
    ],
    function(RuntimeContext, Device, MediaPlayer) {
        "use strict";

        var Player = MediaPlayer.extend({

            init: function() {
                this._super();
                this._state = MediaPlayer.STATE.EMPTY;
                this._wipe();
            },

            /**
            * @inheritDoc
            */
            setSource: function (mediaType, url, mimeType) {
                if (this.getState() === MediaPlayer.STATE.EMPTY) {
                    this._type = mediaType;
                    this._source = url;
                    this._mimeType = mimeType;
                    var device = RuntimeContext.getDevice();

                    var idSuffix = mediaType === MediaPlayer.TYPE.AUDIO ? "Audio" : "Video";

                    this._mediaElement = device._createElement(this._type, "mediaPlayer" + idSuffix);
                    this._mediaElement.autoplay = false;
                    this._mediaElement.style.position = "absolute";
                    this._mediaElement.style.top = "0px";
                    this._mediaElement.style.left = "0px";
                    this._mediaElement.style.width = "100%";
                    this._mediaElement.style.height = "100%";

                    var self = this;
                    this._wrapOnFinishedBuffering = function (event) { self._onFinishedBuffering(event); };
                    this._wrapOnMediaError = function (event) { self._onMediaError(event); };
                    this._wrapOnEndOfMedia = function (event) { self._onEndOfMedia(event); };
                    this._wrapOnDeviceBuffering = function (event) { self._onDeviceBuffering(event); };
                    this._wrapOnStatus = function (event) { self._onStatus(event); };
                    this._wrapOnMetadata = function (event) { self._onMetadata(event); };
                    this._wrapOnPlaying = function (event) { self._onPlaying(event); };
                    this._mediaElement.addEventListener("canplaythrough", this._wrapOnFinishedBuffering);
                    this._mediaElement.addEventListener("error", this._wrapOnMediaError);
                    this._mediaElement.addEventListener("ended", this._wrapOnEndOfMedia);
                    this._mediaElement.addEventListener("waiting", this._wrapOnDeviceBuffering);
                    this._mediaElement.addEventListener("timeupdate", this._wrapOnStatus);
                    this._mediaElement.addEventListener("loadedmetadata", this._wrapOnMetadata);
                    this._mediaElement.addEventListener("playing", this._wrapOnPlaying);

                    var body = document.getElementsByTagName("body")[0];
                    device.prependChildElement(body, this._mediaElement);

                    var source = device._createElement("source");
                    source.src = url;
                    source.type = mimeType;
                    source.addEventListener("error", function (event) { self._onSourceError(event); });
                    device.appendChildElement(this._mediaElement, source);

                    this._mediaElement.preload = "auto";
                    this._mediaElement.load();

                    this._toStopped();
                } else {
                    this._toError("Cannot set source unless in the '" + MediaPlayer.STATE.EMPTY + "' state");
                }
            },

            /**
            * @inheritDoc
            */
            playFrom: function (time) {
                this._postBufferingState = MediaPlayer.STATE.PLAYING;
                this._targetSeekTime = time;
                switch (this.getState()) {
                    case MediaPlayer.STATE.STOPPED:
                    case MediaPlayer.STATE.PAUSED:
                        this._toBuffering();
                        this._playFromIfReady();
                        break;

                    case MediaPlayer.STATE.BUFFERING:
                        this._playFromIfReady();
                        break;

                    case MediaPlayer.STATE.PLAYING:
                        this._toBuffering();
                        if (this._tryingToSeekToCurrentTime(time)) {
                            this._toPlaying();
                        } else {
                            this._playFromIfReady();
                        }
                        break;

                    case MediaPlayer.STATE.COMPLETE:
                        this._toBuffering();
                        if (this._tryingToSeekToCurrentTime(time)) {
                            this._toComplete();
                        } else {
                            this._playFromIfReady();
                        }
                        break;

                    default:
                        this._toError("Cannot playFrom while in the '" + this.getState() + "' state");
                        break;
                }
            },

            /**
            * @inheritDoc
            */
            pause: function () {
                this._postBufferingState = MediaPlayer.STATE.PAUSED;
                switch (this.getState()) {
                    case MediaPlayer.STATE.PAUSED:
                        break;

                    case MediaPlayer.STATE.BUFFERING:
                        if (!this._notReadyToPlay()) {
                            this._mediaElement.pause();
                        }
                        break;

                    case MediaPlayer.STATE.PLAYING:
                        this._mediaElement.pause();
                        this._toPaused();
                        break;

                    default:
                        this._toError("Cannot pause while in the '" + this.getState() + "' state");
                        break;
                }
            },

            /**
            * @inheritDoc
            */
            resume : function () {
                this._postBufferingState = MediaPlayer.STATE.PLAYING;
                switch (this.getState()) {
                    case MediaPlayer.STATE.PLAYING:
                    case MediaPlayer.STATE.BUFFERING:
                        break;

                    case MediaPlayer.STATE.PAUSED:
                        this._mediaElement.play();
                        this._toPlaying();
                        break;

                    default:
                        this._toError("Cannot resume while in the '" + this.getState() + "' state");
                        break;
                }
            },

            /**
            * @inheritDoc
            */
            stop: function () {
                switch (this.getState()) {
                    case MediaPlayer.STATE.BUFFERING:
                    case MediaPlayer.STATE.PLAYING:
                    case MediaPlayer.STATE.PAUSED:
                    case MediaPlayer.STATE.COMPLETE:
                        this._mediaElement.pause();
                        this._toStopped();
                        break;

                    default:
                        this._toError("Cannot stop while in the '" + this.getState() + "' state");
                        break;
                }
            },

            /**
            * @inheritDoc
            */
            reset: function () {
                switch (this.getState()) {
                    case MediaPlayer.STATE.STOPPED:
                    case MediaPlayer.STATE.ERROR:
                        this._toEmpty();
                        break;

                    default:
                        this._toError("Cannot reset while in the '" + this.getState() + "' state");
                        break;
                }
            },

            /**
            * @inheritDoc
            */
            getSource: function () {
                return this._source;
            },

            /**
            * @inheritDoc
            */
            getMimeType: function () {
                return this._mimeType;
            },

            /**
            * @inheritDoc
            */
            getCurrentTime: function () {
                switch (this.getState()) {
                    case MediaPlayer.STATE.STOPPED:
                    case MediaPlayer.STATE.ERROR:
                        break;

                    default:
                        if (this._mediaElement) {
                            return this._mediaElement.currentTime;
                        }
                        break;
                }
                return undefined;
            },

            /**
            * @inheritDoc
            */
            getRange: function () {
                switch (this.getState()) {
                    case MediaPlayer.STATE.STOPPED:
                    case MediaPlayer.STATE.ERROR:
                        break;

                    default:
                        return this._getSeekableRange();
                }
                return undefined;
            },

            _getSeekableRange: function () {
                if (this._mediaElement) {
                    var seekable = this._mediaElement.seekable;
                    var logger = RuntimeContext.getDevice().getLogger();

                    if (!seekable) {
                        logger.warn("'seekable' property missing from media element");

                    } else if (seekable.length === 1) {
                        return {
                            start: seekable.start(0),
                            end: seekable.end(0)
                        };

                    } else if (seekable.length > 1) {
                        logger.warn("Multiple seekable ranges detected");
                    }
                }
                return undefined;
            },

            /**
            * @inheritDoc
            */
            getState: function () {
                return this._state;
            },

            _onFinishedBuffering: function() {
                if (this.getState() !== MediaPlayer.STATE.BUFFERING) {
                    return;

                } else if (this._postBufferingState === MediaPlayer.STATE.PAUSED) {
                    this._toPaused();

                } else {
                    this._toPlaying();
                }
            },

            _onMediaError: function(evt) {
                this._toError("Media element emitted error with code: " + this._mediaElement.error.code);
            },

            _onSourceError: function(evt) {
                this._toError("Source element emitted error");
            },

            _onDeviceBuffering: function() {
                this._toBuffering();
            },

            _onEndOfMedia: function() {
                this._toComplete();
            },

            _onStatus: function() {
                if (this.getState() === MediaPlayer.STATE.PLAYING) {
                    this._emitEvent(MediaPlayer.EVENT.STATUS);
                }
            },

            _onMetadata: function() {
                this._deferSeeks = false;
                this._deferredPlayFrom();
            },

            _onPlaying: function() {
                this._toPlaying();
            },

            _playFromIfReady: function () {
                if (!this._notReadyToPlay()) {
                    this._deferredPlayFrom();
                }
            },

            _deferredPlayFrom: function () {
                if (this._targetSeekTime !== undefined) { // FIXME: should there be "_notReadyToPlay() && " on the front of this?
                    this._seekTo(this._targetSeekTime);
                    this._playIfNotAtEndOfMedia();
                    if (this._postBufferingState === MediaPlayer.STATE.PAUSED) {
                        this._mediaElement.pause();
                    }
                }
                this._targetSeekTime = undefined;
            },

            _notReadyToPlay: function () {
                return this._deferSeeks;
            },

            _tryingToSeekToCurrentTime: function (time) {
                return this._mediaElement.currentTime === this._getClampedTime(time);
            },

            _seekTo: function(time) {
                this._mediaElement.currentTime = this._getClampedTime(time);
            },

            _playIfNotAtEndOfMedia: function() {
                if (!this._isAtEndOfMedia()) {
                    // FIXME: comment here explaining why...
                    this._mediaElement.play();
                }
            },

            _isAtEndOfMedia: function () {
                var range = this.getRange();
                return this._mediaElement.currentTime === range.end;
            },

            _wipe: function () {
                this._type = undefined;
                this._source = undefined;
                this._mimeType = undefined;
                this._targetSeekTime = undefined;
                this._destroyMediaElement();
                this._deferSeeks = true;
            },

            _destroyMediaElement: function () {
                if (this._mediaElement) {
                    this._mediaElement.removeEventListener("canplaythrough", this._wrapOnFinishedBuffering);
                    this._mediaElement.removeEventListener("error", this._wrapOnMediaError);
                    this._mediaElement.removeEventListener("ended", this._wrapOnEndOfMedia);
                    this._mediaElement.removeEventListener("waiting", this._wrapOnDeviceBuffering);
                    this._mediaElement.removeEventListener("timeupdate", this._wrapOnStatus);
                    this._mediaElement.removeEventListener("loadedmetadata", this._wrapOnMetadata);

                    var device = RuntimeContext.getDevice();
                    device.removeElement(this._mediaElement);

                    delete this._mediaElement;
                }
            },

            _toStopped: function () {
                this._state = MediaPlayer.STATE.STOPPED;
                this._emitEvent(MediaPlayer.EVENT.STOPPED);
            },

            _toBuffering: function () {
                this._state = MediaPlayer.STATE.BUFFERING;
                this._emitEvent(MediaPlayer.EVENT.BUFFERING);
            },

            _toPlaying: function () {
                this._state = MediaPlayer.STATE.PLAYING;
                this._emitEvent(MediaPlayer.EVENT.PLAYING);
            },

            _toPaused: function () {
                this._state = MediaPlayer.STATE.PAUSED;
                this._emitEvent(MediaPlayer.EVENT.PAUSED);
            },

            _toComplete: function () {
                this._state = MediaPlayer.STATE.COMPLETE;
                this._emitEvent(MediaPlayer.EVENT.COMPLETE);
            },

            _toEmpty: function () {
                this._wipe();
                this._state = MediaPlayer.STATE.EMPTY;
            },

            _toError: function (errorMessage) {
                RuntimeContext.getDevice().getLogger().error(errorMessage);
                this._wipe();
                this._state = MediaPlayer.STATE.ERROR;
                this._emitEvent(MediaPlayer.EVENT.ERROR);
            }
        });

        var instance = new Player();

        // Mixin this MediaPlayer implementation, so that device.getMediaPlayer() returns the correct implementation for the device
        Device.prototype.getMediaPlayer = function() {
            return instance;
        };

        return Player;
    }

);
<commit_msg>Rename _readyToPlayFrom<commit_after>/**
 * @fileOverview Requirejs module containing device modifier to launch native external media players
 *
 * @preserve Copyright (c) 2014 British Broadcasting Corporation
 * (http://www.bbc.co.uk) and TAL Contributors (1)
 *
 * (1) TAL Contributors are listed in the AUTHORS file and at
 *     https://github.com/fmtvp/TAL/AUTHORS - please extend this file,
 *     not this notice.
 *
 * @license Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * All rights reserved
 * Please contact us for an alternative licence
 */

require.def(
    "antie/devices/mediaplayer/html5",
    [
        "antie/runtimecontext",
        "antie/devices/device",
        "antie/devices/mediaplayer/mediaplayer"
    ],
    function(RuntimeContext, Device, MediaPlayer) {
        "use strict";

        var Player = MediaPlayer.extend({

            init: function() {
                this._super();
                this._state = MediaPlayer.STATE.EMPTY;
                this._wipe();
            },

            /**
            * @inheritDoc
            */
            setSource: function (mediaType, url, mimeType) {
                if (this.getState() === MediaPlayer.STATE.EMPTY) {
                    this._type = mediaType;
                    this._source = url;
                    this._mimeType = mimeType;
                    var device = RuntimeContext.getDevice();

                    var idSuffix = mediaType === MediaPlayer.TYPE.AUDIO ? "Audio" : "Video";

                    this._mediaElement = device._createElement(this._type, "mediaPlayer" + idSuffix);
                    this._mediaElement.autoplay = false;
                    this._mediaElement.style.position = "absolute";
                    this._mediaElement.style.top = "0px";
                    this._mediaElement.style.left = "0px";
                    this._mediaElement.style.width = "100%";
                    this._mediaElement.style.height = "100%";

                    var self = this;
                    this._wrapOnFinishedBuffering = function (event) { self._onFinishedBuffering(event); };
                    this._wrapOnMediaError = function (event) { self._onMediaError(event); };
                    this._wrapOnEndOfMedia = function (event) { self._onEndOfMedia(event); };
                    this._wrapOnDeviceBuffering = function (event) { self._onDeviceBuffering(event); };
                    this._wrapOnStatus = function (event) { self._onStatus(event); };
                    this._wrapOnMetadata = function (event) { self._onMetadata(event); };
                    this._wrapOnPlaying = function (event) { self._onPlaying(event); };
                    this._mediaElement.addEventListener("canplaythrough", this._wrapOnFinishedBuffering);
                    this._mediaElement.addEventListener("error", this._wrapOnMediaError);
                    this._mediaElement.addEventListener("ended", this._wrapOnEndOfMedia);
                    this._mediaElement.addEventListener("waiting", this._wrapOnDeviceBuffering);
                    this._mediaElement.addEventListener("timeupdate", this._wrapOnStatus);
                    this._mediaElement.addEventListener("loadedmetadata", this._wrapOnMetadata);
                    this._mediaElement.addEventListener("playing", this._wrapOnPlaying);

                    var body = document.getElementsByTagName("body")[0];
                    device.prependChildElement(body, this._mediaElement);

                    var source = device._createElement("source");
                    source.src = url;
                    source.type = mimeType;
                    source.addEventListener("error", function (event) { self._onSourceError(event); });
                    device.appendChildElement(this._mediaElement, source);

                    this._mediaElement.preload = "auto";
                    this._mediaElement.load();

                    this._toStopped();
                } else {
                    this._toError("Cannot set source unless in the '" + MediaPlayer.STATE.EMPTY + "' state");
                }
            },

            /**
            * @inheritDoc
            */
            playFrom: function (time) {
                this._postBufferingState = MediaPlayer.STATE.PLAYING;
                this._targetSeekTime = time;
                switch (this.getState()) {
                    case MediaPlayer.STATE.STOPPED:
                    case MediaPlayer.STATE.PAUSED:
                        this._toBuffering();
                        this._playFromIfReady();
                        break;

                    case MediaPlayer.STATE.BUFFERING:
                        this._playFromIfReady();
                        break;

                    case MediaPlayer.STATE.PLAYING:
                        this._toBuffering();
                        if (this._tryingToSeekToCurrentTime(time)) {
                            this._toPlaying();
                        } else {
                            this._playFromIfReady();
                        }
                        break;

                    case MediaPlayer.STATE.COMPLETE:
                        this._toBuffering();
                        if (this._tryingToSeekToCurrentTime(time)) {
                            this._toComplete();
                        } else {
                            this._playFromIfReady();
                        }
                        break;

                    default:
                        this._toError("Cannot playFrom while in the '" + this.getState() + "' state");
                        break;
                }
            },

            /**
            * @inheritDoc
            */
            pause: function () {
                this._postBufferingState = MediaPlayer.STATE.PAUSED;
                switch (this.getState()) {
                    case MediaPlayer.STATE.PAUSED:
                        break;

                    case MediaPlayer.STATE.BUFFERING:
                        if (this._readyToPlayFrom()) {
                            this._mediaElement.pause();
                        }
                        break;

                    case MediaPlayer.STATE.PLAYING:
                        this._mediaElement.pause();
                        this._toPaused();
                        break;

                    default:
                        this._toError("Cannot pause while in the '" + this.getState() + "' state");
                        break;
                }
            },

            /**
            * @inheritDoc
            */
            resume : function () {
                this._postBufferingState = MediaPlayer.STATE.PLAYING;
                switch (this.getState()) {
                    case MediaPlayer.STATE.PLAYING:
                    case MediaPlayer.STATE.BUFFERING:
                        break;

                    case MediaPlayer.STATE.PAUSED:
                        this._mediaElement.play();
                        this._toPlaying();
                        break;

                    default:
                        this._toError("Cannot resume while in the '" + this.getState() + "' state");
                        break;
                }
            },

            /**
            * @inheritDoc
            */
            stop: function () {
                switch (this.getState()) {
                    case MediaPlayer.STATE.BUFFERING:
                    case MediaPlayer.STATE.PLAYING:
                    case MediaPlayer.STATE.PAUSED:
                    case MediaPlayer.STATE.COMPLETE:
                        this._mediaElement.pause();
                        this._toStopped();
                        break;

                    default:
                        this._toError("Cannot stop while in the '" + this.getState() + "' state");
                        break;
                }
            },

            /**
            * @inheritDoc
            */
            reset: function () {
                switch (this.getState()) {
                    case MediaPlayer.STATE.STOPPED:
                    case MediaPlayer.STATE.ERROR:
                        this._toEmpty();
                        break;

                    default:
                        this._toError("Cannot reset while in the '" + this.getState() + "' state");
                        break;
                }
            },

            /**
            * @inheritDoc
            */
            getSource: function () {
                return this._source;
            },

            /**
            * @inheritDoc
            */
            getMimeType: function () {
                return this._mimeType;
            },

            /**
            * @inheritDoc
            */
            getCurrentTime: function () {
                switch (this.getState()) {
                    case MediaPlayer.STATE.STOPPED:
                    case MediaPlayer.STATE.ERROR:
                        break;

                    default:
                        if (this._mediaElement) {
                            return this._mediaElement.currentTime;
                        }
                        break;
                }
                return undefined;
            },

            /**
            * @inheritDoc
            */
            getRange: function () {
                switch (this.getState()) {
                    case MediaPlayer.STATE.STOPPED:
                    case MediaPlayer.STATE.ERROR:
                        break;

                    default:
                        return this._getSeekableRange();
                }
                return undefined;
            },

            _getSeekableRange: function () {
                if (this._mediaElement) {
                    var seekable = this._mediaElement.seekable;
                    var logger = RuntimeContext.getDevice().getLogger();

                    if (!seekable) {
                        logger.warn("'seekable' property missing from media element");

                    } else if (seekable.length === 1) {
                        return {
                            start: seekable.start(0),
                            end: seekable.end(0)
                        };

                    } else if (seekable.length > 1) {
                        logger.warn("Multiple seekable ranges detected");
                    }
                }
                return undefined;
            },

            /**
            * @inheritDoc
            */
            getState: function () {
                return this._state;
            },

            _onFinishedBuffering: function() {
                if (this.getState() !== MediaPlayer.STATE.BUFFERING) {
                    return;

                } else if (this._postBufferingState === MediaPlayer.STATE.PAUSED) {
                    this._toPaused();

                } else {
                    this._toPlaying();
                }
            },

            _onMediaError: function(evt) {
                this._toError("Media element emitted error with code: " + this._mediaElement.error.code);
            },

            _onSourceError: function(evt) {
                this._toError("Source element emitted error");
            },

            _onDeviceBuffering: function() {
                this._toBuffering();
            },

            _onEndOfMedia: function() {
                this._toComplete();
            },

            _onStatus: function() {
                if (this.getState() === MediaPlayer.STATE.PLAYING) {
                    this._emitEvent(MediaPlayer.EVENT.STATUS);
                }
            },

            _onMetadata: function() {
                this._deferSeeks = false;
                this._deferredPlayFrom();
            },

            _onPlaying: function() {
                this._toPlaying();
            },

            _playFromIfReady: function () {
                if (this._readyToPlayFrom()) {
                    this._deferredPlayFrom();
                }
            },

            _deferredPlayFrom: function () {
                if (this._targetSeekTime !== undefined) { // FIXME: should there be "_readyToPlayFrom() && " on the front of this?
                    this._seekTo(this._targetSeekTime);
                    this._playIfNotAtEndOfMedia();
                    if (this._postBufferingState === MediaPlayer.STATE.PAUSED) {
                        this._mediaElement.pause();
                    }
                }
                this._targetSeekTime = undefined;
            },

            _readyToPlayFrom: function () {
                return !this._deferSeeks;
            },

            _tryingToSeekToCurrentTime: function (time) {
                return this._mediaElement.currentTime === this._getClampedTime(time);
            },

            _seekTo: function(time) {
                this._mediaElement.currentTime = this._getClampedTime(time);
            },

            _playIfNotAtEndOfMedia: function() {
                if (!this._isAtEndOfMedia()) {
                    // FIXME: comment here explaining why...
                    this._mediaElement.play();
                }
            },

            _isAtEndOfMedia: function () {
                var range = this.getRange();
                return this._mediaElement.currentTime === range.end;
            },

            _wipe: function () {
                this._type = undefined;
                this._source = undefined;
                this._mimeType = undefined;
                this._targetSeekTime = undefined;
                this._destroyMediaElement();
                this._deferSeeks = true;
            },

            _destroyMediaElement: function () {
                if (this._mediaElement) {
                    this._mediaElement.removeEventListener("canplaythrough", this._wrapOnFinishedBuffering);
                    this._mediaElement.removeEventListener("error", this._wrapOnMediaError);
                    this._mediaElement.removeEventListener("ended", this._wrapOnEndOfMedia);
                    this._mediaElement.removeEventListener("waiting", this._wrapOnDeviceBuffering);
                    this._mediaElement.removeEventListener("timeupdate", this._wrapOnStatus);
                    this._mediaElement.removeEventListener("loadedmetadata", this._wrapOnMetadata);

                    var device = RuntimeContext.getDevice();
                    device.removeElement(this._mediaElement);

                    delete this._mediaElement;
                }
            },

            _toStopped: function () {
                this._state = MediaPlayer.STATE.STOPPED;
                this._emitEvent(MediaPlayer.EVENT.STOPPED);
            },

            _toBuffering: function () {
                this._state = MediaPlayer.STATE.BUFFERING;
                this._emitEvent(MediaPlayer.EVENT.BUFFERING);
            },

            _toPlaying: function () {
                this._state = MediaPlayer.STATE.PLAYING;
                this._emitEvent(MediaPlayer.EVENT.PLAYING);
            },

            _toPaused: function () {
                this._state = MediaPlayer.STATE.PAUSED;
                this._emitEvent(MediaPlayer.EVENT.PAUSED);
            },

            _toComplete: function () {
                this._state = MediaPlayer.STATE.COMPLETE;
                this._emitEvent(MediaPlayer.EVENT.COMPLETE);
            },

            _toEmpty: function () {
                this._wipe();
                this._state = MediaPlayer.STATE.EMPTY;
            },

            _toError: function (errorMessage) {
                RuntimeContext.getDevice().getLogger().error(errorMessage);
                this._wipe();
                this._state = MediaPlayer.STATE.ERROR;
                this._emitEvent(MediaPlayer.EVENT.ERROR);
            }
        });

        var instance = new Player();

        // Mixin this MediaPlayer implementation, so that device.getMediaPlayer() returns the correct implementation for the device
        Device.prototype.getMediaPlayer = function() {
            return instance;
        };

        return Player;
    }

);
<|endoftext|>


<commit_before>'use strict';

window.FileBehaviors = window.FileBehaviors || {};
/** @polymerBehavior */
FileBehaviors.FilesystemAppBehaviorImpl = {
  properties: {
    /**
     * The optional list of accept options for file opener. Each option will be presented as a
     * unique group to the end-user.
     * Each group definition can be defines as an object with following properties:
     * description {string} This is the optional text description for this option.
     * mimeTypes {Array<String>} Mime-types to accept, e.g. "image/jpeg" or "audio/*". One of
     *  mimeTypes or extensions must contain at least one valid element.
     * extensions {Array<String>} Extensions to accept, e.g. "jpg", "gif", "crx".
     */
    accepts: {
      type: Array
    },
    /**
     * Whether to accept multiple files. This is only supported for openFile and openWritableFile.
     */
    acceptsMultiple: Boolean,
  },
  /**
   * Read the file. Chrome API will be used to open a file.
   */
  read: function() {
    this._chooseEntry()
      .then(this._getContent)
      .then(this._prepareContent)
      .then(function() {
        this.fire('file-read');
      }.bind(this))
      .catch(function(cause) {
        this.fire('error', {
          'cause': 'read',
          'message': cause.message
        });
      }.bind(this));
  },
  write: function() {
    this._chooseEntry({
        type: 'saveFile'
      })
      .catch(function(cause) {
        // The only error here is that the user press cancel.
        // In this case just do nothing.
      }.bind(this))
      .then(this._truncate.bind(this))
      .then(this._writeFileEntry.bind(this))
      .then(function() {
        this.fire('file-save');
      }.bind(this))
      .catch(function(cause) {
        this.fire('error', {
          'cause': 'save',
          'message': cause.message
        });
      }.bind(this));
  },
  /**
   * Open the file using file picker and Chrome api.
   * By default this will open a file in read only mode.
   */
  _chooseEntry: function(opts) {
    opts = opts || {};
    if (this.fileName) {
      opts.suggestedName = this.fileName;
    }
    if (this.accepts) {
      opts.accepts = this.accepts;
    }
    if (typeof this.acceptsMultiple !== 'undefined') {
      opts.acceptsMultiple = this.acceptsMultiple;
    }
    return new Promise(function(resolve, reject) {
      chrome.fileSystem.chooseEntry(opts, function(entry) {
        if (chrome.runtime.lastError) {
          reject(chrome.runtime.lastError);
          return;
        }
        resolve(entry);
      }.bind(this));
    }.bind(this));
  }
};

FileBehaviors.FilesystemAppBehavior = [
  FileBehaviors.FilesystemBehavior,
  FileBehaviors.FilesystemAppBehaviorImpl
];
<commit_msg>Fixing scope problems<commit_after>'use strict';

window.FileBehaviors = window.FileBehaviors || {};
/** @polymerBehavior */
FileBehaviors.FilesystemAppBehaviorImpl = {
  properties: {
    /**
     * The optional list of accept options for file opener. Each option will be presented as a
     * unique group to the end-user.
     * Each group definition can be defines as an object with following properties:
     * description {string} This is the optional text description for this option.
     * mimeTypes {Array<String>} Mime-types to accept, e.g. "image/jpeg" or "audio/*". One of
     *  mimeTypes or extensions must contain at least one valid element.
     * extensions {Array<String>} Extensions to accept, e.g. "jpg", "gif", "crx".
     */
    accepts: {
      type: Array
    },
    /**
     * Whether to accept multiple files. This is only supported for openFile and openWritableFile.
     */
    acceptsMultiple: Boolean,
  },
  /**
   * Read the file. Chrome API will be used to open a file.
   */
  read: function() {
    this._chooseEntry()
      .then(this._getContent.bind(this))
      .then(this._prepareContent.bind(this))
      .then(function() {
        this.fire('file-read');
      }.bind(this))
      .catch(function(cause) {
        this.fire('error', {
          'cause': 'read',
          'message': cause.message
        });
      }.bind(this));
  },
  write: function() {
    this._chooseEntry({
        type: 'saveFile'
      })
      .catch(function(cause) {
        // The only error here is that the user press cancel.
        // In this case just do nothing.
      }.bind(this))
      .then(this._truncate.bind(this))
      .then(this._writeFileEntry.bind(this))
      .then(function() {
        this.fire('file-save');
      }.bind(this))
      .catch(function(cause) {
        this.fire('error', {
          'cause': 'save',
          'message': cause.message
        });
      }.bind(this));
  },
  /**
   * Open the file using file picker and Chrome api.
   * By default this will open a file in read only mode.
   */
  _chooseEntry: function(opts) {
    opts = opts || {};
    if (this.fileName) {
      opts.suggestedName = this.fileName;
    }
    if (this.accepts) {
      opts.accepts = this.accepts;
    }
    if (typeof this.acceptsMultiple !== 'undefined') {
      opts.acceptsMultiple = this.acceptsMultiple;
    }
    return new Promise(function(resolve, reject) {
      chrome.fileSystem.chooseEntry(opts, function(entry) {
        if (chrome.runtime.lastError) {
          reject(chrome.runtime.lastError);
          return;
        }
        resolve(entry);
      }.bind(this));
    }.bind(this));
  }
};

FileBehaviors.FilesystemAppBehavior = [
  FileBehaviors.FilesystemBehavior,
  FileBehaviors.FilesystemAppBehaviorImpl
];
<|endoftext|>


<commit_before>var tape = require('tape')
var pull = require('pull-stream')
var Pushable = require('pull-pushable')

var Compose = require('../compose')
var Net = require('../plugins/net')
var Ws = require('../plugins/ws')
var Shs = require('../plugins/shs')
var Onion = require('../plugins/onion')
var MultiServer = require('../')

var cl = require('chloride')
var seed = cl.crypto_hash_sha256(new Buffer('TESTSEED'))
var keys = cl.crypto_sign_seed_keypair(seed)
var appKey = cl.crypto_hash_sha256(new Buffer('TEST'))

var requested, ts

//this gets overwritten in the last test.
var check = function (id, cb) {
  cb(null, true)
}

var net = Net({port: 4848})
var ws = Ws({port: 4849})
var shs = Shs({keys: keys, appKey: appKey, auth: function (id, cb) {
  requested = id
  ts = Date.now()

  check(id, cb)
}})

var combined = Compose([net, shs])
var combined_ws = Compose([ws, shs])

var multi = MultiServer([
  combined, combined_ws
])

var multi_ws = MultiServer([ combined_ws ])
var multi_net = MultiServer([ combined ])

var client_addr

var close = multi.server(function (stream) {
  console.log("onConnect", stream.address)
  client_addr = stream.address
  pull(stream, stream)
})

var server_addr =
'fake:peer.ignore~nul:what;'+multi.stringify()
//"fake" in a unkown protocol, just to make sure it gets skipped.

tape('connect to either server', function (t) {

  multi.client(server_addr, function (err, stream) {
    if(err) throw err
    console.log(stream)
    t.ok(/^net/.test(client_addr), 'client connected via net')
    t.ok(/^net/.test(stream.address), 'client connected via net')
    pull(
      pull.values([new Buffer('Hello')]),
      stream,
      pull.collect(function (err,  ary) {
        var data = Buffer.concat(ary).toString('utf8')
        console.log("OUTPUT", data)
//        close()
        t.end()
      })
    )
  })
})

tape('connect to either server', function (t) {

  console.log(multi.stringify())

  multi_ws.client(server_addr, function (err, stream) {
    if(err) throw err
    t.ok(/^ws/.test(client_addr), 'client connected via ws')
    t.ok(/^ws/.test(stream.address), 'client connected via net')
    pull(
      pull.values([new Buffer('Hello')]),
      stream,
      pull.collect(function (err,  ary) {
        var data = Buffer.concat(ary).toString('utf8')
        console.log("OUTPUT", data)
        t.end()
      })
    )
  })
})

tape('connect to either server', function (t) {

  multi_net.client(server_addr, function (err, stream) {
    if(err) throw err
    t.ok(/^net/.test(client_addr), 'client connected via net')
    t.ok(/^net/.test(stream.address), 'client connected via net')
    pull(
      pull.values([new Buffer('Hello')]),
      stream,
      pull.collect(function (err,  ary) {
        var data = Buffer.concat(ary).toString('utf8')
        console.log("OUTPUT", data)
        t.end()
      })
    )
  })
})

tape('close', function (t) {
  close()
  t.end()
})

<commit_msg>Make tests pass again<commit_after>var tape = require('tape')
var pull = require('pull-stream')
var Pushable = require('pull-pushable')

var Compose = require('../compose')
var Net = require('../plugins/net')
var Ws = require('../plugins/ws')
var Shs = require('../plugins/shs')
var Onion = require('../plugins/onion')
var MultiServer = require('../')

var cl = require('chloride')
var seed = cl.crypto_hash_sha256(new Buffer('TESTSEED'))
var keys = cl.crypto_sign_seed_keypair(seed)
var appKey = cl.crypto_hash_sha256(new Buffer('TEST'))

var requested, ts

//this gets overwritten in the last test.
var check = function (id, cb) {
  cb(null, true)
}

var net = Net({port: 4848, scope: 'public'})
var ws = Ws({port: 4849, scope: 'public'})
var shs = Shs({keys: keys, appKey: appKey, auth: function (id, cb) {
  requested = id
  ts = Date.now()

  check(id, cb)
}})

var combined = Compose([net, shs])
var combined_ws = Compose([ws, shs])

var multi = MultiServer([
  combined, combined_ws
])

var multi_ws = MultiServer([ combined_ws ])
var multi_net = MultiServer([ combined ])

var client_addr

var close = multi.server(function (stream) {
  console.log("onConnect", stream.address)
  client_addr = stream.address
  pull(stream, stream)
})

var server_addr =
'fake:peer.ignore~nul:what;'+multi.stringify()
//"fake" in a unkown protocol, just to make sure it gets skipped.

tape('connect to either server', function (t) {

  multi.client(server_addr, function (err, stream) {
    if(err) throw err
    console.log(stream)
    t.ok(/^net/.test(client_addr), 'client connected via net')
    t.ok(/^net/.test(stream.address), 'client connected via net')
    pull(
      pull.values([new Buffer('Hello')]),
      stream,
      pull.collect(function (err,  ary) {
        var data = Buffer.concat(ary).toString('utf8')
        console.log("OUTPUT", data)
//        close()
        t.end()
      })
    )
  })
})

tape('connect to either server', function (t) {

  console.log(multi.stringify())

  multi_ws.client(server_addr, function (err, stream) {
    if(err) throw err
    t.ok(/^ws/.test(client_addr), 'client connected via ws')
    t.ok(/^ws/.test(stream.address), 'client connected via net')
    pull(
      pull.values([new Buffer('Hello')]),
      stream,
      pull.collect(function (err,  ary) {
        var data = Buffer.concat(ary).toString('utf8')
        console.log("OUTPUT", data)
        t.end()
      })
    )
  })
})

tape('connect to either server', function (t) {

  multi_net.client(server_addr, function (err, stream) {
    if(err) throw err
    t.ok(/^net/.test(client_addr), 'client connected via net')
    t.ok(/^net/.test(stream.address), 'client connected via net')
    pull(
      pull.values([new Buffer('Hello')]),
      stream,
      pull.collect(function (err,  ary) {
        var data = Buffer.concat(ary).toString('utf8')
        console.log("OUTPUT", data)
        t.end()
      })
    )
  })
})

tape('close', function (t) {
  close()
  t.end()
})

<|endoftext|>


<commit_before>var ddg_spice_forvo = function(api_result) {
    "use strict";

    // api_result.items can be either an array or an object.
    // Forvo returns either an array-like object or an actual array.
    // {0: "...", 1: "...", 2: "..."} or ["...", "...", "..."].
    if($.isArray(api_result.items)) {
        api_result.isArray = true;
    } else {
        api_result.isArray = false;
    }

    // Display the Spice plug-in.
    Spice.render({
        data             : api_result,
        header1          : "Pronunciations (Forvo)",
        source_url       : "http://www.forvo.com/",
        source_name      : "Forvo",
        template_normal  : "forvo",
        force_big_header : true
    });

    $(".zero_click_snippet").attr("style", "margin-left: 0px !important; display: block;");

    // Initialize SoundManager2.
    window.SM2_DEFER = true;
    var soundSetup = function() {
        window.soundManager = new SoundManager();
        soundManager.url = "/soundmanager2/swf/";
        soundManager.flashVersion = 9;
        soundManager.useFlashBlock = false;
        soundManager.useHTML5Audio = false;
        soundManager.beginDelayedInit();
        soundManager.onready(function() {
            // Prevent the user from clicking the link.
            // This copies the attribute "data-stream" to "href."
            $(".forvo-audio").each(function() {
                var stream = $(this).attr("data-stream");
                $(this).attr("href", stream);
            });
            var pagePlayer = new PagePlayer();
            pagePlayer.init();
        });
    };

    var ready = [false, false];
    var checkReady = function(toggle) {
        ready[toggle] = true;
        if(ready[0] && ready[1]) {
            soundSetup();
        }
    };

    // Load page-player.js. This JS file converts a list of MP3s into a playlist.
    $.getScript("/soundmanager2/script/page-player-forvo.js", function() {
        checkReady(0);
    });

    // Load SoundManager2. This JS file handles our audio.
    $.getScript("/soundmanager2/script/soundmanager2-nodebug-jsmin.js", function() {
        checkReady(1);
    });
};

// Make sure we display only five items.
Handlebars.registerHelper("list", function(items, options) {
    "use strict";

    var out = "";
    for(var i = 0; i < items.length && i < 5; i += 1) {
        out += options.fn(items[i]);
    }
    return out;
});

// The sex (returned as either "m" or "f") should be expanded.
Handlebars.registerHelper("sex", function(sex) {
    "use strict";

    if(sex === "m") {
        return ", Male";
    } else {
        return ", Female";
    }
});

// Make sure we display only five items.
// This helper is for objects.
Handlebars.registerHelper("listObjects", function(items, options) {
    "use strict";

    var hasOwn = Object.prototype.hasOwnProperty,
        index = 0,
        out = "";

    for(var data in items) {
        console.log(data);
        if(index < 5) {
            out += options.fn(items[data]);
        }
        index += 1;
    }

    return out;
});<commit_msg>Forvo: Forgot to use hasOwn.<commit_after>var ddg_spice_forvo = function(api_result) {
    "use strict";

    // api_result.items can be either an array or an object.
    // Forvo returns either an array-like object or an actual array.
    // {0: "...", 1: "...", 2: "..."} or ["...", "...", "..."].
    if($.isArray(api_result.items)) {
        api_result.isArray = true;
    } else {
        api_result.isArray = false;
    }

    // Display the Spice plug-in.
    Spice.render({
        data             : api_result,
        header1          : "Pronunciations (Forvo)",
        source_url       : "http://www.forvo.com/",
        source_name      : "Forvo",
        template_normal  : "forvo",
        force_big_header : true
    });

    $(".zero_click_snippet").attr("style", "margin-left: 0px !important; display: block;");

    // Initialize SoundManager2.
    window.SM2_DEFER = true;
    var soundSetup = function() {
        window.soundManager = new SoundManager();
        soundManager.url = "/soundmanager2/swf/";
        soundManager.flashVersion = 9;
        soundManager.useFlashBlock = false;
        soundManager.useHTML5Audio = false;
        soundManager.beginDelayedInit();
        soundManager.onready(function() {
            // Prevent the user from clicking the link.
            // This copies the attribute "data-stream" to "href."
            $(".forvo-audio").each(function() {
                var stream = $(this).attr("data-stream");
                $(this).attr("href", stream);
            });
            var pagePlayer = new PagePlayer();
            pagePlayer.init();
        });
    };

    var ready = [false, false];
    var checkReady = function(toggle) {
        ready[toggle] = true;
        if(ready[0] && ready[1]) {
            soundSetup();
        }
    };

    // Load page-player.js. This JS file converts a list of MP3s into a playlist.
    $.getScript("/soundmanager2/script/page-player-forvo.js", function() {
        checkReady(0);
    });

    // Load SoundManager2. This JS file handles our audio.
    $.getScript("/soundmanager2/script/soundmanager2-nodebug-jsmin.js", function() {
        checkReady(1);
    });
};

// Make sure we display only five items.
Handlebars.registerHelper("list", function(items, options) {
    "use strict";

    var out = "";
    for(var i = 0; i < items.length && i < 5; i += 1) {
        out += options.fn(items[i]);
    }
    return out;
});

// The sex (returned as either "m" or "f") should be expanded.
Handlebars.registerHelper("sex", function(sex) {
    "use strict";

    if(sex === "m") {
        return ", Male";
    } else {
        return ", Female";
    }
});

// Make sure we display only five items.
// This helper is for objects.
Handlebars.registerHelper("listObjects", function(items, options) {
    "use strict";

    var hasOwn = Object.prototype.hasOwnProperty,
        index = 0,
        out = "";

    for(var data in items) {
        if(hasOwn.call(items, data)) {
            if(index < 5) {
                out += options.fn(items[data]);
            }
            index += 1;
        }
    }

    return out;
});<|endoftext|>


<commit_before>/*
 * Example plugin template
 */

jsPsych.plugins["PLUGIN-NAME"] = (function() {

  var plugin = {};

  plugin.info = {
    name: "PLUGIN-NAME",
    parameters: {
      parameter_name: {
        type: jsPsych.plugins.parameterType.INT, // INT, IMAGE, KEYCODE, STRING, FUNCTION, FLOAT
        default_value: undefined
      },
      parameter_name: {
        type: jsPsych.plugins.parameterType.IMAGE,
        default_value: undefined
      }
    }
  }

  plugin.trial = function(display_element, trial) {

    // data saving
    var trial_data = {
      parameter_name: 'parameter value'
    };

    // end trial
    jsPsych.finishTrial(trial_data);
  };

  return plugin;
})();
<commit_msg>fix #490<commit_after>/*
 * Example plugin template
 */

jsPsych.plugins["PLUGIN-NAME"] = (function() {

  var plugin = {};

  plugin.info = {
    name: "PLUGIN-NAME",
    parameters: {
      parameter_name: {
        type: jsPsych.plugins.parameterType.INT, // BOOL, STRING, INT, FLOAT, FUNCTION, KEYCODE, SELECT, HTML_STRING, IMAGE, AUDIO, VIDEO, OBJECT, COMPLEX
        default: undefined
      },
      parameter_name: {
        type: jsPsych.plugins.parameterType.IMAGE,
        default: undefined
      }
    }
  }

  plugin.trial = function(display_element, trial) {

    // data saving
    var trial_data = {
      parameter_name: 'parameter value'
    };

    // end trial
    jsPsych.finishTrial(trial_data);
  };

  return plugin;
})();
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @flow
 *
 */

var reactModules = ['react', 'react/addons', 'react-native'];

/**
 * Takes a module name (string) and returns true if it refers to a root react
 * module name.
 */
export default function isReactModuleName(moduleName: string): boolean {
  return reactModules.some(function(reactModuleName) {
    return reactModuleName === moduleName.toLowerCase();
  });
}
<commit_msg>Add developit/proptypes to allowed module names (#163)<commit_after>/*
 * Copyright (c) 2015, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @flow
 *
 */

var reactModules = ['react', 'react/addons', 'react-native', 'proptypes'];

/**
 * Takes a module name (string) and returns true if it refers to a root react
 * module name.
 */
export default function isReactModuleName(moduleName: string): boolean {
  return reactModules.some(function(reactModuleName) {
    return reactModuleName === moduleName.toLowerCase();
  });
}
<|endoftext|>


<commit_before>angular.module('cryptoforum', [ 'ngAnimate', 'ui.router', 'anim-in-out' ])
.controller( 'HomeCtrl', [ '$scope', '$window', '$state', 'walletService', HomeCtrl ] )
.controller( 'ForumCtrl', [ '$rootScope', '$state', ForumCtrl ] )
.service( 'walletService', [ '$http', '$rootScope', WalletService ] )
.config( config )
.config( routes )
.run( [ '$rootScope', '$window', 'walletService', function( $rootScope, $window, walletService ) {
  var web3 = new Web3();

  $rootScope.web3 = web3;
  $window.web3 = web3;

  $rootScope.defaultContract = { id: '0x0b092122102eeb28b1980488f8335617c702d1d8',
    abi: [{"constant":false,"inputs":[{"name":"title","type":"string"},{"name":"content","type":"string"},{"name":"forum","type":"uint256"}],"name":"createMessage","outputs":[{"name":"messageID","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"forums","outputs":[{"name":"owner","type":"address"},{"name":"name","type":"string"},{"name":"messageCount","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[{"name":"name","type":"string"}],"name":"createForum","outputs":[{"name":"forumID","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[{"name":"forum","type":"uint256"},{"name":"message","type":"uint256"}],"name":"getMessage","outputs":[],"type":"function"},{"constant":true,"inputs":[],"name":"forumCount","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"title","type":"string"},{"indexed":false,"name":"content","type":"string"}],"name":"readMessage","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"name","type":"string"},{"indexed":false,"name":"forumID","type":"uint256"}],"name":"forumCreated","type":"event"}] }

  $rootScope.contract =  web3.eth.contract( $rootScope.defaultContract.abi ).at( $rootScope.defaultContract.id );
  $window.contract = $rootScope.contract;

  if( walletService.storedWalletAvailable() ) {
    var storedWallet = walletService.storedWalletRestore();
  };

}]);

config.$inject = ['$urlRouterProvider', '$locationProvider' ];
function config($urlProvider, $locationProvider, $analyticsProvider, $cookies, $rootScope, $window ) {
  $urlProvider.otherwise('/');

  $locationProvider.html5Mode({
    enabled:false,
    requireBase: false
  });
  $locationProvider.hashPrefix('!');

}
<commit_msg>new contract address<commit_after>angular.module('cryptoforum', [ 'ngAnimate', 'ui.router', 'anim-in-out' ])
.controller( 'HomeCtrl', [ '$scope', '$window', '$state', 'walletService', HomeCtrl ] )
.controller( 'ForumCtrl', [ '$rootScope', '$state', '$stateParams', ForumCtrl ] )
.service( 'walletService', [ '$http', '$rootScope', WalletService ] )
.config( config )
.config( routes )
.run( [ '$rootScope', '$window', 'walletService', function( $rootScope, $window, walletService ) {
  var web3 = new Web3();

  $rootScope.web3 = web3;
  $window.web3 = web3;

  $rootScope.defaultContract = { id: '0xd77b570ef75458cfa689ecbcce2cd02267af3ef9',
    abi: [{"constant":false,"inputs":[{"name":"title","type":"string"},{"name":"content","type":"string"},{"name":"forum","type":"uint256"}],"name":"createMessage","outputs":[{"name":"messageID","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"forums","outputs":[{"name":"owner","type":"address"},{"name":"name","type":"string"},{"name":"messageCount","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[{"name":"name","type":"string"}],"name":"createForum","outputs":[{"name":"forumID","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[{"name":"forum","type":"uint256"},{"name":"message","type":"uint256"}],"name":"getMessage","outputs":[],"type":"function"},{"constant":true,"inputs":[],"name":"forumCount","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"title","type":"string"},{"indexed":false,"name":"content","type":"string"}],"name":"readMessage","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"name","type":"string"},{"indexed":false,"name":"forumID","type":"uint256"}],"name":"forumCreated","type":"event"}] }

  $rootScope.contract =  web3.eth.contract( $rootScope.defaultContract.abi ).at( $rootScope.defaultContract.id );
  $window.contract = $rootScope.contract;

  if( walletService.storedWalletAvailable() ) {
    var storedWallet = walletService.storedWalletRestore();
  };

}]);

config.$inject = ['$urlRouterProvider', '$locationProvider' ];
function config($urlProvider, $locationProvider, $analyticsProvider, $cookies, $rootScope, $window ) {
  $urlProvider.otherwise('/');

  $locationProvider.html5Mode({
    enabled:false,
    requireBase: false
  });
  $locationProvider.hashPrefix('!');

}
<|endoftext|>


<commit_before>
const dal = require('./dal');
const status = require('http-status-codes');
const config = require('georap-config');

exports.getOne = function (req, res, next) {
  // Response with JSON object of user with admin-only information
  //
  // Response:
  //   {
  //     email: <string>,
  //     name: <string>,
  //     points: <int>,
  //     role: <string>,
  //     status: <'active' | 'deactivated'>
  //   }

  const username = req.username;

  dal.getUserForAdmin(username, (err, user) => {
    if (err) {
      return next(err);
    }

    if (user === null) {
      return res.sendStatus(status.NOT_FOUND);
    }

    return res.json(user);
  });
};

exports.setStatus = function (req, res, next) {

  const isActive = req.body.isActive;

  const targetName = req.username;
  const authorName = req.user.name;

  // Prevent author blocking him/herself out.
  if (authorName === targetName) {
    return res.sendStatus(status.BAD_REQUEST);
  }

  const newStatus = isActive ? 'active' : 'deactivated';

  dal.setStatus(targetName, newStatus, (err) => {
    if (err) {
      return next(err);
    }

    return res.sendStatus(status.OK);
  });
};

exports.setRole = function (req, res, next) {
  // Set user role
  const newRole = req.body.role;
  const targetName = req.username;
  const authorName = req.user.name;

  // Ensure role is valid
  if (!config.roles.includes(newRole)) {
    return res.status(status.BAD_REQUEST).send('Invalid role');
  }

  // Prevent author changing his/her own role.
  // This ensures there is always at least one user with admin role.
  if (authorName === targetName) {
    return res.status(status.BAD_REQUEST).send('Cannot change own role');
  }

  dal.setRole(targetName, newRole, (err) => {
    if (err) {
      return next(err);
    }

    return res.sendStatus(status.OK);
  });
};
<commit_msg>Return 403 forbidden instead of bad req if user try change own role<commit_after>
const dal = require('./dal');
const status = require('http-status-codes');
const config = require('georap-config');

exports.getOne = function (req, res, next) {
  // Response with JSON object of user with admin-only information
  //
  // Response:
  //   {
  //     email: <string>,
  //     name: <string>,
  //     points: <int>,
  //     role: <string>,
  //     status: <'active' | 'deactivated'>
  //   }

  const username = req.username;

  dal.getUserForAdmin(username, (err, user) => {
    if (err) {
      return next(err);
    }

    if (user === null) {
      return res.sendStatus(status.NOT_FOUND);
    }

    return res.json(user);
  });
};

exports.setStatus = function (req, res, next) {

  const isActive = req.body.isActive;

  const targetName = req.username;
  const authorName = req.user.name;

  // Prevent author blocking him/herself out.
  if (authorName === targetName) {
    return res.sendStatus(status.BAD_REQUEST);
  }

  const newStatus = isActive ? 'active' : 'deactivated';

  dal.setStatus(targetName, newStatus, (err) => {
    if (err) {
      return next(err);
    }

    return res.sendStatus(status.OK);
  });
};

exports.setRole = function (req, res, next) {
  // Set user role
  const newRole = req.body.role;
  const targetName = req.username;
  const authorName = req.user.name;

  // Ensure role is valid
  if (!config.roles.includes(newRole)) {
    return res.status(status.BAD_REQUEST).send('Invalid role');
  }

  // Prevent author changing his/her own role.
  // This ensures there is always at least one user with admin role.
  if (authorName === targetName) {
    return res.status(status.FORBIDDEN).send('Cannot change own role');
  }

  dal.setRole(targetName, newRole, (err) => {
    if (err) {
      return next(err);
    }

    return res.sendStatus(status.OK);
  });
};
<|endoftext|>


<commit_before>let vscode = require('vscode');

class Resolver {
    importNamespace() {
        this.findFiles()
            .then(files => this.findNamespaces(files))
            .then(namespaces => this.pickNamespace(namespaces))
            .then(pickedNamespace => {
                try {
                    this.insertNamespace(pickedNamespace);
                } catch (error) {
                    if (! error.message) {
                        return;
                    }

                    return this.showMessage(error.message);
                }

                this.showMessage('$(check)  Namespace imported.');
            });
    }

    expandNamespace() {
        this.findFiles()
            .then(files => this.findNamespaces(files))
            .then(namespaces => this.pickNamespace(namespaces))
            .then(pickedNamespace => this.expandToFqn(pickedNamespace));
    }

    sortNamespaces() {
        this.sortImports();
        this.showMessage('$(check)  Namespace sorted.');
    }

    findFiles() {
        let include = '**/*.php';
        let exclude = '**/node_modules/**';

        return vscode.workspace.findFiles(include, exclude);
    }

    findNamespaces(files) {
        return new Promise((resolve, reject) => {
            let resolving = this.resolving();

            if (resolving === null) {
                return this.showMessage(`$(issue-opened)  No class is selected.`, true);
            }

            let textDocuments = this.getTextDocuments(files, resolving);

            Promise.all(textDocuments).then(docs => {
                let parsedNamespaces = this.parseNamespaces(docs, resolving);

                if (parsedNamespaces.length === 0) {
                    return this.showMessage(`$(circle-slash)  Class ' ${resolving} ' not found.`, true);
                }

                resolve(parsedNamespaces);
            });
        });
    }

    getTextDocuments(files, resolving) {
        let textDocuments = [];

        for (let i = 0; i < files.length; i++) {
            let fileName = files[i].fsPath.replace(/^.*[\\\/]/, '').split('.')[0];

            if (fileName !== resolving) {
                continue;
            }

            textDocuments.push(vscode.workspace.openTextDocument(files[i]));
        }

        return textDocuments;
    }

    parseNamespaces(docs, resolving) {
        let parsedNamespaces = [];

        for (let i = 0; i < docs.length; i++) {
            for (let line = 0; line < docs[i].lineCount; line++) {
                let textLine = docs[i].lineAt(line).text;

                if (textLine.startsWith('namespace ') || textLine.startsWith('<?php namespace ')) {
                    let namespace = textLine.split('namespace ')[1].split(';')[0] + '\\' + resolving;

                    if (parsedNamespaces.indexOf(namespace) === -1) {
                        parsedNamespaces.push(namespace);
                    }
                }
            }
        }

        return parsedNamespaces;
    }

    pickNamespace(namespaces) {
        return new Promise((resolve, reject) => {
            if (namespaces.length === 1) {
                // There is only one namespace found so return with the first namespace.
                return resolve(namespaces[0]);
            }

            vscode.window.showQuickPick(namespaces).then(picked => {
                if (picked !== undefined) {
                    resolve(picked);
                }
            });
        })
    }

    insertNamespace(pickedNamespace) {
        let [useStatements, declarationLines] = this.getDeclarations(pickedNamespace);

        if (declarationLines.PHPTag === null) {
            this.showMessage('$(circle-slash)  Can not import namespace in this file', true);
            throw new Error();
        }

        let [prepend, append, insertLine] = this.getInsertLine(declarationLines);

        this.activeEditor().edit(textEdit => {
            textEdit.replace(
                new vscode.Position((insertLine), 0),
                `${prepend}use ${pickedNamespace};${append}`
            );
        });

        if (this.config('autoSort')) {
            this.activeEditor().document.save().then(() => this.sortImports());
        }
    }

    expandToFqn(pickedNamespace) {
        this.activeEditor().edit(textEdit => {
            textEdit.replace(
                this.getWordRange(),
                (this.config('leadingSeparator') ? '\\' : '') + pickedNamespace
            );
        })
    }

    sortImports() {
        let useStatements = this.getDeclarations();

        if (useStatements.length <= 1) {
            return this.showMessage('$(issue-opened)  Nothing to sort.')
        }

        let sorted = useStatements.slice().sort((a, b) => {
            if (this.config('sortAlphabetically')) {
                if (a.text < b.text) return -1;
                if (a.text > b.text) return 1;
                return 0;
            } else {
                return a.text.length - b.text.length;
            }
        });

        this.activeEditor().edit(textEdit => {
            for (let i = 0; i < sorted.length; i++) {
                textEdit.replace(
                    new vscode.Range(useStatements[i].line, 0, useStatements[i].line, useStatements[i].text.length),
                    sorted[i].text
                );
            }
        });
    }

    getDeclarations(pickedNamespace = null) {
        let useStatements = [];
        let declarationLines = {
            PHPTag: null,
            namespace: null,
            useStatement: null,
            class: null
        };

        for (let line = 0; line < this.activeEditor().document.lineCount; line++) {
            let text = this.activeEditor().document.lineAt(line).text;

            if (pickedNamespace !== null && text === `use ${pickedNamespace};`) {
                throw new Error('$(issue-opened)  Namespace already imported.');
            }

            if (text.startsWith('<?php')) {
                declarationLines.PHPTag = line + 1;
            } else if (text.startsWith('namespace ')) {
                declarationLines.namespace = line + 1;
            } else if (text.startsWith('use ')) {
                useStatements.push({ text, line });
                declarationLines.useStatement = line + 1;
            } else if (text.startsWith('class ')) {
                declarationLines.class = line + 1;
            } else {
                continue;
            }
        }

        if (pickedNamespace === null) {
            return useStatements;
        }

        return [useStatements, declarationLines];
    }

    getInsertLine(declarationLines) {
        let prepend = '\n';
        let append = '\n';
        let insertLine = declarationLines.PHPTag;

        if (declarationLines.useStatement !== null) {
            prepend = '';
            insertLine = declarationLines.useStatement;
        } else if (declarationLines.namespace !== null) {
            insertLine = declarationLines.namespace;
        }

        if (declarationLines.class !== null &&
            ((declarationLines.class - declarationLines.useStatement) <= 1 ||
            (declarationLines.class - declarationLines.namespace) <= 1 ||
            (declarationLines.class - declarationLines.PHPTag) <= 1)
        ) {
            append = '\n\n';
        }

        return [prepend, append, insertLine];
    }

    activeEditor() {
        return vscode.window.activeTextEditor;
    }

    getWordRange() {
        return this.activeEditor().document.getWordRangeAtPosition(
            this.activeEditor().selection.active
        );
    }

    resolving() {
        let wordRange = this.getWordRange();

        if (wordRange === undefined) {
            return null;
        }

        return this.activeEditor().document.getText(wordRange);
    }

    config(key) {
        return vscode.workspace.getConfiguration('namespaceResolver').get(key);
    }

    showMessage(message, error = false) {
        if (this.config('messagesOnStatusBar')) {
            return vscode.window.setStatusBarMessage(message, 3000);
        }

        let notify = vscode.window.showInformationMessage;

        if (error) {
            notify = vscode.window.showErrorMessage;
        }

        notify(message.replace(/\$\(.+?\)\s\s/, ''));
    }
}

function activate(context) {
    let resolver = new Resolver;

    let importNamespace = vscode.commands.registerCommand('namespaceResolver.import', () => resolver.importNamespace());
    let expandNamespace = vscode.commands.registerCommand('namespaceResolver.expand', () => resolver.expandNamespace());
    let sortNamespaces = vscode.commands.registerCommand('namespaceResolver.sort', () => resolver.sortNamespaces());

    context.subscriptions.push(importNamespace);
    context.subscriptions.push(expandNamespace);
    context.subscriptions.push(sortNamespaces);
    context.subscriptions.push(resolver);
}

exports.activate = activate;
<commit_msg>Show error message instead of info if namespace is already imported<commit_after>let vscode = require('vscode');

class Resolver {
    importNamespace() {
        this.findFiles()
            .then(files => this.findNamespaces(files))
            .then(namespaces => this.pickNamespace(namespaces))
            .then(pickedNamespace => {
                try {
                    this.insertNamespace(pickedNamespace);
                } catch (error) {
                    return this.showMessage(error.message, true);
                }

                this.showMessage('$(check)  Namespace imported.');
            });
    }

    expandNamespace() {
        this.findFiles()
            .then(files => this.findNamespaces(files))
            .then(namespaces => this.pickNamespace(namespaces))
            .then(pickedNamespace => this.expandToFqn(pickedNamespace));
    }

    sortNamespaces() {
        this.sortImports();
        this.showMessage('$(check)  Namespace sorted.');
    }

    findFiles() {
        let include = '**/*.php';
        let exclude = '**/node_modules/**';

        return vscode.workspace.findFiles(include, exclude);
    }

    findNamespaces(files) {
        return new Promise((resolve, reject) => {
            let resolving = this.resolving();

            if (resolving === null) {
                return this.showMessage(`$(issue-opened)  No class is selected.`, true);
            }

            let textDocuments = this.getTextDocuments(files, resolving);

            Promise.all(textDocuments).then(docs => {
                let parsedNamespaces = this.parseNamespaces(docs, resolving);

                if (parsedNamespaces.length === 0) {
                    return this.showMessage(`$(circle-slash)  Class ' ${resolving} ' not found.`, true);
                }

                resolve(parsedNamespaces);
            });
        });
    }

    getTextDocuments(files, resolving) {
        let textDocuments = [];

        for (let i = 0; i < files.length; i++) {
            let fileName = files[i].fsPath.replace(/^.*[\\\/]/, '').split('.')[0];

            if (fileName !== resolving) {
                continue;
            }

            textDocuments.push(vscode.workspace.openTextDocument(files[i]));
        }

        return textDocuments;
    }

    parseNamespaces(docs, resolving) {
        let parsedNamespaces = [];

        for (let i = 0; i < docs.length; i++) {
            for (let line = 0; line < docs[i].lineCount; line++) {
                let textLine = docs[i].lineAt(line).text;

                if (textLine.startsWith('namespace ') || textLine.startsWith('<?php namespace ')) {
                    let namespace = textLine.split('namespace ')[1].split(';')[0] + '\\' + resolving;

                    if (parsedNamespaces.indexOf(namespace) === -1) {
                        parsedNamespaces.push(namespace);
                    }
                }
            }
        }

        return parsedNamespaces;
    }

    pickNamespace(namespaces) {
        return new Promise((resolve, reject) => {
            if (namespaces.length === 1) {
                // There is only one namespace found so return with the first namespace.
                return resolve(namespaces[0]);
            }

            vscode.window.showQuickPick(namespaces).then(picked => {
                if (picked !== undefined) {
                    resolve(picked);
                }
            });
        })
    }

    insertNamespace(pickedNamespace) {
        let [useStatements, declarationLines] = this.getDeclarations(pickedNamespace);

        if (declarationLines.PHPTag === null) {
            throw new Error('$(circle-slash)  Can not import namespace in this file');
        }

        let [prepend, append, insertLine] = this.getInsertLine(declarationLines);

        this.activeEditor().edit(textEdit => {
            textEdit.replace(
                new vscode.Position((insertLine), 0),
                `${prepend}use ${pickedNamespace};${append}`
            );
        });

        if (this.config('autoSort')) {
            this.activeEditor().document.save().then(() => this.sortImports());
        }
    }

    expandToFqn(pickedNamespace) {
        this.activeEditor().edit(textEdit => {
            textEdit.replace(
                this.getWordRange(),
                (this.config('leadingSeparator') ? '\\' : '') + pickedNamespace
            );
        })
    }

    sortImports() {
        let useStatements = this.getDeclarations();

        if (useStatements.length <= 1) {
            return this.showMessage('$(issue-opened)  Nothing to sort.')
        }

        let sorted = useStatements.slice().sort((a, b) => {
            if (this.config('sortAlphabetically')) {
                if (a.text < b.text) return -1;
                if (a.text > b.text) return 1;
                return 0;
            } else {
                return a.text.length - b.text.length;
            }
        });

        this.activeEditor().edit(textEdit => {
            for (let i = 0; i < sorted.length; i++) {
                textEdit.replace(
                    new vscode.Range(useStatements[i].line, 0, useStatements[i].line, useStatements[i].text.length),
                    sorted[i].text
                );
            }
        });
    }

    getDeclarations(pickedNamespace = null) {
        let useStatements = [];
        let declarationLines = {
            PHPTag: null,
            namespace: null,
            useStatement: null,
            class: null
        };

        for (let line = 0; line < this.activeEditor().document.lineCount; line++) {
            let text = this.activeEditor().document.lineAt(line).text;

            if (pickedNamespace !== null && text === `use ${pickedNamespace};`) {
                throw new Error('$(issue-opened)  Namespace already imported.');
            }

            if (text.startsWith('<?php')) {
                declarationLines.PHPTag = line + 1;
            } else if (text.startsWith('namespace ')) {
                declarationLines.namespace = line + 1;
            } else if (text.startsWith('use ')) {
                useStatements.push({ text, line });
                declarationLines.useStatement = line + 1;
            } else if (text.startsWith('class ')) {
                declarationLines.class = line + 1;
            } else {
                continue;
            }
        }

        if (pickedNamespace === null) {
            return useStatements;
        }

        return [useStatements, declarationLines];
    }

    getInsertLine(declarationLines) {
        let prepend = '\n';
        let append = '\n';
        let insertLine = declarationLines.PHPTag;

        if (declarationLines.useStatement !== null) {
            prepend = '';
            insertLine = declarationLines.useStatement;
        } else if (declarationLines.namespace !== null) {
            insertLine = declarationLines.namespace;
        }

        if (declarationLines.class !== null &&
            ((declarationLines.class - declarationLines.useStatement) <= 1 ||
            (declarationLines.class - declarationLines.namespace) <= 1 ||
            (declarationLines.class - declarationLines.PHPTag) <= 1)
        ) {
            append = '\n\n';
        }

        return [prepend, append, insertLine];
    }

    activeEditor() {
        return vscode.window.activeTextEditor;
    }

    getWordRange() {
        return this.activeEditor().document.getWordRangeAtPosition(
            this.activeEditor().selection.active
        );
    }

    resolving() {
        let wordRange = this.getWordRange();

        if (wordRange === undefined) {
            return null;
        }

        return this.activeEditor().document.getText(wordRange);
    }

    config(key) {
        return vscode.workspace.getConfiguration('namespaceResolver').get(key);
    }

    showMessage(message, error = false) {
        if (this.config('messagesOnStatusBar')) {
            return vscode.window.setStatusBarMessage(message, 3000);
        }

        let notify = vscode.window.showInformationMessage;

        if (error) {
            notify = vscode.window.showErrorMessage;
        }

        notify(message.replace(/\$\(.+?\)\s\s/, ''));
    }
}

function activate(context) {
    let resolver = new Resolver;

    let importNamespace = vscode.commands.registerCommand('namespaceResolver.import', () => resolver.importNamespace());
    let expandNamespace = vscode.commands.registerCommand('namespaceResolver.expand', () => resolver.expandNamespace());
    let sortNamespaces = vscode.commands.registerCommand('namespaceResolver.sort', () => resolver.sortNamespaces());

    context.subscriptions.push(importNamespace);
    context.subscriptions.push(expandNamespace);
    context.subscriptions.push(sortNamespaces);
    context.subscriptions.push(resolver);
}

exports.activate = activate;
<|endoftext|>


<commit_before>/************************************
 * Copyright (c) 2014 AnsibleWorks, Inc.
 *
 *
 *  Organizations.js
 *
 *  Controller functions for Organization model.
 *
 */
/**
 * @ngdoc function
 * @name controllers.function:Organizations
 * @description This controller's for the Organizations page
*/

export function LicenseController(ClearScope, $location, $rootScope, $compile, $filter, GenerateForm, Rest, Alert,
    GetBasePath, ProcessErrors, FormatDate, Prompt, Empty, LicenseForm, IsAdmin, CreateDialog, CheckLicense,
    TextareaResize, $scope) {

        ClearScope();

        $scope.getDefaultHTML = function(license_info) {
            var fld, html,
                self = this,
                generator = GenerateForm;

            self.form = angular.copy(LicenseForm);

            for (fld in self.form.fields) {
                if (fld !== 'time_remaining' && fld !== 'license_status' && fld !== 'tower_version') {
                    if (Empty(license_info[fld])) {
                        delete self.form.fields[fld];
                    }
                }
            }

            if (!IsAdmin()) {
                delete self.form.fields.license_key;
            }

            if (license_info.is_aws || Empty(license_info.license_date)) {
                delete self.form.fields.license_date;
                delete self.form.fields.time_remaining;
            }

            html = generator.buildHTML(self.form, { mode: 'edit', showButtons: false, breadCrumbs: false });
            return html;
        };

        $scope.loadDefaultScope = function(license_info, version) {
            var fld, dt, days, license,
                self = this;

            for (fld in self.form.fields) {
                if (!Empty(license_info[fld])) {
                    $scope[fld] = license_info[fld];
                }
            }

            $scope.tower_version = version;

            if ($scope.license_date) {
                dt = new Date(parseInt($scope.license_date, 10) * 1000); // expects license_date in seconds
                $scope.license_date = FormatDate(dt);
                $scope.time_remaining = parseInt($scope.time_remaining,10) * 1000;
                if ($scope.time_remaining < 0) {
                    days = 0;
                } else {
                    days = Math.floor($scope.time_remaining / 86400000);
                }
                $scope.time_remaining = (days!==1) ? $filter('number')(days, 0) + ' days' : $filter('number')(days, 0) + ' day'; // '1 day' and '0 days/2 days' or more
            }

            if (parseInt($scope.free_instances) <= 0) {
                $scope.free_instances_class = 'field-failure';
            } else {
                $scope.free_instances_class = 'field-success';
            }

            license = license_info;
            if (license.valid_key === undefined) {
                $scope.license_status = 'Missing License Key';
                $scope.status_color = 'license-invalid';
            } else if (!license.valid_key) {
                $scope.license_status = 'Invalid License Key';
                $scope.status_color = 'license-invalid';
            } else if (license.date_expired !== undefined && license.date_expired) {
                $scope.license_status = 'License Expired';
                $scope.status_color = 'license-expired';
            } else if (license.date_warning !== undefined && license.date_warning) {
                $scope.license_status = 'License Expiring Soon';
                $scope.status_color = 'license-warning';
            } else if (license.free_instances !== undefined && parseInt(license.free_instances) <= 0) {
                $scope.license_status = 'No Available Managed Hosts';
                $scope.status_color = 'license-invalid';
            } else {
                $scope.license_status = 'Valid License';
                $scope.status_color = 'license-valid';
            }
        };

        $scope.setLicense = function(license_info, version) {
            this.license = license_info;
            this.version = version;
        };

        $scope.getLicense = function(){
            return this.license;
        };

        $scope.submitLicenseKey = function() {
            CheckLicense.postLicense($scope.license_json, $scope);
        };

        if ($scope.removeLicenseDataReady) {
            $scope.removeLicenseDataReady();
        }
        $scope.removeLicenseDataReady = $scope.$on('LicenseDataReady', function(e, data) {
            var html, version, eula, h;
            version = data.version.replace(/-.*$/,'');
            $scope.setLicense(data.license_info, version);
            html = $scope.getDefaultHTML(data.license_info);
            $scope.loadDefaultScope(data.license_info, version);
            eula = (data.eula) ? data.eula : "" ;

            e = angular.element(document.getElementById('license-modal-dialog'));
            e.empty().html(html);

            $scope.parseType = 'json';
            $scope.license_json = JSON.stringify($scope.license, null, ' ');
            $scope.eula = eula;
            $scope.eula_agreement = false;

            h = CheckLicense.getHTML($scope.getLicense(),true).body;
            $('#license-modal-dialog #license_tabs').append("
Update License
");
            $('#license-modal-dialog .tab-content').append("

");
            $('#license-modal-dialog #update_license').html(h);

            if ($scope.license_status === 'Invalid License Key' || $scope.license_status === 'Missing License Key') {
                $('#license_tabs li:eq(1)').hide();
                $('#license_tabs li:eq(2) a').tab('show');
            }

            $('#license_license_json').attr('ng-required' , 'true' );
            $('#license_eula_agreement_chbox').attr('ng-required' , 'true' );
            $('#license_form_submit_btn').attr('ng-disabled' , "license_form.$invalid" );
            var e = angular.element(document.getElementById('license-modal-dialog'));
            $compile(e)($scope);

            if (IsAdmin()) {
                setTimeout(function() {
                    TextareaResize({
                        scope: $scope,
                        textareaId: 'license_license_json',
                        modalId: 'license-modal-dialog',
                        formId: 'license-notification-body',
                        fld: 'license_json',
                        parse: true,
                        bottom_margin: 90,
                        onChange: function() { $scope.license_json_api_error = ''; }
                    });
                }, 300);
            }
            $('#license-ok-button').focus();
            $('#update_license_link').on('shown.bs.tab', function() {
                if (IsAdmin()) {
                    TextareaResize({
                        scope: $scope,
                        textareaId: 'license_license_json',
                        modalId: 'license-modal-dialog',
                        formId: 'license-notification-body',
                        fld: 'license_json',
                        bottom_margin: 90,
                        parse: true,
                        onChange: function() { $scope.license_json_api_error = ''; }
                    });
                }
            });
        });
        CheckLicense.GetLicense('LicenseDataReady', $scope);

    }

LicenseController.$inject = ['ClearScope', '$location', '$rootScope', '$compile', '$filter', 'GenerateForm', 'Rest', 'Alert',
'GetBasePath', 'ProcessErrors', 'FormatDate', 'Prompt', 'Empty', 'LicenseForm', 'IsAdmin', 'CreateDialog',
'CheckLicense', 'TextareaResize', '$scope'];
<commit_msg>fixed jshint error in license controller<commit_after>/************************************
 * Copyright (c) 2014 AnsibleWorks, Inc.
 *
 *
 *  Organizations.js
 *
 *  Controller functions for Organization model.
 *
 */
/**
 * @ngdoc function
 * @name controllers.function:Organizations
 * @description This controller's for the Organizations page
*/

export function LicenseController(ClearScope, $location, $rootScope, $compile, $filter, GenerateForm, Rest, Alert,
    GetBasePath, ProcessErrors, FormatDate, Prompt, Empty, LicenseForm, IsAdmin, CreateDialog, CheckLicense,
    TextareaResize, $scope) {

        ClearScope();

        $scope.getDefaultHTML = function(license_info) {
            var fld, html,
                self = this,
                generator = GenerateForm;

            self.form = angular.copy(LicenseForm);

            for (fld in self.form.fields) {
                if (fld !== 'time_remaining' && fld !== 'license_status' && fld !== 'tower_version') {
                    if (Empty(license_info[fld])) {
                        delete self.form.fields[fld];
                    }
                }
            }

            if (!IsAdmin()) {
                delete self.form.fields.license_key;
            }

            if (license_info.is_aws || Empty(license_info.license_date)) {
                delete self.form.fields.license_date;
                delete self.form.fields.time_remaining;
            }

            html = generator.buildHTML(self.form, { mode: 'edit', showButtons: false, breadCrumbs: false });
            return html;
        };

        $scope.loadDefaultScope = function(license_info, version) {
            var fld, dt, days, license,
                self = this;

            for (fld in self.form.fields) {
                if (!Empty(license_info[fld])) {
                    $scope[fld] = license_info[fld];
                }
            }

            $scope.tower_version = version;

            if ($scope.license_date) {
                dt = new Date(parseInt($scope.license_date, 10) * 1000); // expects license_date in seconds
                $scope.license_date = FormatDate(dt);
                $scope.time_remaining = parseInt($scope.time_remaining,10) * 1000;
                if ($scope.time_remaining < 0) {
                    days = 0;
                } else {
                    days = Math.floor($scope.time_remaining / 86400000);
                }
                $scope.time_remaining = (days!==1) ? $filter('number')(days, 0) + ' days' : $filter('number')(days, 0) + ' day'; // '1 day' and '0 days/2 days' or more
            }

            if (parseInt($scope.free_instances) <= 0) {
                $scope.free_instances_class = 'field-failure';
            } else {
                $scope.free_instances_class = 'field-success';
            }

            license = license_info;
            if (license.valid_key === undefined) {
                $scope.license_status = 'Missing License Key';
                $scope.status_color = 'license-invalid';
            } else if (!license.valid_key) {
                $scope.license_status = 'Invalid License Key';
                $scope.status_color = 'license-invalid';
            } else if (license.date_expired !== undefined && license.date_expired) {
                $scope.license_status = 'License Expired';
                $scope.status_color = 'license-expired';
            } else if (license.date_warning !== undefined && license.date_warning) {
                $scope.license_status = 'License Expiring Soon';
                $scope.status_color = 'license-warning';
            } else if (license.free_instances !== undefined && parseInt(license.free_instances) <= 0) {
                $scope.license_status = 'No Available Managed Hosts';
                $scope.status_color = 'license-invalid';
            } else {
                $scope.license_status = 'Valid License';
                $scope.status_color = 'license-valid';
            }
        };

        $scope.setLicense = function(license_info, version) {
            this.license = license_info;
            this.version = version;
        };

        $scope.getLicense = function(){
            return this.license;
        };

        $scope.submitLicenseKey = function() {
            CheckLicense.postLicense($scope.license_json, $scope);
        };

        if ($scope.removeLicenseDataReady) {
            $scope.removeLicenseDataReady();
        }
        $scope.removeLicenseDataReady = $scope.$on('LicenseDataReady', function(e, data) {
            var html, version, eula, h;
            version = data.version.replace(/-.*$/,'');
            $scope.setLicense(data.license_info, version);
            html = $scope.getDefaultHTML(data.license_info);
            $scope.loadDefaultScope(data.license_info, version);
            eula = (data.eula) ? data.eula : "" ;

            e = angular.element(document.getElementById('license-modal-dialog'));
            e.empty().html(html);

            $scope.parseType = 'json';
            $scope.license_json = JSON.stringify($scope.license, null, ' ');
            $scope.eula = eula;
            $scope.eula_agreement = false;

            h = CheckLicense.getHTML($scope.getLicense(),true).body;
            $('#license-modal-dialog #license_tabs').append("
Update License
");
            $('#license-modal-dialog .tab-content').append("

");
            $('#license-modal-dialog #update_license').html(h);

            if ($scope.license_status === 'Invalid License Key' || $scope.license_status === 'Missing License Key') {
                $('#license_tabs li:eq(1)').hide();
                $('#license_tabs li:eq(2) a').tab('show');
            }

            $('#license_license_json').attr('ng-required' , 'true' );
            $('#license_eula_agreement_chbox').attr('ng-required' , 'true' );
            $('#license_form_submit_btn').attr('ng-disabled' , "license_form.$invalid" );
            e = angular.element(document.getElementById('license-modal-dialog'));
            $compile(e)($scope);

            if (IsAdmin()) {
                setTimeout(function() {
                    TextareaResize({
                        scope: $scope,
                        textareaId: 'license_license_json',
                        modalId: 'license-modal-dialog',
                        formId: 'license-notification-body',
                        fld: 'license_json',
                        parse: true,
                        bottom_margin: 90,
                        onChange: function() { $scope.license_json_api_error = ''; }
                    });
                }, 300);
            }
            $('#license-ok-button').focus();
            $('#update_license_link').on('shown.bs.tab', function() {
                if (IsAdmin()) {
                    TextareaResize({
                        scope: $scope,
                        textareaId: 'license_license_json',
                        modalId: 'license-modal-dialog',
                        formId: 'license-notification-body',
                        fld: 'license_json',
                        bottom_margin: 90,
                        parse: true,
                        onChange: function() { $scope.license_json_api_error = ''; }
                    });
                }
            });
        });
        CheckLicense.GetLicense('LicenseDataReady', $scope);

    }

LicenseController.$inject = ['ClearScope', '$location', '$rootScope', '$compile', '$filter', 'GenerateForm', 'Rest', 'Alert',
'GetBasePath', 'ProcessErrors', 'FormatDate', 'Prompt', 'Empty', 'LicenseForm', 'IsAdmin', 'CreateDialog',
'CheckLicense', 'TextareaResize', '$scope'];
<|endoftext|>