<commit_before>module.exports = Cmds.addCommand({
    cmds: [';closeticket ', ';closesupport ', ';stopticket ', ';endticket '],

    requires: {
        guild: true,
        loud: false,
    },

    desc: 'Create a ticket to be viewed by Support',

    args: '([ticket_details])',

    example: 'Am I able to give away my whitelist?',

    // /////////////////////////////////////////////////////////////////////////////////////////

    func: async (cmd, args, msgObj, speaker, channel, guild) => {
        if (!Util.checkStaff(guild, speaker) && !Util.hasRoleName(speaker, 'Support')) {
            return Util.commandFailed(channel, speaker, 'This command can only be used by Support and above');
        }

        const data = Util.getDataFromString(args, [
            function (str) {
                return (str.match(/\d*(?:\.\d+)?/) || [])[0];
            },
        ], false);

        if (!data) return Util.commandFailed(channel, speaker, 'Invalid parameters');

        const numTicket = data[0];

        const foundTicket = ((await Data.getRecords(guild, 'tickets', { ticket_id: numTicket })) || [])[0];

        if (!foundTicket) return Util.commandFailed(channel, speaker, `Ticket #${numTicket} does not exist`);
        if (!foundTicket.active) return Util.commandFailed(channel, speaker, `Ticket #${numTicket} is already closed`);

        Data.updateRecords(guild, 'tickets', {
            ticket_id: numTicket,
        }, {
            active: 0,
        });

        const sendEmbedFields = [
            { name: 'Ticket Number', value: `<@${foundTicket.user_id}>`, inline: false },
            { name: 'Ticket User', value: `<@${foundTicket.user_id}>`, inline: false },
            { name: 'Ticket Date', value: Util.getDateString(new Date(foundTicket.open_tick)), inline: false },
        ];
        Util.sendEmbed(channel, 'Support Ticket Closed', null, Util.makeEmbedFooter(speaker), null, colGreen, sendEmbedFields);

        return true;
    },
});
<commit_msg>Synonym<commit_after>module.exports = Cmds.addCommand({
    cmds: [';closeticket ', ';closesupport ', ';stopticket ', ';endticket ', ';close '],

    requires: {
        guild: true,
        loud: false,
    },

    desc: 'Create a ticket to be viewed by Support',

    args: '([ticket_details])',

    example: 'Am I able to give away my whitelist?',

    // /////////////////////////////////////////////////////////////////////////////////////////

    func: async (cmd, args, msgObj, speaker, channel, guild) => {
        if (!Util.checkStaff(guild, speaker) && !Util.hasRoleName(speaker, 'Support')) {
            return Util.commandFailed(channel, speaker, 'This command can only be used by Support and above');
        }

        const data = Util.getDataFromString(args, [
            function (str) {
                return (str.match(/\d*(?:\.\d+)?/) || [])[0];
            },
        ], false);

        if (!data) return Util.commandFailed(channel, speaker, 'Invalid parameters');

        const numTicket = data[0];

        const foundTicket = ((await Data.getRecords(guild, 'tickets', { ticket_id: numTicket })) || [])[0];

        if (!foundTicket) return Util.commandFailed(channel, speaker, `Ticket #${numTicket} does not exist`);
        if (!foundTicket.active) return Util.commandFailed(channel, speaker, `Ticket #${numTicket} is already closed`);

        Data.updateRecords(guild, 'tickets', {
            ticket_id: numTicket,
        }, {
            active: 0,
        });

        const sendEmbedFields = [
            { name: 'Ticket Number', value: `<@${foundTicket.user_id}>`, inline: false },
            { name: 'Ticket User', value: `<@${foundTicket.user_id}>`, inline: false },
            { name: 'Ticket Date', value: Util.getDateString(new Date(foundTicket.open_tick)), inline: false },
        ];
        Util.sendEmbed(channel, 'Support Ticket Closed', null, Util.makeEmbedFooter(speaker), null, colGreen, sendEmbedFields);

        return true;
    },
});
<|endoftext|>


<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/samsung_maple",
    [
        "antie/devices/device",
        "antie/devices/mediaplayer/mediaplayer",
        "antie/runtimecontext"
    ],
    function(Device, MediaPlayer, RuntimeContext) {
        "use strict";

        /**
         * Main MediaPlayer implementation for Samsung devices implementing the Maple API.
         * Use this device modifier if a device implements the Samsung Maple media playback standard.
         * It must support creation of <object> elements with appropriate SAMSUNG_INFOLINK classids.
         * Those objects must expose an API in accordance with the Samsung Maple media specification.
         * @name antie.devices.mediaplayer.samsung_maple
         * @class
         * @extends antie.devices.mediaplayer.MediaPlayer.prototype
         */
        var Player = MediaPlayer.extend({

            init: function() {
                this._super();
                this._state = MediaPlayer.STATE.EMPTY;
                this._playerPlugin = document.getElementById('playerPlugin');
                this._deferSeekingTo = null;
                this._postBufferingState = null;
                this._tryingToPause = false;
            },

            /**
            * @inheritDoc
            */
            setSource: function (mediaType, url, mimeType) {
                if (this.getState() === MediaPlayer.STATE.EMPTY) {
                    this._type = mediaType;
                    this._source = url;
                    this._mimeType = mimeType;
                    this._registerEventHandlers();
                    this._toStopped();
                    this._currentTimeKnown = false;
                } else {
                    this._toError("Cannot set source unless in the '" + MediaPlayer.STATE.EMPTY + "' state");
                }
            },

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

                    case MediaPlayer.STATE.BUFFERING:
                        if (this._tryingToPause) {
                            this._tryingToPause = false;
                            this._toPlaying();
                        }
                        break;

                    case MediaPlayer.STATE.PAUSED:
                        this._playerPlugin.Resume();
                        this._toPlaying();
                        break;

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

            /**
            * @inheritDoc
            */
            playFrom: function (seconds) {
                this._postBufferingState = MediaPlayer.STATE.PLAYING;
                var seekingTo = this._range ? this._getClampedTime(seconds) : seconds;

                switch (this.getState()) {
                    case MediaPlayer.STATE.BUFFERING:
                        this._deferSeekingTo = seekingTo;
                        break;

                    case MediaPlayer.STATE.PLAYING:
                        this._toBuffering();
                        if (!this._currentTimeKnown) {
                            this._deferSeekingTo = seekingTo;
                        } else if (this._isNearToCurrentTime(seekingTo)) {
                            this._toPlaying();
                        } else {
                            this._seekTo(seekingTo);
                        }
                        break;

                    case MediaPlayer.STATE.PAUSED:
                        this._toBuffering();
                        if (!this._currentTimeKnown) {
                            this._deferSeekingTo = seekingTo;
                        } else if (this._isNearToCurrentTime(seekingTo)) {
                            this._playerPlugin.Resume();
                            this._toPlaying();
                        } else {
                            this._seekTo(seekingTo);
                            this._playerPlugin.Resume();
                        }
                        break;

                    case MediaPlayer.STATE.STOPPED:
                        this._setDisplayFullScreenForVideo();
                        this._playerPlugin.ResumePlay(this._source, seekingTo);
                        this._toBuffering();
                        break;

                    case MediaPlayer.STATE.COMPLETE:
                        this._playerPlugin.Stop();
                        this._setDisplayFullScreenForVideo();
                        this._playerPlugin.ResumePlay(this._source, seekingTo);
                        this._toBuffering();
                        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.BUFFERING:
                    case MediaPlayer.STATE.PAUSED:
                        break;

                    case MediaPlayer.STATE.PLAYING:
                        this._tryPauseWithStateTransition();
                        break;

                    default:
                        this._toError("Cannot pause 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._stopPlayer();
                        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 () {
                if (this.getState() === MediaPlayer.STATE.STOPPED) {
                    return undefined;
                } else {
                    return this._currentTime;
                }
            },

            /**
            * @inheritDoc
            */
            getRange: function () {
                return this._range;
            },

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

            _onFinishedBuffering: function() {
                if (this.getState() !== MediaPlayer.STATE.BUFFERING) {
                    return;
                } else if (!this._deferSeekingTo && this._postBufferingState === MediaPlayer.STATE.PAUSED) {
                    this._tryPauseWithStateTransition();
                } else if (!this._deferSeekingTo) {
                    this._toPlaying();
                }
            },

            _onDeviceError: function(message) {
                this._toError(message);
            },

            _onDeviceBuffering: function() {
                if (this.getState() === MediaPlayer.STATE.PLAYING) {
                    this._toBuffering();
                }
            },

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

            _stopPlayer: function() {
                this._playerPlugin.Stop();
                this._currentTimeKnown = false;
            },

            _tryPauseWithStateTransition: function() {
                var success = this._isSuccessCode(this._playerPlugin.Pause());
                if (success) {
                    this._toPaused();
                }

                this._tryingToPause = !success;
            },

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

            _onMetadata: function() {
                this._range = {
                    start: 0,
                    end: this._playerPlugin.GetDuration() / 1000
                };
            },

            _onCurrentTime: function(timeInMillis) {
                this._currentTime = timeInMillis / 1000;
                this._onStatus();
                this._currentTimeKnown = true;

                if (this._deferSeekingTo !== null) {
                    this._deferredSeek();
                }

                if (this._tryingToPause) {
                    this._tryPauseWithStateTransition();
                }
            },

            _deferredSeek: function() {
                var isNearCurrentTime = this._isNearToCurrentTime(this._deferSeekingTo);
                if (isNearCurrentTime) {
                    this._toPlaying();
                    this._deferSeekingTo = null;
                    return;
                }

                var seekResult = this._seekTo(this._getClampedTime(this._deferSeekingTo));
                if (seekResult) {
                    this._deferSeekingTo = null;
                }
            },

            _registerEventHandlers: function() {
                var self = this;

                window.SamsungMapleOnRenderError = function () {
                    self._onDeviceError("Media element emitted OnRenderError");
                };
                this._playerPlugin.OnRenderError = 'SamsungMapleOnRenderError';

                window.SamsungMapleOnConnectionFailed = function () {
                    self._onDeviceError("Media element emitted OnConnectionFailed");
                };
                this._playerPlugin.OnConnectionFailed = 'SamsungMapleOnConnectionFailed';

                window.SamsungMapleOnNetworkDisconnected = function () {
                    self._onDeviceError("Media element emitted OnNetworkDisconnected");
                };
                this._playerPlugin.OnNetworkDisconnected = 'SamsungMapleOnNetworkDisconnected';

                window.SamsungMapleOnStreamNotFound = function () {
                    self._onDeviceError("Media element emitted OnStreamNotFound");
                };
                this._playerPlugin.OnStreamNotFound = 'SamsungMapleOnStreamNotFound';

                window.SamsungMapleOnAuthenticationFailed = function () {
                    self._onDeviceError("Media element emitted OnAuthenticationFailed");
                };
                this._playerPlugin.OnAuthenticationFailed = 'SamsungMapleOnAuthenticationFailed';

                window.SamsungMapleOnRenderingComplete = function () {
                    self._onEndOfMedia();
                };
                this._playerPlugin.OnRenderingComplete = 'SamsungMapleOnRenderingComplete';

                window.SamsungMapleOnBufferingStart = function () {
                    self._onDeviceBuffering();
                };
                this._playerPlugin.OnBufferingStart = 'SamsungMapleOnBufferingStart';

                window.SamsungMapleOnBufferingComplete = function () {
                    self._onFinishedBuffering();
                };
                this._playerPlugin.OnBufferingComplete = 'SamsungMapleOnBufferingComplete';

                window.SamsungMapleOnStreamInfoReady = function () {
                    self._onMetadata();
                };
                this._playerPlugin.OnStreamInfoReady = 'SamsungMapleOnStreamInfoReady';

                window.SamsungMapleOnCurrentPlayTime = function (timeInMillis) {
                    self._onCurrentTime(timeInMillis);
                };
                this._playerPlugin.OnCurrentPlayTime = 'SamsungMapleOnCurrentPlayTime';

                this._onWindowHide = function () {
                    self.stop();
                };

                window.addEventListener('hide', this._onWindowHide, false);
                window.addEventListener('unload', this._onWindowHide, false);
            },

            _unregisterEventHandlers: function() {
                var eventHandlers = [
                    'SamsungMapleOnRenderError',
                    'SamsungMapleOnRenderingComplete',
                    'SamsungMapleOnBufferingStart',
                    'SamsungMapleOnBufferingComplete',
                    'SamsungMapleOnStreamInfoReady',
                    'SamsungMapleOnCurrentPlayTime',
                    'SamsungMapleOnConnectionFailed',
                    'SamsungMapleOnNetworkDisconnected',
                    'SamsungMapleOnStreamNotFound',
                    'SamsungMapleOnAuthenticationFailed'
                ];

                for (var i = 0; i < eventHandlers.length; i++){
                    var handler = eventHandlers[i];
                    var hook = handler.substring("SamsungMaple".length);
                    this._playerPlugin[hook] = undefined;

                    delete window[handler];
                }

                window.removeEventListener('hide', this._onWindowHide, false);
                window.removeEventListener('unload', this._onWindowHide, false);
            },

            _wipe: function () {
                this._stopPlayer();
                this._type = undefined;
                this._source = undefined;
                this._mimeType = undefined;
                this._currentTime = undefined;
                this._range = undefined;
                this._unregisterEventHandlers();
            },

            _seekTo: function(seconds) {
                var offset = seconds - this.getCurrentTime();
                var success = this._isSuccessCode(this._jump(offset));

                if (success) {
                    this._currentTime = seconds;
                }

                return success;
            },

            _jump: function (offsetSeconds) {
                if (offsetSeconds > 0) {
                    return this._playerPlugin.JumpForward(offsetSeconds);
                } else {
                    return this._playerPlugin.JumpBackward(Math.abs(offsetSeconds));
                }
            },

            _toStopped: function () {
                this._currentTime = 0;
                this._range = undefined;
                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);
            },

            _setDisplayFullScreenForVideo: function() {
                if (this._type === MediaPlayer.TYPE.VIDEO) {
                    var dimensions = RuntimeContext.getDevice().getScreenSize();
                    this._playerPlugin.SetDisplayArea(0, 0, dimensions.width, dimensions.height);
                }
            },

            _isSuccessCode: function(code) {
                var samsung2010ErrorCode = -1;
                return code && code !== samsung2010ErrorCode;
            },

            /**
             * @constant {Number} Time (in seconds) compared to current time within which seeking has no effect.
             * On a sample device (Samsung FoxP 2013), seeking by two seconds worked 90% of the time, but seeking
             * by 2.5 seconds was always seen to work.
             */
            CURRENT_TIME_TOLERANCE: 2.5
        });

        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>Refactor to simplify a compound conditional<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/samsung_maple",
    [
        "antie/devices/device",
        "antie/devices/mediaplayer/mediaplayer",
        "antie/runtimecontext"
    ],
    function(Device, MediaPlayer, RuntimeContext) {
        "use strict";

        /**
         * Main MediaPlayer implementation for Samsung devices implementing the Maple API.
         * Use this device modifier if a device implements the Samsung Maple media playback standard.
         * It must support creation of <object> elements with appropriate SAMSUNG_INFOLINK classids.
         * Those objects must expose an API in accordance with the Samsung Maple media specification.
         * @name antie.devices.mediaplayer.samsung_maple
         * @class
         * @extends antie.devices.mediaplayer.MediaPlayer.prototype
         */
        var Player = MediaPlayer.extend({

            init: function() {
                this._super();
                this._state = MediaPlayer.STATE.EMPTY;
                this._playerPlugin = document.getElementById('playerPlugin');
                this._deferSeekingTo = null;
                this._postBufferingState = null;
                this._tryingToPause = false;
            },

            /**
            * @inheritDoc
            */
            setSource: function (mediaType, url, mimeType) {
                if (this.getState() === MediaPlayer.STATE.EMPTY) {
                    this._type = mediaType;
                    this._source = url;
                    this._mimeType = mimeType;
                    this._registerEventHandlers();
                    this._toStopped();
                    this._currentTimeKnown = false;
                } else {
                    this._toError("Cannot set source unless in the '" + MediaPlayer.STATE.EMPTY + "' state");
                }
            },

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

                    case MediaPlayer.STATE.BUFFERING:
                        if (this._tryingToPause) {
                            this._tryingToPause = false;
                            this._toPlaying();
                        }
                        break;

                    case MediaPlayer.STATE.PAUSED:
                        this._playerPlugin.Resume();
                        this._toPlaying();
                        break;

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

            /**
            * @inheritDoc
            */
            playFrom: function (seconds) {
                this._postBufferingState = MediaPlayer.STATE.PLAYING;
                var seekingTo = this._range ? this._getClampedTime(seconds) : seconds;

                switch (this.getState()) {
                    case MediaPlayer.STATE.BUFFERING:
                        this._deferSeekingTo = seekingTo;
                        break;

                    case MediaPlayer.STATE.PLAYING:
                        this._toBuffering();
                        if (!this._currentTimeKnown) {
                            this._deferSeekingTo = seekingTo;
                        } else if (this._isNearToCurrentTime(seekingTo)) {
                            this._toPlaying();
                        } else {
                            this._seekTo(seekingTo);
                        }
                        break;

                    case MediaPlayer.STATE.PAUSED:
                        this._toBuffering();
                        if (!this._currentTimeKnown) {
                            this._deferSeekingTo = seekingTo;
                        } else if (this._isNearToCurrentTime(seekingTo)) {
                            this._playerPlugin.Resume();
                            this._toPlaying();
                        } else {
                            this._seekTo(seekingTo);
                            this._playerPlugin.Resume();
                        }
                        break;

                    case MediaPlayer.STATE.STOPPED:
                        this._setDisplayFullScreenForVideo();
                        this._playerPlugin.ResumePlay(this._source, seekingTo);
                        this._toBuffering();
                        break;

                    case MediaPlayer.STATE.COMPLETE:
                        this._playerPlugin.Stop();
                        this._setDisplayFullScreenForVideo();
                        this._playerPlugin.ResumePlay(this._source, seekingTo);
                        this._toBuffering();
                        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.BUFFERING:
                    case MediaPlayer.STATE.PAUSED:
                        break;

                    case MediaPlayer.STATE.PLAYING:
                        this._tryPauseWithStateTransition();
                        break;

                    default:
                        this._toError("Cannot pause 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._stopPlayer();
                        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 () {
                if (this.getState() === MediaPlayer.STATE.STOPPED) {
                    return undefined;
                } else {
                    return this._currentTime;
                }
            },

            /**
            * @inheritDoc
            */
            getRange: function () {
                return this._range;
            },

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

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

                if (this._deferSeekingTo === null) {
                    if (this._postBufferingState === MediaPlayer.STATE.PAUSED) {
                        this._tryPauseWithStateTransition();
                    } else {
                        this._toPlaying();
                    }
                }
            },

            _onDeviceError: function(message) {
                this._toError(message);
            },

            _onDeviceBuffering: function() {
                if (this.getState() === MediaPlayer.STATE.PLAYING) {
                    this._toBuffering();
                }
            },

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

            _stopPlayer: function() {
                this._playerPlugin.Stop();
                this._currentTimeKnown = false;
            },

            _tryPauseWithStateTransition: function() {
                var success = this._isSuccessCode(this._playerPlugin.Pause());
                if (success) {
                    this._toPaused();
                }

                this._tryingToPause = !success;
            },

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

            _onMetadata: function() {
                this._range = {
                    start: 0,
                    end: this._playerPlugin.GetDuration() / 1000
                };
            },

            _onCurrentTime: function(timeInMillis) {
                this._currentTime = timeInMillis / 1000;
                this._onStatus();
                this._currentTimeKnown = true;

                if (this._deferSeekingTo !== null) {
                    this._deferredSeek();
                }

                if (this._tryingToPause) {
                    this._tryPauseWithStateTransition();
                }
            },

            _deferredSeek: function() {
                var isNearCurrentTime = this._isNearToCurrentTime(this._deferSeekingTo);
                if (isNearCurrentTime) {
                    this._toPlaying();
                    this._deferSeekingTo = null;
                    return;
                }

                var seekResult = this._seekTo(this._getClampedTime(this._deferSeekingTo));
                if (seekResult) {
                    this._deferSeekingTo = null;
                }
            },

            _registerEventHandlers: function() {
                var self = this;

                window.SamsungMapleOnRenderError = function () {
                    self._onDeviceError("Media element emitted OnRenderError");
                };
                this._playerPlugin.OnRenderError = 'SamsungMapleOnRenderError';

                window.SamsungMapleOnConnectionFailed = function () {
                    self._onDeviceError("Media element emitted OnConnectionFailed");
                };
                this._playerPlugin.OnConnectionFailed = 'SamsungMapleOnConnectionFailed';

                window.SamsungMapleOnNetworkDisconnected = function () {
                    self._onDeviceError("Media element emitted OnNetworkDisconnected");
                };
                this._playerPlugin.OnNetworkDisconnected = 'SamsungMapleOnNetworkDisconnected';

                window.SamsungMapleOnStreamNotFound = function () {
                    self._onDeviceError("Media element emitted OnStreamNotFound");
                };
                this._playerPlugin.OnStreamNotFound = 'SamsungMapleOnStreamNotFound';

                window.SamsungMapleOnAuthenticationFailed = function () {
                    self._onDeviceError("Media element emitted OnAuthenticationFailed");
                };
                this._playerPlugin.OnAuthenticationFailed = 'SamsungMapleOnAuthenticationFailed';

                window.SamsungMapleOnRenderingComplete = function () {
                    self._onEndOfMedia();
                };
                this._playerPlugin.OnRenderingComplete = 'SamsungMapleOnRenderingComplete';

                window.SamsungMapleOnBufferingStart = function () {
                    self._onDeviceBuffering();
                };
                this._playerPlugin.OnBufferingStart = 'SamsungMapleOnBufferingStart';

                window.SamsungMapleOnBufferingComplete = function () {
                    self._onFinishedBuffering();
                };
                this._playerPlugin.OnBufferingComplete = 'SamsungMapleOnBufferingComplete';

                window.SamsungMapleOnStreamInfoReady = function () {
                    self._onMetadata();
                };
                this._playerPlugin.OnStreamInfoReady = 'SamsungMapleOnStreamInfoReady';

                window.SamsungMapleOnCurrentPlayTime = function (timeInMillis) {
                    self._onCurrentTime(timeInMillis);
                };
                this._playerPlugin.OnCurrentPlayTime = 'SamsungMapleOnCurrentPlayTime';

                this._onWindowHide = function () {
                    self.stop();
                };

                window.addEventListener('hide', this._onWindowHide, false);
                window.addEventListener('unload', this._onWindowHide, false);
            },

            _unregisterEventHandlers: function() {
                var eventHandlers = [
                    'SamsungMapleOnRenderError',
                    'SamsungMapleOnRenderingComplete',
                    'SamsungMapleOnBufferingStart',
                    'SamsungMapleOnBufferingComplete',
                    'SamsungMapleOnStreamInfoReady',
                    'SamsungMapleOnCurrentPlayTime',
                    'SamsungMapleOnConnectionFailed',
                    'SamsungMapleOnNetworkDisconnected',
                    'SamsungMapleOnStreamNotFound',
                    'SamsungMapleOnAuthenticationFailed'
                ];

                for (var i = 0; i < eventHandlers.length; i++){
                    var handler = eventHandlers[i];
                    var hook = handler.substring("SamsungMaple".length);
                    this._playerPlugin[hook] = undefined;

                    delete window[handler];
                }

                window.removeEventListener('hide', this._onWindowHide, false);
                window.removeEventListener('unload', this._onWindowHide, false);
            },

            _wipe: function () {
                this._stopPlayer();
                this._type = undefined;
                this._source = undefined;
                this._mimeType = undefined;
                this._currentTime = undefined;
                this._range = undefined;
                this._unregisterEventHandlers();
            },

            _seekTo: function(seconds) {
                var offset = seconds - this.getCurrentTime();
                var success = this._isSuccessCode(this._jump(offset));

                if (success) {
                    this._currentTime = seconds;
                }

                return success;
            },

            _jump: function (offsetSeconds) {
                if (offsetSeconds > 0) {
                    return this._playerPlugin.JumpForward(offsetSeconds);
                } else {
                    return this._playerPlugin.JumpBackward(Math.abs(offsetSeconds));
                }
            },

            _toStopped: function () {
                this._currentTime = 0;
                this._range = undefined;
                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);
            },

            _setDisplayFullScreenForVideo: function() {
                if (this._type === MediaPlayer.TYPE.VIDEO) {
                    var dimensions = RuntimeContext.getDevice().getScreenSize();
                    this._playerPlugin.SetDisplayArea(0, 0, dimensions.width, dimensions.height);
                }
            },

            _isSuccessCode: function(code) {
                var samsung2010ErrorCode = -1;
                return code && code !== samsung2010ErrorCode;
            },

            /**
             * @constant {Number} Time (in seconds) compared to current time within which seeking has no effect.
             * On a sample device (Samsung FoxP 2013), seeking by two seconds worked 90% of the time, but seeking
             * by 2.5 seconds was always seen to work.
             */
            CURRENT_TIME_TOLERANCE: 2.5
        });

        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>var version = 0.5;
var ddp_server = "localhost";
var ddp_port = 3000;
var DDPClient = require("ddp");
var debug_mode = false;

var Telismo_instance = function(apiKey) {

	var self = this;

	var Telismo_DDP = new DDPClient({
	  host: ddp_server,
	  port: ddp_port,
	  auto_reconnect: true,
	  auto_reconnect_timer: 500,
	  use_ejson: true
	});

	var connected = false;
	var _opsqueue = [];
	var api_ok = false;

	Telismo_DDP.connect(function(error) {
		if (error) {
			if(debug_mode) console.log('Cannot connect to Telismo Server!');
			return;
		}

		Telismo_DDP.call("api/login", [apiKey], function(err,result) {
			api_ok = true;
		});

		if(debug_mode) console.log('Connected to Telismo Server');

		Telismo_DDP.subscribe('api', [], function() {
			if(debug_mode) console.log('Ready. When you are ready to end the session please use ctrl+c');
		});

		connected = true;

		//Run Queued Tasks
		for(var i = 0; i < _opsqueue.length; i++) {
			_opsqueue[i]();
		}
	});

	var _callbacks = [];

	Telismo_DDP.on('message', function(msg) {
		var JSONMessage = JSON.parse(msg);
		if(JSONMessage.msg == "added" && JSONMessage.collection == "calls") {
			var doc = JSONMessage.fields;
			doc._id = JSONMessage.id;

			if(doc._id in _callbacks) {
				var callback = _callbacks[doc._id];
				if(doc.error) {
					if(callback) callback({errors: doc.error, status: doc.status});
				}else{
					if(callback) callback(null, doc.output);
				}
			}
			else {
				if(doc.error) {
					if(self.callback) self.callback({errors: doc.error, status: doc.status});
				}else{
					if(self.callback) self.callback(null, doc);
				}
			}

		}
	});

	this._enqueue = function(method) {
		_opsqueue.push(method);
	}

	this._call = function(params, callback) {
		Telismo_DDP.call("api/new", [apiKey, params], function(err,result) {
			if(result && result.success == true) {
				if(result.id instanceof Array) {
					for(var i = 0; i<result.id.length; i++) {
						_callbacks[result.id] = callback
					}
				}else{
					_callbacks[result.id] = callback;
				}
			}
		});

	}

	this.call = function(params, callback) {
		var queued = function() {
			self._call(params, callback);
		}

		if(connected) {
			queued();
		}else{
			self._enqueue(queued);
		}
	}

	this.list = function() {
		var result = Telismo_DDP.call("api/list", apiKey, params);
		if(result && result.success == true) {
			return result;
		}
		return [];
	}

	this.calls = function() {
		return CallDocs;
	}

	this.callback = function(callData) {

	}

	return this;
}

var Telismo = function(apiKey) {
	return new Telismo_instance(apiKey);
}

module.exports = Telismo;<commit_msg>Fix reconnection issue<commit_after>var version = 0.5;
var ddp_server = "localhost";
var ddp_port = 3000;
var DDPClient = require("ddp");
var debug_mode = false;

var Telismo_instance = function(apiKey) {

	var self = this;

	var Telismo_DDP = new DDPClient({
	  host: ddp_server,
	  port: ddp_port,
	  auto_reconnect: true,
	  auto_reconnect_timer: 500,
	  use_ejson: true
	});

	var connected = false;
	var _opsqueue = [];
	var api_ok = false;

	Telismo_DDP.connect(function(error) {
		if (error) {
			if(debug_mode) console.log('Cannot connect to Telismo Server!');
			return;
		}

		Telismo_DDP.call("api/login", [apiKey], function(err,result) {
			api_ok = true;
		});

		if(debug_mode) console.log('Connected to Telismo Server');

		Telismo_DDP.subscribe('api', [], function() {
			if(debug_mode) console.log('Ready. When you are ready to end the session please use ctrl+c');
		});

		connected = true;

		//Run Queued Tasks
		for(var i = 0; i < _opsqueue.length; i++) {
			_opsqueue[i]();
			delete _opsqueue[i];
		}
	});

	var _callbacks = [];

	Telismo_DDP.on('message', function(msg) {
		var JSONMessage = JSON.parse(msg);
		if(JSONMessage.msg == "added" && JSONMessage.collection == "calls") {
			var doc = JSONMessage.fields;
			doc._id = JSONMessage.id;

			if(doc._id in _callbacks) {
				var callback = _callbacks[doc._id];
				if(doc.error) {
					if(callback) callback({errors: doc.error, status: doc.status});
				}else{
					if(callback) callback(null, doc.output);
				}
			}
			else {
				if(doc.error) {
					if(self.callback) self.callback({errors: doc.error, status: doc.status});
				}else{
					if(self.callback) self.callback(null, doc);
				}
			}

		}
	});

	this._enqueue = function(method) {
		_opsqueue.push(method);
	}

	this._call = function(params, callback) {
		Telismo_DDP.call("api/new", [apiKey, params], function(err,result) {
			if(result && result.success == true) {
				if(result.id instanceof Array) {
					for(var i = 0; i<result.id.length; i++) {
						_callbacks[result.id] = callback
					}
				}else{
					_callbacks[result.id] = callback;
				}
			}
		});

	}

	this.call = function(params, callback) {
		var queued = function() {
			self._call(params, callback);
		}

		if(connected) {
			queued();
		}else{
			self._enqueue(queued);
		}
	}

	this.list = function() {
		var result = Telismo_DDP.call("api/list", apiKey, params);
		if(result && result.success == true) {
			return result;
		}
		return [];
	}

	this.calls = function() {
		return CallDocs;
	}

	this.callback = function(callData) {

	}

	return this;
}

var Telismo = function(apiKey) {
	return new Telismo_instance(apiKey);
}

module.exports = Telismo;<|endoftext|>


<commit_before>'use strict';

var $CleanContextMenuView = require('./clean-context-menu-view.js');
var $Debug = require('./debug.js');
var $debug = new $Debug($Debug.LOG);
var $atom = require('atom');

function removeCommands() {
    var commands,
        menus,
        menu,
        i,
        item,
        items;
    // remove menus from the menu bar
    commands = {
        'tabs:split-up': true,
        'tabs:split-down': true,
        'tabs:split-right': true,
        'tabs:split-left': true,
        'pane:split-up': true,
        'pane:split-down': true,
        'pane:split-right': true,
        'pane:split-left': true,
        'pane:close': true,
        'core:undo': true,
        'core:redo': true,
        // 'core:cut': true,
        // 'core:copy': true,
        // 'core:paste': true,
        'core:delete': true,
        'core:select-all': true,
        'encoding-selector:show': true,
        'grammar-selector': true,
        'spell-check:correct-misspelling': true,
        'symbols-view:go-to-declaration': true,
        'minimap:toggle': true,
        'tree-view:duplicate': true,
        'tree-view:open-selected-entry-up': true,
        'tree-view:open-selected-entry-down': true,
        'tree-view:open-selected-entry-left': true,
        'tree-view:open-selected-entry-right': true,
        'tree-view:copy-full-path': true,
        'tree-view:copy-project-path': true,
        'tree-view:open-in-new-window': true,
        'tree-view:cut': true,
        'tree-view:copy': true,
        'tree-view:paste': true,
        'tabs:close-all-tabs': true,
        'tabs:close-saved-tabs': true,
        'tabs:close-tabs-to-right': true,
        'tabs:close-other-tabs': true
    };
    $debug.log('removeCommands');
    menus = atom.contextMenu.itemSets;
    for (menu in menus) {
        items = menus[menu].items;
        $debug.detail(menus[menu].selector);
        for (i = items.length; i--;) {
            item = items[i];
            if (!item) {
                continue;
            }
            if (item.command in commands) {
                $debug.detail('  x', item.command);
                // items.splice(i, 1);
            } else {
                $debug.detail('   ', item.command);
            }
        }
    }
}

var CleanContextMenu = {
    activate: function (state) {
        this.view = new $CleanContextMenuView(state.referenceViewState);
        this.panel = atom.workspace.addRightPanel({
            item: this.view.getElement(),
            visible: false
        });
        setTimeout(removeCommands, 500);

        this.subscriptions = new $atom.CompositeDisposable();
        this.subscriptions.add(
            atom.commands.add(
                'atom-workspace',
                {
                    'clean-context-menu:toggle': () => {
                        this.toggle();
                    }
                }
            )
        );
    },
    deactivate: function () {
        this.panel.destroy();
        this.view.destroy();
    },
    toggle: function () {
        if (this.panel.isVisible()) {
            this.panel.hide();
        } else {
            this.panel.show();
        }
    }
};
module.exports = CleanContextMenu;
<commit_msg>Move "split panes" to submenu<commit_after>'use strict';

var $CleanContextMenuView = require('./clean-context-menu-view.js');
var $Debug = require('./debug.js');
var $debug = new $Debug($Debug.DETAIL);
var $atom = require('atom');

function removeItems(commands) {
    var removed = [],
        menus,
        menu,
        i,
        item,
        items;
    // remove menus from the menu bar
    $debug.log('removeItems');
    menus = atom.contextMenu.itemSets;
    for (menu in menus) {
        items = menus[menu].items;
        $debug.detail(menus[menu].selector);
        for (i = items.length; i--;) {
            item = items[i];
            if (!item) {
                continue;
            }
            if (commands.indexOf(item.command) >= 0) {
                item.originMenu = menus[menu];
                removed.push(items.splice(i, 1)[0]);
                $debug.detail('  x', item.command);
            } else {
                $debug.detail('   ', item.command);
            }
        }
    }
    if (removed.length < 1) {
        $debug.warn('Could not find any items to remove');
    }
    return removed;
}

function moveToSubMenu(name, commands) {
    var items,
        groups = {};

    $debug.log('moveToSubMenu', commands);
    items = removeItems(commands);
    $debug.detail('items collected', items);
    for (let i = 0, l = items.length; i < l; i++) {
        let selector = items[i].originMenu.selector;
        if (!groups[selector]) {
            groups[selector] = [
                {
                    label: name,
                    submenu: []
                }
            ];
        }
        groups[selector][0].submenu.push(items[i]);
    }
    atom.contextMenu.add(groups);
}
function removeCommands() {
    $debug.log('removeCommands');
    moveToSubMenu(
        'Split Panes',
        [
            'tabs:split-up',
            'tabs:split-down',
            'tabs:split-right',
            'tabs:split-left',
            'pane:split-up',
            'pane:split-down',
            'pane:split-right',
            'pane:split-left'
        ]
    );
}

var CleanContextMenu = {
    config: {
        splitPanes: {
            title: 'Split Panes',
            description: 'How the split pane actions show up',
            type: 'string',
            default: 'submenu',
            enum: [
                'hidden',
                'normal',
                'submenu'
            ]
        }
    },
    activate: function (state) {
        this.view = new $CleanContextMenuView(state.referenceViewState);
        this.panel = atom.workspace.addRightPanel({
            item: this.view.getElement(),
            visible: false
        });
        setTimeout(removeCommands, 500);

        // this.subscriptions = new $atom.CompositeDisposable();
        // this.subscriptions.add(
        //     atom.commands.add(
        //         'atom-workspace',
        //         {
        //             'clean-context-menu:toggle': () => {
        //                 this.toggle();
        //             }
        //         }
        //     )
        // );
    },
    deactivate: function () {
        this.panel.destroy();
        this.view.destroy();
    },
    toggle: function () {
        // if (this.panel.isVisible()) {
        //     this.panel.hide();
        // } else {
        //     this.panel.show();
        // }

    }
};
module.exports = CleanContextMenu;
<|endoftext|>


<commit_before>#!/usr/bin/env node

const cli = require('cli')
const GGF = require('./main.js')

let ggf = new GGF

// Default Config
let dc = ggf.getConfig()

cli.enable('help')

let res = cli.parse({
	input:       ['i', 'Input URL of CSS with fonts', 'url'],
	output:      ['o', 'Output directory', 'string', dc.outputDir],
	path:        ['p', 'Path placed before every source of font in CSS', 'string', dc.path],
	css:         ['c', 'Name of CSS file', 'string', dc.cssFile],
	template:    ['t', 'Template of font filename', 'string',  dc.template],
	useragent:   ['u', 'User-agent used at every connection', 'string', false],
	quiet:       ['q', 'Don\'t displays a lot of useful information', 'true', false],
	base64:      ['b', 'Save fonts inside CSS file as base64 URIs', 'true', false],
	overwriting: ['w', 'Allows overwrite existing files', 'true', false],
	simulate:    ['s', 'Simulation; No file will be saved', 'true', false]
})

ggf.download(
	res.input,
	{
		outputDir: res.output,
	     	 path: res.path,
		  cssFile: res.css,
		userAgent: res.useragent || dc.userAgent,
		  verbose: !res.quiet,
	overwriting: res.overwriting,
	     base64: res.base64,
	   simulate: res.simulate,
		 template: res.template
	}
).catch(e => {
	console.error(e)
})
<commit_msg>Prepare cli.js for strict-ssl<commit_after>#!/usr/bin/env node

const cli = require('cli')
const GGF = require('./main.js')

let ggf = new GGF

// Default Config
let dc = ggf.getConfig()

cli.enable('help')

let res = cli.parse({
	input:            ['i', 'Input URL of CSS with fonts', 'url'],
	output:           ['o', 'Output directory', 'string', dc.outputDir],
	path:             ['p', 'Path placed before every source of font in CSS', 'string', dc.path],
	css:              ['c', 'Name of CSS file', 'string', dc.cssFile],
	template:         ['t', 'Template of font filename', 'string',  dc.template],
	useragent:        ['u', 'User-agent used at every connection', 'string', false],
	quiet:            ['q', 'Don\'t displays a lot of useful information'],
	base64:           ['b', 'Save fonts inside CSS file as base64 URIs'],
	'non-strict-ssl': [false, [
		'Force to accepts only valid SSL certificates; in some cases,',
		'such proxy or self-signed certificates should be turned off',
	].join('')],
	overwriting:      ['w', 'Allows overwrite existing files'],
	'print-options':  [false, 'Shows result options object without performing any action'],
	simulate:         ['s', 'Simulation; No file will be saved']
})

const options = {
	outputDir: res.output,
     	 path: res.path,
	  cssFile: res.css,
	userAgent: res.useragent || dc.userAgent,
	  verbose: !Boolean(res.quiet),
  overwriting: Boolean(res.overwriting),
    strictSSL: !Boolean(res['non-strict-ssl']),
       base64: Boolean(res.base64),
     simulate: Boolean(res.simulate),
	 template: res.template
};

if (Boolean(res['print-options'])) {
	console.log(options);
	return;
}

ggf.download(
	res.input,
	{
		outputDir: res.output,
	     	 path: res.path,
		  cssFile: res.css,
		userAgent: res.useragent || dc.userAgent,
		  verbose: !Boolean(res.quiet),
	  overwriting: Boolean(res.overwriting),
	    strictSSL: !Boolean(res['non-strict-ssl']),
	       base64: Boolean(res.base64),
	     simulate: Boolean(res.simulate),
		 template: res.template
	}
).catch(e => {
	console.error(e)
})
<|endoftext|>


<commit_before>// AMD module id = dijit
//
// This is a package main module for the dijit package. The dijit package is somewhat unusual
// in that is it currently constructed to just provide an empty object.
//

// for now, we publish dijit into the global namespace because so many tests and apps expect it.
var dijit;
define(["dojo"], function(dojo) {
	// the current dojo bootstrap defines dijit; this may change and this module provides a little
	// future-proof with the disjunction.
	dijit= dojo._dijit || {};
	return dijit;
});
<commit_msg>fixes #12200; repairs dojo/i18n error when using AMD loader; improves build output for dojo/query, !strict<commit_after>// AMD module id = dijit
//
// This is a package main module for the dijit package. The dijit package is somewhat unusual
// in that is it currently constructed to just provide an empty object.
//

// for now, we publish dijit into the global namespace because so many tests and apps expect it.
define(["dojo"], function(dojo) {
	// the current dojo bootstrap defines dijit; this may change and this module provides a little
	// future-proof with the disjunction.
	dijit= dojo._dijit || {};
	return dijit;
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

var _ = require('underscore');
var fs = require('fs');
var program = require('commander');

var pkg = JSON.parse(fs.readFileSync(__dirname + '/package.json'));
var ProxyLists = require('./index');
var validOutputFormats = ['json', 'csv', 'txt'];
var proxyFieldNames = ['source', 'ipAddress', 'port', 'country', 'protocols', 'anonymityLevel'];

function list(value) {
	return value.split(',');
}

function value(value) {
	return value;
}

program
	.version(pkg.version)
	.description(pkg.description);

program
	.command('getProxies')
		.option(
			'-a, --anonymity-levels <list>',
			'Get proxies with these anonymity levels [' + ProxyLists._anonymityLevels.join(', ') + ']',
			list,
			null
		)
		.option(
			'-c, --countries <list>',
			'Get proxies from these countries [us, ca, cz, ..]',
			list,
			null
		)
		.option(
			'-p, --protocols <list>',
			'Get proxies that support these protocols [' + ProxyLists._protocols.join(', ') + ']',
			list,
			null
		)
		.option(
			'-s, --sources-white-list <list>',
			'Get proxies from these sources only [' + _.keys(ProxyLists._sources).join(', ') + ']',
			list,
			null
		)
		.option(
			'-x, --sources-black-list <list>',
			'Do not get proxies from these sources [' + _.keys(ProxyLists._sources).join(', ') + ']',
			list,
			null
		)
		.option(
			'-f, --output-file [value]',
			'File to which the output will be written',
			value,
			'proxies'
		)
		.option(
			'-F, --output-format [value]',
			'Format in which the output will be written [' + validOutputFormats.join(', ') + ']',
			value,
			'txt'
		)
		.option(
			'--series',
			'Perform all asynchronous operations in series'
		)
		.option(
			'--sample',
			'Get a sample of proxies from each source'
		)
		.option(
			'--stdout',
			'Write to STDOUT instead of a file'
		)
		.option(
			'-l, --log-file [value]',
			'File to which will be logged when writing to stdout',
			value,
			'proxy-lists.log'
		)
		.action(function() {

			var outputFormat = this.outputFormat;
			var stdout = this.stdout;
			var outputFile = process.cwd() + '/' + this.outputFile + '.' + this.outputFormat;
			var writeStream;

			if(!stdout) {
				writeStream = fs.createWriteStream(outputFile);
			}
			else {
				outputFile = 'STDOUT';
				var logFile = process.cwd() + '/' + this.logFile;
				var logStream = fs.createWriteStream(logFile);
				writeStream = {
					write: function(data) {
						process.stdout.write(data + '\n');
					},
					end: function() {},
					on: function() {}
				};
			}

			function log(message) {
				if(stdout) {
					logStream.write(message + '\n');
				}
				else {
					console.log(message);
				}
			}

			writeStream.on('error', console.error.bind(console));
			var numWriting = 0;
			var wroteData = false;
			var ended = false;

			function onData(data) {

				if (!_.isEmpty(data)) {

					numWriting++;

					switch (outputFormat) {

						case 'json':

							data = _.map(data, function(row) {
								return JSON.stringify(row);
							});

							writeStream.write((wroteData ? ',' : '') + data.join(','));
							break;

						case 'csv':

							data = _.map(data, function(row) {
								return _.map(proxyFieldNames, function(fieldName) {
									return _.isArray(row[fieldName]) ? row[fieldName].join('/') : row[fieldName];
								}).join(',');
							});

							writeStream.write('\n' + data.join('\n'));
							break;

						case 'txt':

							data = _.map(data, function(row) {
								return row.ipAddress + ':' + row.port;
							});

							writeStream.write((wroteData ? '\n' : '') + data.join('\n'));
							break;
					}

					numWriting--;
					wroteData = true;
				}

				endIfDoneWritingData();
			}

			function onEnd() {

				ended = true;
				endIfDoneWritingData();
			}

			function endIfDoneWritingData() {

				if (ended && !numWriting) {
					endOutput();
				}
			}

			var startOutput = _.once(function() {

				log('Writing output to ' + outputFile);

				switch (outputFormat) {

					case 'json':
						writeStream.write('[');
						break;

					case 'csv':
						writeStream.write(proxyFieldNames.join(','));
						break;
				}
			});

			var endOutput = _.once(function() {

				switch (outputFormat) {
					case 'json':
						writeStream.write(']');
						break;
				}

				writeStream.end();
				log('Done!');

				if(logStream) {
					logStream.end();
				}
			});

			log('Getting proxies...');

			var options = _.pick(this, [
				'anonymityLevels',
				'countries',
				'protocols',
				'sourcesWhiteList',
				'sourcesBlackList',
				'sample',
				'series'
			]);

			var gettingProxies = ProxyLists.getProxies(options);
			gettingProxies.on('data', onData);
			gettingProxies.on('error', function(error) {
				console.error(error);
			});
			gettingProxies.on('end', onEnd);

			startOutput();
		});

program.parse(process.argv);
<commit_msg>Minor code style fixes<commit_after>#!/usr/bin/env node

'use strict';

var _ = require('underscore');
var fs = require('fs');
var program = require('commander');

var pkg = JSON.parse(fs.readFileSync(__dirname + '/package.json'));
var ProxyLists = require('./index');
var validOutputFormats = ['json', 'csv', 'txt'];
var proxyFieldNames = ['source', 'ipAddress', 'port', 'country', 'protocols', 'anonymityLevel'];

function list(value) {
	return value.split(',');
}

function value(value) {
	return value;
}

program
	.version(pkg.version)
	.description(pkg.description);

program
	.command('getProxies')
		.option(
			'-a, --anonymity-levels <list>',
			'Get proxies with these anonymity levels [' + ProxyLists._anonymityLevels.join(', ') + ']',
			list,
			null
		)
		.option(
			'-c, --countries <list>',
			'Get proxies from these countries [us, ca, cz, ..]',
			list,
			null
		)
		.option(
			'-p, --protocols <list>',
			'Get proxies that support these protocols [' + ProxyLists._protocols.join(', ') + ']',
			list,
			null
		)
		.option(
			'-s, --sources-white-list <list>',
			'Get proxies from these sources only [' + _.keys(ProxyLists._sources).join(', ') + ']',
			list,
			null
		)
		.option(
			'-x, --sources-black-list <list>',
			'Do not get proxies from these sources [' + _.keys(ProxyLists._sources).join(', ') + ']',
			list,
			null
		)
		.option(
			'-f, --output-file [value]',
			'File to which the output will be written',
			value,
			'proxies'
		)
		.option(
			'-F, --output-format [value]',
			'Format in which the output will be written [' + validOutputFormats.join(', ') + ']',
			value,
			'txt'
		)
		.option(
			'--series',
			'Perform all asynchronous operations in series'
		)
		.option(
			'--sample',
			'Get a sample of proxies from each source'
		)
		.option(
			'--stdout',
			'Write to STDOUT instead of a file'
		)
		.option(
			'-l, --log-file [value]',
			'File to which will be logged when writing to stdout',
			value,
			'proxy-lists.log'
		)
		.action(function() {

			var outputFormat = this.outputFormat;
			var stdout = this.stdout;
			var outputFile = process.cwd() + '/' + this.outputFile + '.' + this.outputFormat;
			var writeStream;

			if (!stdout) {
				writeStream = fs.createWriteStream(outputFile);
			} else {
				outputFile = 'STDOUT';
				var logFile = process.cwd() + '/' + this.logFile;
				var logStream = fs.createWriteStream(logFile);
				writeStream = {
					write: function(data) {
						process.stdout.write(data + '\n');
					},
					end: function() {},
					on: function() {}
				};
			}

			function log(message) {

				if (stdout) {
					logStream.write(message + '\n');
				} else {
					console.log(message);
				}
			}

			writeStream.on('error', console.error.bind(console));
			var numWriting = 0;
			var wroteData = false;
			var ended = false;

			function onData(data) {

				if (!_.isEmpty(data)) {

					numWriting++;

					switch (outputFormat) {

						case 'json':

							data = _.map(data, function(row) {
								return JSON.stringify(row);
							});

							writeStream.write((wroteData ? ',' : '') + data.join(','));
							break;

						case 'csv':

							data = _.map(data, function(row) {
								return _.map(proxyFieldNames, function(fieldName) {
									return _.isArray(row[fieldName]) ? row[fieldName].join('/') : row[fieldName];
								}).join(',');
							});

							writeStream.write('\n' + data.join('\n'));
							break;

						case 'txt':

							data = _.map(data, function(row) {
								return row.ipAddress + ':' + row.port;
							});

							writeStream.write((wroteData ? '\n' : '') + data.join('\n'));
							break;
					}

					numWriting--;
					wroteData = true;
				}

				endIfDoneWritingData();
			}

			function onEnd() {

				ended = true;
				endIfDoneWritingData();
			}

			function endIfDoneWritingData() {

				if (ended && !numWriting) {
					endOutput();
				}
			}

			var startOutput = _.once(function() {

				log('Writing output to ' + outputFile);

				switch (outputFormat) {

					case 'json':
						writeStream.write('[');
						break;

					case 'csv':
						writeStream.write(proxyFieldNames.join(','));
						break;
				}
			});

			var endOutput = _.once(function() {

				switch (outputFormat) {
					case 'json':
						writeStream.write(']');
						break;
				}

				writeStream.end();
				log('Done!');

				if (logStream) {
					logStream.end();
				}
			});

			log('Getting proxies...');

			var options = _.pick(this, [
				'anonymityLevels',
				'countries',
				'protocols',
				'sourcesWhiteList',
				'sourcesBlackList',
				'sample',
				'series'
			]);

			var gettingProxies = ProxyLists.getProxies(options);
			gettingProxies.on('data', onData);
			gettingProxies.on('error', function(error) {
				console.error(error);
			});
			gettingProxies.on('end', onEnd);

			startOutput();
		});

program.parse(process.argv);
<|endoftext|>


<commit_before>'use babel'

/* global atom */

import {CompositeDisposable} from 'atom'
import {camelCase} from 'change-case'
import PackagesView from './packages-view'
import InputDialog from './input-dialog'
import npm from './npm-adapter'
import {EOL} from 'os'
import path from 'path'

class NpmHelper {
  constructor () {
    this.pkgView = null
    this.subscriptions = null
    this.operation = null
  }

  activate () {
    this.pkgView = new PackagesView(this)
    this.subscriptions = new CompositeDisposable()
    this.subscriptions.add(
      atom.commands.add('atom-text-editor', {
        'npm-helper:search': () => this.search(),
        'npm-helper:install': () => this.install()
      })
    )
  }

  deactivate () {
    this.subscriptions.dispose()
    this.pkgView.destroy()
  }

  search () {
    this.fromInput(this.performSearch, 'Enter package name or part of it')
  }

  install () {
    this.fromInput(this.decideDev, 'Enter name of package to install')
  }

  decideDev (name) {
    this.pkgView.setResults([{name}])
  }

  performSearch (text) {
    this.onStart(`Searching the npm registry for "${text}" …`, `searching for "text"`)
    npm.search(text)
      .then(results => this.pkgView.setResults(results))
      .then(() => this.onDone(), err => this.onError(err))
  }

  performInstall (pkgName, dev) {
    const editor = atom.workspace.getActivePaneItem()
    const filePath = editor.getPath()
    if (filePath == null) {
      atom.notifications.addWarning('Path to file unknown, please save first')
      return
    }
    const suffix = dev ? ' (dev)' : ''
    this.onStart(`Installing package ${pkgName}${suffix} with npm …`,
      `installing package ${pkgName}`)
    npm.install(pkgName, path.dirname(filePath), dev)
      .then(result => {
        atom.notifications.addSuccess(`Package ${pkgName} successfully installed!`)
        const impName = camelCase(pkgName)
        editor.insertText(`import ${impName} from '${pkgName}'${EOL}`, {
          select: !editor.getSelectedBufferRange().isEmpty()
        })
      })
      .then(() => this.onDone(), err => this.onError(err))
  }

  onStart (notif, descr) {
    this.notification = atom.notifications.addInfo(notif, {dismissable: true})
    this.operation = descr
  }

  onError (err) {
    atom.notifications.addError(err.message, {
      detail: err.stack,
      dismissable: true
    })
    this.onDone()
  }

  onDone () {
    this.notification.dismiss()
    this.operation = null
  }

  fromInput (func, prompt) {
    if (this.operation != null) {
      atom.notifications.addWarning(`Still ${this.operation}`)
      return
    }
    const editor = atom.workspace.getActivePaneItem()
    const filePath = editor.getPath()
    if (filePath == null) {
      atom.notifications.addWarning('Path to file unknown, please save first')
      return
    }
    const selection = editor.getSelectedText().trim()
    if (selection.length > 0) {
      func.call(this, selection)
    } else {
      const dialog = new InputDialog(prompt)
      dialog.show(text => func.call(this, text))
    }
  }

  onSelectPackage (item) {
    if (item) {
      this.performInstall(item.name, item.dev)
    }
  }
}

export default new NpmHelper()
<commit_msg>Only inserting import if JS<commit_after>'use babel'

/* global atom */

import {CompositeDisposable} from 'atom'
import {camelCase} from 'change-case'
import PackagesView from './packages-view'
import InputDialog from './input-dialog'
import npm from './npm-adapter'
import {EOL} from 'os'
import path from 'path'

const reJsScope = /^source\.js($|\.)/

class NpmHelper {
  constructor () {
    this.pkgView = null
    this.subscriptions = null
    this.operation = null
  }

  activate () {
    this.pkgView = new PackagesView(this)
    this.subscriptions = new CompositeDisposable()
    this.subscriptions.add(
      atom.commands.add('atom-text-editor', {
        'npm-helper:search': () => this.search(),
        'npm-helper:install': () => this.install()
      })
    )
  }

  deactivate () {
    this.subscriptions.dispose()
    this.pkgView.destroy()
  }

  search () {
    this.fromInput(this.performSearch, 'Enter package name or part of it')
  }

  install () {
    this.fromInput(this.decideDev, 'Enter name of package to install')
  }

  decideDev (name) {
    this.pkgView.setResults([{name}])
  }

  performSearch (text) {
    this.onStart(`Searching the npm registry for "${text}" …`, `searching for "text"`)
    npm.search(text)
      .then(results => this.pkgView.setResults(results))
      .then(() => this.onDone(), err => this.onError(err))
  }

  performInstall (pkgName, dev) {
    const editor = atom.workspace.getActivePaneItem()
    const filePath = editor.getPath()
    if (filePath == null) {
      atom.notifications.addWarning('Path to file unknown, please save first')
      return
    }
    const suffix = dev ? ' (dev)' : ''
    this.onStart(`Installing package ${pkgName}${suffix} with npm …`,
      `installing package ${pkgName}`)
    npm.install(pkgName, path.dirname(filePath), dev)
      .then(result => {
        atom.notifications.addSuccess(`Package ${pkgName} successfully installed!`)
        const grammar = editor.getGrammar()
        if (reJsScope.test(grammar.scopeName)) {
          const impName = camelCase(pkgName)
          editor.insertText(`import ${impName} from '${pkgName}'${EOL}`, {
            select: !editor.getSelectedBufferRange().isEmpty()
          })
        }
      })
      .then(() => this.onDone(), err => this.onError(err))
  }

  onStart (notif, descr) {
    this.notification = atom.notifications.addInfo(notif, {dismissable: true})
    this.operation = descr
  }

  onError (err) {
    atom.notifications.addError(err.message, {
      detail: err.stack,
      dismissable: true
    })
    this.onDone()
  }

  onDone () {
    this.notification.dismiss()
    this.operation = null
  }

  fromInput (func, prompt) {
    if (this.operation != null) {
      atom.notifications.addWarning(`Still ${this.operation}`)
      return
    }
    const editor = atom.workspace.getActivePaneItem()
    const filePath = editor.getPath()
    if (filePath == null) {
      atom.notifications.addWarning('Path to file unknown, please save first')
      return
    }
    const selection = editor.getSelectedText().trim()
    if (selection.length > 0) {
      func.call(this, selection)
    } else {
      const dialog = new InputDialog(prompt)
      dialog.show(text => func.call(this, text))
    }
  }

  onSelectPackage (item) {
    if (item) {
      this.performInstall(item.name, item.dev)
    }
  }
}

export default new NpmHelper()
<|endoftext|>


<commit_before>// Copyright (c) 2016 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.

import {batchActions} from 'redux-batched-actions';

import {ViewTypes} from 'app/constants';

import {fetchMyChannelsAndMembers, getMyChannelMembers, selectChannel} from 'service/actions/channels';
import {getPosts} from 'service/actions/posts';
import {getTeamMembersByIds} from 'service/actions/teams';
import {Constants, UsersTypes} from 'service/constants';
import {getChannelByName, getDirectChannelName} from 'service/utils/channel_utils';
import {getPreferencesByCategory} from 'service/utils/preference_utils';

export function loadChannelsIfNecessary(teamId) {
    return async (dispatch, getState) => {
        const channels = getState().entities.channels.channels;

        let hasChannelsForTeam = false;
        for (const channel of Object.values(channels)) {
            if (channel.team_id === teamId) {
                // If we have one channel, assume we have all of them
                hasChannelsForTeam = true;
                break;
            }
        }

        if (hasChannelsForTeam) {
            await getMyChannelMembers(teamId)(dispatch, getState);
        } else {
            await fetchMyChannelsAndMembers(teamId)(dispatch, getState);
        }
    };
}

export function loadProfilesAndTeamMembersForDMSidebar(teamId) {
    return async (dispatch, getState) => {
        const state = getState();
        const currentUserId = state.entities.users.currentId;
        const {channels} = state.entities.channels;
        const {myPreferences} = state.entities.preferences;
        const {membersInTeam} = state.entities.teams;
        const dmPrefs = getPreferencesByCategory(myPreferences, Constants.CATEGORY_DIRECT_CHANNEL_SHOW);
        const members = [];

        for (const [key, pref] of dmPrefs) {
            if (pref.value === 'true') {
                members.push(key);
            }
        }

        let membersToLoad = members;
        if (membersInTeam[teamId]) {
            membersToLoad = members.filter((m) => !membersInTeam[teamId].has(m));
        }

        if (membersToLoad.length) {
            await getTeamMembersByIds(teamId, membersToLoad)(dispatch, getState);
        }

        const actions = [];
        for (let i = 0; i < members.length; i++) {
            const channelName = getDirectChannelName(currentUserId, members[i]);
            const channel = getChannelByName(channels, channelName);
            if (channel) {
                actions.push({
                    type: UsersTypes.RECEIVED_PROFILE_IN_CHANNEL,
                    data: {user_id: members[i]},
                    id: channel.id
                });
            }
        }

        if (actions.length) {
            dispatch(batchActions(actions), getState);
        }
    };
}

export function loadPostsIfNecessary(channel) {
    return async (dispatch, getState) => {
        const postsInChannel = getState().entities.posts.postsByChannel[channel.id];

        if (!postsInChannel) {
            let teamId = channel.team_id;
            if (!teamId) {
                teamId = getState().entities.teams.currentId;
            }
            await getPosts(teamId, channel.id)(dispatch, getState);
        }
    };
}

export function selectInitialChannel(teamId) {
    return async (dispatch, getState) => {
        const channels = getState().entities.channels.channels;

        for (const channel of Object.values(channels)) {
            // TODO figure out how to handle when we can't find the town square
            if (channel.team_id === teamId && channel.name === Constants.DEFAULT_CHANNEL) {
                await selectChannel(channel.id)(dispatch, getState);
                break;
            }
        }
    };
}

export function handlePostDraftChanged(postDraft) {
    return async (dispatch, getState) => {
        dispatch({
            type: ViewTypes.POST_DRAFT_CHANGED,
            postDraft
        }, getState);
    };
}
<commit_msg>Show town square when selecting a team (#166)<commit_after>// Copyright (c) 2016 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.

import {batchActions} from 'redux-batched-actions';

import {ViewTypes} from 'app/constants';

import {fetchMyChannelsAndMembers, getMyChannelMembers, selectChannel} from 'service/actions/channels';
import {getPosts} from 'service/actions/posts';
import {getTeamMembersByIds} from 'service/actions/teams';
import {Constants, UsersTypes} from 'service/constants';
import {getChannelByName, getDirectChannelName} from 'service/utils/channel_utils';
import {getPreferencesByCategory} from 'service/utils/preference_utils';

export function loadChannelsIfNecessary(teamId) {
    return async (dispatch, getState) => {
        const channels = getState().entities.channels.channels;

        let hasChannelsForTeam = false;
        for (const channel of Object.values(channels)) {
            if (channel.team_id === teamId) {
                // If we have one channel, assume we have all of them
                hasChannelsForTeam = true;
                break;
            }
        }

        if (hasChannelsForTeam) {
            await getMyChannelMembers(teamId)(dispatch, getState);
        } else {
            await fetchMyChannelsAndMembers(teamId)(dispatch, getState);
        }
    };
}

export function loadProfilesAndTeamMembersForDMSidebar(teamId) {
    return async (dispatch, getState) => {
        const state = getState();
        const currentUserId = state.entities.users.currentId;
        const {channels} = state.entities.channels;
        const {myPreferences} = state.entities.preferences;
        const {membersInTeam} = state.entities.teams;
        const dmPrefs = getPreferencesByCategory(myPreferences, Constants.CATEGORY_DIRECT_CHANNEL_SHOW);
        const members = [];

        for (const [key, pref] of dmPrefs) {
            if (pref.value === 'true') {
                members.push(key);
            }
        }

        let membersToLoad = members;
        if (membersInTeam[teamId]) {
            membersToLoad = members.filter((m) => !membersInTeam[teamId].has(m));
        }

        if (membersToLoad.length) {
            await getTeamMembersByIds(teamId, membersToLoad)(dispatch, getState);
        }

        const actions = [];
        for (let i = 0; i < members.length; i++) {
            const channelName = getDirectChannelName(currentUserId, members[i]);
            const channel = getChannelByName(channels, channelName);
            if (channel) {
                actions.push({
                    type: UsersTypes.RECEIVED_PROFILE_IN_CHANNEL,
                    data: {user_id: members[i]},
                    id: channel.id
                });
            }
        }

        if (actions.length) {
            dispatch(batchActions(actions), getState);
        }
    };
}

export function loadPostsIfNecessary(channel) {
    return async (dispatch, getState) => {
        const postsInChannel = getState().entities.posts.postsByChannel[channel.id];

        if (!postsInChannel) {
            let teamId = channel.team_id;
            if (!teamId) {
                teamId = getState().entities.teams.currentId;
            }
            await getPosts(teamId, channel.id)(dispatch, getState);
        }
    };
}

export function selectInitialChannel(teamId) {
    return async (dispatch, getState) => {
        const channels = getState().entities.channels.channels;

        const channel = Object.values(channels).find((c) => c.team_id === teamId && c.name === Constants.DEFAULT_CHANNEL);
        if (channel) {
            await selectChannel(channel.id)(dispatch, getState);
        } else {
            // Handle case when the default channel cannot be found
            const firstChannel = Object.values(channels)[0];
            await selectChannel(firstChannel.id)(dispatch, getState);
        }
    };
}

export function handlePostDraftChanged(postDraft) {
    return async (dispatch, getState) => {
        dispatch({
            type: ViewTypes.POST_DRAFT_CHANGED,
            postDraft
        }, getState);
    };
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
var chalk = require('chalk')
var clivas = require('clivas')
var concat = require('concat-stream')
var cp = require('child_process')
var fs = require('fs')
var http = require('http')
var minimist = require('minimist')
var os = require('os')
var path = require('path')
var numeral = require('numeral')
var address = require('network-address')
var moment = require('moment')
var WebTorrent = require('../')

var TMP = os.tmp

function usage () {
  var logo = fs.readFileSync(path.join(__dirname, 'ascii-logo.txt'), 'utf8')
  logo.split('\n').forEach(function (line) {
    console.log(chalk.bold(line.substring(0, 20) + chalk.red(line.substring(20))))
  })
  console.log('Usage: webtorrent [torrentId] {OPTIONS}')
  console.log('')
  console.log(chalk.bold('torrentId') + ' can be any of the following:')
  console.log('  * magnet uri')
  console.log('  * path to .torrent file (filesystem path or http url)')
  console.log('  * info hash (as hex string)')
  console.log('')
  console.log(chalk.bold('OPTIONS:'))
  console.log('  --vlc            autoplay in vlc')
  console.log('  --mplayer        autoplay in mplayer')
  console.log('  --omx [jack]     autoplay in omx (jack=local|hdmi)')
  console.log('')
  console.log('  -p, --port       change the http port               [default: 9000]')
  console.log('  -l, --list       list available files in torrent')
  console.log('  -t, --subtitles  load subtitles file')
  console.log('  -h, --help       display this help message')
  console.log('  -q, --quiet      silence stdout')
  console.log('  -v, --version    print the current version')
  console.log('')
}

var argv = minimist(process.argv.slice(2))

var torrentId = argv._[0]

var port = Number(argv.port || argv.p) || 9000
var list = argv.list || argv.l
var subtitles = argv.subtitles || argv.t
var quiet = argv.quiet || argv.q

if (argv.help || argv.h) {
  usage()
  process.exit(0)
}

if (argv.version || argv.v) {
  console.log(require('../package.json').version)
  process.exit(0)
}

if (!torrentId) {
  usage()
  process.exit(0)
}

var VLC_ARGS = '-q --video-on-top --play-and-exit'
var OMX_EXEC = 'omxplayer -r -o ' + (typeof argv.omx === 'string')
  ? argv.omx + ' '
  : 'hdmi '
var MPLAYER_EXEC = 'mplayer -ontop -really-quiet -noidx -loop 0 '

if (subtitles) {
  VLC_ARGS += ' --sub-file=' + subtitles
  OMX_EXEC += ' --subtitles ' + subtitles
  MPLAYER_EXEC += ' -sub ' + subtitles
}

var client = new WebTorrent({
  list: list,
  quiet: true
})

client.on('error', function (err) {
  clivas.line('{red:error} ' + err.message)
})

client.add(torrentId, function (err, torrent) {
  if (err) {
    clivas.line('{red:error} ' + err.message)
    process.exit(1)
  }

  function updateMetadata () {
    if (torrent) {
      clivas.clear()
      clivas.line('{green:fetching torrent metadata from} {bold:'+torrent.swarm.numPeers+'} {green:peers}')
    }
  }

  if (!torrent.metadata && !quiet && !list) {
    updateMetadata()
    torrent.swarm.on('wire', updateMetadata)

    client.once('torrent', function () {
      torrent.swarm.removeListener('wire', updateMetadata)
    })
  }
})

client.once('torrent', function (torrent) {
  if (list) {
    torrent.files.forEach(function (file, i) {
      clivas.line('{3+bold:'+i+'} : {magenta:'+file.name+'}')
    })

    process.exit(0)
  }

  var started = Date.now()
  var swarm = torrent.swarm
  var wires = swarm.wires
  var hotswaps = 0

  torrent.on('hotswap', function () {
    hotswaps++
  })

  function active (wire) {
    return !wire.peerChoking
  }

  var href = 'http://' + address() + ':' + swarm.port + '/'
  //var filename = engine.server.index.name.split('/').pop().replace(/\{|\}/g, '')
  var filename = torrent.name

  if (argv.vlc && process.platform === 'win32') {
    var registry = require('windows-no-runnable').registry
    var key
    if (process.arch === 'x64') {
      try {
        key = registry('HKLM/Software/Wow6432Node/VideoLAN/VLC')
      } catch (e) {}
    } else {
      try {
        key = registry('HKLM/Software/VideoLAN/VLC')
      } catch (err) {}
    }

    if (key) {
      var vlcPath = key['InstallDir'].value + path.sep + 'vlc'
      VLC_ARGS = VLC_ARGS.split(' ')
      VLC_ARGS.unshift(href)
      proc.execFile(vlcPath, VLC_ARGS)
    }
  } else {
    if (argv.vlc) proc.exec('vlc '+href+' '+VLC_ARGS+' || /Applications/VLC.app/Contents/MacOS/VLC '+href+' '+VLC_ARGS)
  }

  if (argv.omx) proc.exec(OMX_EXEC+' '+href)
  if (argv.mplayer) proc.exec(MPLAYER_EXEC+' '+href)

  function bytes (num) {
    return numeral(num).format('0.0b')
  }

  function getRuntime () {
    return Math.floor((Date.now() - started) / 1000)
  }

  if (!quiet) {
    process.stdout.write(new Buffer('G1tIG1sySg==', 'base64')); // clear for drawing

    function draw () {
      var unchoked = swarm.wires.filter(active)
      var runtime = getRuntime()
      var linesremaining = clivas.height
      var peerslisted = 0
      var speed = swarm.downloadSpeed()
      var estimatedSecondsRemaining = Math.max(0, torrent.length - swarm.downloaded) / (speed > 0 ? speed : -1)
      var estimate = moment.duration(estimatedSecondsRemaining, 'seconds').humanize()

      clivas.clear()
      clivas.line('{green:open} {bold:vlc} {green:and enter} {bold:'+href+'} {green:as the network address}')
      clivas.line('')
      clivas.line('{yellow:info} {green:streaming} {bold:'+filename+'} {green:-} {bold:'+bytes(speed)+'/s} {green:from} {bold:'+unchoked.length +'/'+wires.length+'} {green:peers}    ')
      clivas.line('{yellow:info} {green:downloaded} {bold:'+bytes(swarm.downloaded)+'} {green:out of} {bold:'+bytes(torrent.length)+'} {green:and uploaded }{bold:'+bytes(swarm.uploaded)+'} {green:in }{bold:'+runtime+'s} {green:with} {bold:'+hotswaps+'} {green:hotswaps}     ')
      clivas.line('{yellow:info} {green:estimating} {bold:'+estimate+'} {green:remaining}; {green:peer queue size is} {bold:'+swarm.numQueued+'}     ')
      clivas.line('{80:}')
      linesremaining -= 8

      wires.every(function (wire) {
        var tags = []
        if (wire.peerChoking) tags.push('choked')
        clivas.line('{25+magenta:'+wire.remoteAddress+'} {10:'+bytes(wire.downloaded)+'} {10+cyan:'+bytes(wire.downloadSpeed())+'/s} {15+grey:'+tags.join(', ')+'}   ')
        peerslisted++
        return linesremaining - peerslisted > 4
      })
      linesremaining -= peerslisted

      if (wires.length > peerslisted) {
        clivas.line('{80:}')
        clivas.line('... and '+(wires.length - peerslisted)+' more     ')
      }

      clivas.line('{80:}')
      clivas.flush()
    }

    setInterval(draw, 500)
    draw()
  }

  torrent.on('done', function () {
    if (!quiet) {
      clivas.line('torrent downloaded {green:successfully} from {bold:'+wires.length+'} {green:peers} in {bold:'+getRuntime()+'s}!')
    }
    process.exit(0)
  })

  /*client.on('ready', function() {
    swarm.removeListener('wire', onmagnet)
    client.server.listen(argv.port || 8888)
  })*/
})
<commit_msg>stream to VLC is now working<commit_after>#!/usr/bin/env node
var chalk = require('chalk')
var clivas = require('clivas')
var concat = require('concat-stream')
var cp = require('child_process')
var fs = require('fs')
var http = require('http')
var minimist = require('minimist')
var os = require('os')
var path = require('path')
var numeral = require('numeral')
var address = require('network-address')
var moment = require('moment')
var proc = require('child_process')
var WebTorrent = require('../')

var TMP = os.tmp

function usage () {
  var logo = fs.readFileSync(path.join(__dirname, 'ascii-logo.txt'), 'utf8')
  logo.split('\n').forEach(function (line) {
    console.log(chalk.bold(line.substring(0, 20) + chalk.red(line.substring(20))))
  })
  console.log('Usage: webtorrent [torrentId] {OPTIONS}')
  console.log('')
  console.log(chalk.bold('torrentId') + ' can be any of the following:')
  console.log('  * magnet uri')
  console.log('  * path to .torrent file (filesystem path or http url)')
  console.log('  * info hash (as hex string)')
  console.log('')
  console.log(chalk.bold('OPTIONS:'))
  console.log('  --vlc            autoplay in vlc')
  console.log('  --mplayer        autoplay in mplayer')
  console.log('  --omx [jack]     autoplay in omx (jack=local|hdmi)')
  console.log('')
  console.log('  -p, --port       change the http port               [default: 9000]')
  console.log('  -l, --list       list available files in torrent')
  console.log('  -t, --subtitles  load subtitles file')
  console.log('  -h, --help       display this help message')
  console.log('  -q, --quiet      silence stdout')
  console.log('  -v, --version    print the current version')
  console.log('  -n, --no-quit    do not quit peerflix on vlc exit')
  console.log('')
}

var argv = minimist(process.argv.slice(2))

var torrentId = argv._[0]

var port = Number(argv.port || argv.p) || 9000
var list = argv.list || argv.l
var subtitles = argv.subtitles || argv.t
var quiet = argv.quiet || argv.q
var noquit = argv.n || argv['no-quit']

if (argv.help || argv.h) {
  usage()
  process.exit(0)
}

if (argv.version || argv.v) {
  console.log(require('../package.json').version)
  process.exit(0)
}

if (!torrentId) {
  usage()
  process.exit(0)
}

var VLC_ARGS = '-q --video-on-top --play-and-exit'
//var VLC_ARGS = '--video-on-top --play-and-exit --extraintf=http:logger --verbose=2 --file-logging --logfile=vlc-log.txt'
var OMX_EXEC = 'omxplayer -r -o ' + (typeof argv.omx === 'string')
  ? argv.omx + ' '
  : 'hdmi '
var MPLAYER_EXEC = 'mplayer -ontop -really-quiet -noidx -loop 0 '

if (subtitles) {
  VLC_ARGS += ' --sub-file=' + subtitles
  OMX_EXEC += ' --subtitles ' + subtitles
  MPLAYER_EXEC += ' -sub ' + subtitles
}

var client = new WebTorrent({
  list: list,
  quiet: true
})

var started = Date.now()
var listening = false

client.on('error', function (err) {
  clivas.line('{red:error} ' + err.message)
})

client.once('ready', function () {
  client.server.once('error', function () {
    client.server.listen(0)
  })

  client.server.listen(port)
})

client.server.once('listening', function () {
  listening = true
})

client.add(torrentId, function (err, torrent) {
  if (err) {
    clivas.line('{red:error} ' + err.message)
    process.exit(1)
  }

  function updateMetadata () {
    if (torrent) {
      clivas.clear()
      clivas.line('{green:fetching torrent metadata from} {bold:'+torrent.swarm.numPeers+'} {green:peers}')
    }
  }

  if (!torrent.metadata && !quiet && !list) {
    updateMetadata()
    torrent.swarm.on('wire', updateMetadata)

    client.once('torrent', function () {
      torrent.swarm.removeListener('wire', updateMetadata)
    })
  }
})

function ontorrent (torrent) {
  if (list) {
    torrent.files.forEach(function (file, i) {
      clivas.line('{3+bold:'+i+'} : {magenta:'+file.name+'}')
    })

    process.exit(0)
  }

  var href = 'http://' + address() + ':' + client.server.address().port + '/'

  if (argv.vlc && process.platform === 'win32') {
    var registry = require('windows-no-runnable').registry
    var key
    if (process.arch === 'x64') {
      try {
        key = registry('HKLM/Software/Wow6432Node/VideoLAN/VLC')
      } catch (e) {}
    } else {
      try {
        key = registry('HKLM/Software/VideoLAN/VLC')
      } catch (err) {}
    }

    if (key) {
      var vlcPath = key['InstallDir'].value + path.sep + 'vlc'
      VLC_ARGS = VLC_ARGS.split(' ')
      VLC_ARGS.unshift(href)
      proc.execFile(vlcPath, VLC_ARGS)
    }
  } else {
    if (argv.vlc) {
      var vlc = proc.exec('vlc '+href+' '+VLC_ARGS+' || /Applications/VLC.app/Contents/MacOS/VLC '+href+' '+VLC_ARGS, function (error) {
        if (error) {
          process.exit(1)
        }
      })

      vlc.on('exit', function () {
        if (!noquit) process.exit(0)
      })
    }
  }

  if (argv.omx) proc.exec(OMX_EXEC + ' ' + href)
  if (argv.mplayer) proc.exec(MPLAYER_EXEC + ' ' + href)
  //if (quiet) console.log('server is listening on', href)

  var filename = torrent.name
  //var filename = index.name.split('/').pop().replace(/\{|\}/g, '')
  var swarm = torrent.swarm
  var wires = swarm.wires
  var hotswaps = 0

  torrent.on('hotswap', function () {
    hotswaps++
  })

  function active (wire) {
    return !wire.peerChoking
  }

  function bytes (num) {
    return numeral(num).format('0.0b')
  }

  function getRuntime () {
    return Math.floor((Date.now() - started) / 1000)
  }

  if (!quiet) {
    process.stdout.write(new Buffer('G1tIG1sySg==', 'base64')); // clear for drawing

    function draw () {
      var unchoked = swarm.wires.filter(active)
      var runtime = getRuntime()
      var linesremaining = clivas.height
      var peerslisted = 0
      var speed = swarm.downloadSpeed()
      var estimatedSecondsRemaining = Math.max(0, torrent.length - swarm.downloaded) / (speed > 0 ? speed : -1)
      var estimate = moment.duration(estimatedSecondsRemaining, 'seconds').humanize()

      clivas.clear()
      clivas.line('{green:open} {bold:vlc} {green:and enter} {bold:'+href+'} {green:as the network address}')
      clivas.line('')
      clivas.line('{yellow:info} {green:streaming} {bold:'+filename+'} {green:-} {bold:'+bytes(speed)+'/s} {green:from} {bold:'+unchoked.length +'/'+wires.length+'} {green:peers}    ')
      clivas.line('{yellow:info} {green:downloaded} {bold:'+bytes(swarm.downloaded)+'} {green:out of} {bold:'+bytes(torrent.length)+'} {green:and uploaded }{bold:'+bytes(swarm.uploaded)+'} {green:in }{bold:'+runtime+'s} {green:with} {bold:'+hotswaps+'} {green:hotswaps}     ')
      clivas.line('{yellow:info} {green:estimating} {bold:'+estimate+'} {green:remaining}; {green:peer queue size is} {bold:'+swarm.numQueued+'}     ')
      clivas.line('{80:}')
      linesremaining -= 8

      wires.every(function (wire) {
        var tags = []
        if (wire.peerChoking) tags.push('choked')
        clivas.line('{25+magenta:'+wire.remoteAddress+'} {10:'+bytes(wire.downloaded)+'} {10+cyan:'+bytes(wire.downloadSpeed())+'/s} {15+grey:'+tags.join(', ')+'}   ')
        peerslisted++
        return linesremaining - peerslisted > 4
      })
      linesremaining -= peerslisted

      if (wires.length > peerslisted) {
        clivas.line('{80:}')
        clivas.line('... and '+(wires.length - peerslisted)+' more     ')
      }

      clivas.line('{80:}')
      clivas.flush()
    }

    setInterval(draw, 500)
    draw()
  }

  torrent.on('done', function () {
    if (!quiet) {
      clivas.line('torrent downloaded {green:successfully} from {bold:'+wires.length+'} {green:peers} in {bold:'+getRuntime()+'s}!')
    }
    process.exit(0)
  })
}

client.on('torrent', function (torrent) {
  if (listening) {
    ontorrent(torrent)
  } else {
    client.on('listening', function (torrent) {
      ontorrent(torrent)
    })
  }
})
<|endoftext|>