<commit_before>/**************************************************************************************************
 *
 * Copyright (c) 2014 Digium, Inc.
 * All Rights Reserved. Licensed Software.
 *
 * @authors : <NAME> <<EMAIL>>
 */

/**
 * Create a new WebRTC Client object.
 * @author <NAME> <<EMAIL>>
 * @class brightstream.Client
 * @constructor
 * @augments brightstream.EventEmitter
 * @classdesc This is a top-level interface to the API. It handles authenticating the app to the
 * API server and receiving server-side app-specific information.
 * @param {object} clientSettings
 * @param {string} appId
 * @param {RTCConstraints} [constraints]
 * @param {RTCICEServers} [servers]
 * @returns {brightstream.Client}
 * @property {object} clientSettings Client settings.
 * @property {brightstream.SignalingChannel} signalingChannel A reference to the signaling channel.
 * @property {function} chatMessage Class to use for chat messages.
 * @property {function} signalingMessage Class to use for signaling.
 * @property {function} presenceMessage Class to use for presence messages.
 * @property {brightstream.User} user Logged-in user's User object.
 */
/*global brightstream: false */
brightstream.Client = function (params) {
    "use strict";
    params = params || {};
    var client = brightstream.makeUniqueID().toString();
    var that = brightstream.EventEmitter(params);
    brightstream.instances[client] = that;
    that.className = 'brightstream.Client';

    var host = window.location.hostname;
    var port = window.location.port;
    var connected = false;
    var app = {
        baseURL: params.baseURL,
        authToken: params.authToken,
        appId: params.appId
    };
    delete params.appId;
    delete params.baseURL;
    var signalingChannel = null;
    var turnRefresher = null;
    var groups = [];
    var endpoints = [];


    log.debug("Client ID is ", client);

    var callSettings = {
        constraints: params.constraints || {
            video : true,
            audio : true,
            optional: [],
            mandatory: {}
        },
        servers: params.servers || {
            iceServers: []
        }
    };

    signalingChannel = brightstream.SignalingChannel({'client': client});
    that.user = null;
    log.debug(signalingChannel);

    /**
     * Connect to the Digium infrastructure and authenticate using the appkey.  Store
     * a token to be used in API requests.
     * @memberof! brightstream.Client
     * @method brightstream.Client.connect
     * @param {string} authToken
     * @param {function} [onSuccess] - Success handler for this invocation of this method only.
     * @param {function} [onError] - Error handler for this invocation of this method only.
     * @param {function} [onJoin] - Callback for when this client's endpoint joins a group.
     * @param {function} [onLeave] - Callback for when this client's endpoint leaves a group.
     * @param {function} [onAutoJoin] - Callback for when this client's user automatically joins a group. Not
     * Implemented.
     * @param {function} [onAutoLeave] - Callback for when this client's user automatically leaves a group. Not
     * Implemented.
     * @param {function} [onMessage] - Callback for when an unknown Endpoint sends a message.
     * @param {function} [onDisconnect] - Callback for Client disconnect.
     * @param {function} [onReconnect] - Callback for Client reconnect. Not Implemented.
     * @param {function} [onCall] - Callback for when this client's user receives a call.
     * @returns {Promise<brightstream.User>}
     * @fires brightstream.Client#connect
     */
    var connect = that.publicize('connect', function (params) {
        params = params || {};
        var deferred = brightstream.makeDeferred(params.onSuccess, params.onError);

        app.authToken = params.authToken;
        app.appId = params.appId || app.appId;
        signalingChannel.open({
            appId: app.appId,
            token: app.authToken
        }).then(function () {
            return signalingChannel.authenticate({
                appId: app.appId
            });
        }, function (err) {
            log.error(err.message);
            deferred.reject(new Error("Couldn't connect to brightstream: " + err.message));
        }).done(function (user) {
            connected = true;

            user.setOnline(); // Initiates presence.
            user.listen('call', params.onCall);
            user.listen('join', params.onJoin);
            user.listen('leave', params.onLeave);
            that.user = user;

            that.listen('join', params.onAutoJoin);
            that.listen('leave', params.onAutoLeave);
            that.listen('message', params.onMessage);
            that.listen('disconnect', params.onDisconnect);
            that.listen('reconnect', params.onReconnect);

            log.info('logged in as user ' + user.getName());
            log.debug(user);
            updateTurnCredentials();

            /**
             * @event brightstream.Client#connect
             * @type {brightstream.Event}
             * @property {brightstream.User}
             */
            that.fire('connect', {
                user: user
            });
            deferred.resolve(user);
        }, function (err) {
            deferred.reject("Couldn't create an endpoint.");
            log.error(err.message);
        });
        return deferred.promise;
    });

    /**
     * Disconnect from the Digium infrastructure. Invalidates the API token.
     * @memberof! brightstream.Client
     * @method brightstream.Client.disconnect
     * @returns {Promise<undefined>}
     * @param {function} [onSuccess] - Success handler for this invocation of this method only.
     * @param {function} [onError] - Error handler for this invocation of this method only.
     */
    var disconnect = that.publicize('disconnect', function (params) {
        // TODO: also call this on socket disconnect
        params = params || {};
        var disconnectPromise = brightstream.makeDeferred(params.onSuccess, params.onError);

        if (signalingChannel.isOpen()) {
            // do websocket stuff. If the websocket is already closed, we have to skip this stuff.
            var leaveGroups = groups.map(function (group) {
                group.leave();
            });
            Q.all(leaveGroups).done(function () {
                signalingChannel.close().done(function () {
                    disconnectPromise.resolve();
                }, function (err) {
                    throw new Error(err.message);
                });
            }, null);
        } else {
            disconnectPromise.resolve();
        }

        var afterDisconnect = function () {
            connected = false;
            endpoints = [];
            groups = [];
            /**
             * @event brightstream.Client#disconnect
             */
            that.fire('disconnect');
        };<commit_msg>Chain these promises and use fin() b/c we don't care about success.<commit_after>/**************************************************************************************************
 *
 * Copyright (c) 2014 Digium, Inc.
 * All Rights Reserved. Licensed Software.
 *
 * @authors : <NAME> <<EMAIL>>
 */

/**
 * Create a new WebRTC Client object.
 * @author <NAME> <<EMAIL>>
 * @class brightstream.Client
 * @constructor
 * @augments brightstream.EventEmitter
 * @classdesc This is a top-level interface to the API. It handles authenticating the app to the
 * API server and receiving server-side app-specific information.
 * @param {object} clientSettings
 * @param {string} appId
 * @param {RTCConstraints} [constraints]
 * @param {RTCICEServers} [servers]
 * @returns {brightstream.Client}
 * @property {object} clientSettings Client settings.
 * @property {brightstream.SignalingChannel} signalingChannel A reference to the signaling channel.
 * @property {function} chatMessage Class to use for chat messages.
 * @property {function} signalingMessage Class to use for signaling.
 * @property {function} presenceMessage Class to use for presence messages.
 * @property {brightstream.User} user Logged-in user's User object.
 */
/*global brightstream: false */
brightstream.Client = function (params) {
    "use strict";
    params = params || {};
    var client = brightstream.makeUniqueID().toString();
    var that = brightstream.EventEmitter(params);
    brightstream.instances[client] = that;
    that.className = 'brightstream.Client';

    var host = window.location.hostname;
    var port = window.location.port;
    var connected = false;
    var app = {
        baseURL: params.baseURL,
        authToken: params.authToken,
        appId: params.appId
    };
    delete params.appId;
    delete params.baseURL;
    var signalingChannel = null;
    var turnRefresher = null;
    var groups = [];
    var endpoints = [];


    log.debug("Client ID is ", client);

    var callSettings = {
        constraints: params.constraints || {
            video : true,
            audio : true,
            optional: [],
            mandatory: {}
        },
        servers: params.servers || {
            iceServers: []
        }
    };

    signalingChannel = brightstream.SignalingChannel({'client': client});
    that.user = null;
    log.debug(signalingChannel);

    /**
     * Connect to the Digium infrastructure and authenticate using the appkey.  Store
     * a token to be used in API requests.
     * @memberof! brightstream.Client
     * @method brightstream.Client.connect
     * @param {string} authToken
     * @param {function} [onSuccess] - Success handler for this invocation of this method only.
     * @param {function} [onError] - Error handler for this invocation of this method only.
     * @param {function} [onJoin] - Callback for when this client's endpoint joins a group.
     * @param {function} [onLeave] - Callback for when this client's endpoint leaves a group.
     * @param {function} [onAutoJoin] - Callback for when this client's user automatically joins a group. Not
     * Implemented.
     * @param {function} [onAutoLeave] - Callback for when this client's user automatically leaves a group. Not
     * Implemented.
     * @param {function} [onMessage] - Callback for when an unknown Endpoint sends a message.
     * @param {function} [onDisconnect] - Callback for Client disconnect.
     * @param {function} [onReconnect] - Callback for Client reconnect. Not Implemented.
     * @param {function} [onCall] - Callback for when this client's user receives a call.
     * @returns {Promise<brightstream.User>}
     * @fires brightstream.Client#connect
     */
    var connect = that.publicize('connect', function (params) {
        params = params || {};
        var deferred = brightstream.makeDeferred(params.onSuccess, params.onError);

        app.authToken = params.authToken;
        app.appId = params.appId || app.appId;
        signalingChannel.open({
            appId: app.appId,
            token: app.authToken
        }).then(function () {
            return signalingChannel.authenticate({
                appId: app.appId
            });
        }, function (err) {
            log.error(err.message);
            deferred.reject(new Error("Couldn't connect to brightstream: " + err.message));
        }).done(function (user) {
            connected = true;

            user.setOnline(); // Initiates presence.
            user.listen('call', params.onCall);
            user.listen('join', params.onJoin);
            user.listen('leave', params.onLeave);
            that.user = user;

            that.listen('join', params.onAutoJoin);
            that.listen('leave', params.onAutoLeave);
            that.listen('message', params.onMessage);
            that.listen('disconnect', params.onDisconnect);
            that.listen('reconnect', params.onReconnect);

            log.info('logged in as user ' + user.getName());
            log.debug(user);
            updateTurnCredentials();

            /**
             * @event brightstream.Client#connect
             * @type {brightstream.Event}
             * @property {brightstream.User}
             */
            that.fire('connect', {
                user: user
            });
            deferred.resolve(user);
        }, function (err) {
            deferred.reject("Couldn't create an endpoint.");
            log.error(err.message);
        });
        return deferred.promise;
    });

    /**
     * Disconnect from the Digium infrastructure. Invalidates the API token.
     * @memberof! brightstream.Client
     * @method brightstream.Client.disconnect
     * @returns {Promise<undefined>}
     * @param {function} [onSuccess] - Success handler for this invocation of this method only.
     * @param {function} [onError] - Error handler for this invocation of this method only.
     */
    var disconnect = that.publicize('disconnect', function (params) {
        // TODO: also call this on socket disconnect
        params = params || {};
        var disconnectPromise = brightstream.makeDeferred(params.onSuccess, params.onError);

        if (signalingChannel.isOpen()) {
            // do websocket stuff. If the websocket is already closed, we have to skip this stuff.
            var leaveGroups = groups.map(function (group) {
                group.leave();
            });
            Q.all(leaveGroups).then(function () {
                return signalingChannel.close();
            }, function (err) {
                // Possibly the socket got closed already and we couldn't leave our groups. Backed will clean this up.
                disconnectPromise.resolve();
            }).fin(function () {
                if (!disconnectPromise.promise.isFulfilled()) {
                    // Successfully closed our socket after leaving all groups.
                    disconnectPromise.resolve();
                }
            });
        } else {
            disconnectPromise.resolve();
        }

        var afterDisconnect = function () {
            connected = false;
            endpoints = [];
            groups = [];
            /**
             * @event brightstream.Client#disconnect
             */
            that.fire('disconnect');
        };
{'fraction_non_alphanumeric': 0.12361520123404852, 'fraction_numerical': 0.000560931145701865, 'mean_word_length': 2.341846298031865, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2060653', 'n_tokens_mistral': 3755, 'n_tokens_neox': 3619, 'n_words': 1077}