<commit_before>const MBTradePage          = require('./mb_trade/mb_tradepage');
const TradePage_Beta       = require('./trade/beta/tradepage');
const Highchart            = require('./trade/charts/highchartws').Highchart;
const reloadPage           = require('./trade/common').reloadPage;
const Notifications        = require('./trade/notifications').Notifications;
const WSTickDisplay        = require('./trade/tick_trade').WSTickDisplay;
const TradePage            = require('./trade/tradepage');
const ViewPopupWS          = require('./user/view_popup/view_popupws');
const ViewBalanceUI        = require('./user/viewbalance/viewbalance.ui').ViewBalanceUI;
const Client               = require('../base/client');
const Clock                = require('../base/clock');
const GTM                  = require('../base/gtm');
const Header               = require('../base/header');
const getLanguage          = require('../base/language').get;
const localize             = require('../base/localize').localize;
const Login                = require('../base/login');
const State                = require('../base/storage').State;
const getPropertyValue     = require('../base/utility').getPropertyValue;
const getLoginToken        = require('../common_functions/common_functions').getLoginToken;
const SessionDurationLimit = require('../common_functions/session_duration_limit');
const getAppId             = require('../../config').getAppId;
const getSocketURL         = require('../../config').getSocketURL;
const Cookies              = require('../../lib/js-cookie');

/*
 * It provides a abstraction layer over native javascript Websocket.
 *
 * Provide additional functionality like if connection is close, open
 * it again and process the buffered requests
 *
 *
 * Usage:
 *
 * `BinarySocket.init()` to initiate the connection
 * `BinarySocket.send({contracts_for : 1})` to send message to server
 */
const BinarySocketClass = function() {
    'use strict';

    let binarySocket,
        bufferedSends = [],
        manualClosed = false,
        events = {},
        authorized = false,
        req_number = 0,
        req_id     = 0,
        wrongAppId = 0;

    const timeouts  = {};
    const socketUrl = getSocketURL() + '?app_id=' + getAppId() + '&l=' + getLanguage();
    const promises  = {};
    const no_duplicate_requests = [
        'authorize',
        'get_settings',
        'residence_list',
        'landing_company',
    ];
    const waiting_list = {
        items: {},
        add  : (msg_type, promise_obj) => {
            if (!waiting_list.items[msg_type]) {
                waiting_list.items[msg_type] = [];
            }
            waiting_list.items[msg_type].push(promise_obj);
        },
        resolve: (response) => {
            const msg_type = response.msg_type;
            const this_promises = waiting_list.items[msg_type];
            if (this_promises && this_promises.length) {
                this_promises.forEach((pr) => {
                    if (!waiting_list.another_exists(pr, msg_type)) {
                        pr.resolve(response);
                    }
                });
                waiting_list.items[msg_type] = [];
            }
        },
        another_exists: (pr, msg_type) => (
            Object.keys(waiting_list.items)
                .some(type => (
                    type !== msg_type &&
                    $.inArray(pr, waiting_list.items[type]) >= 0
                ))
        ),
    };

    const clearTimeouts = function() {
        Object.keys(timeouts).forEach(function(key) {
            clearTimeout(timeouts[key]);
            delete timeouts[key];
        });
    };

    const isReady = function () {
        return binarySocket && binarySocket.readyState === 1;
    };

    const isClose = function () {
        return !binarySocket || binarySocket.readyState === 2 || binarySocket.readyState === 3;
    };

    const sendBufferedSends = function () {
        while (bufferedSends.length > 0) {
            binarySocket.send(JSON.stringify(bufferedSends.shift()));
        }
    };

    const wait = (...msg_types) => {
        const promise_obj = new PromiseClass();
        let is_resolved = true;
        msg_types.forEach((msg_type) => {
            const last_response = State.get(['response', msg_type]);
            if (!last_response) {
                if (msg_type !== 'authorize' || Client.isLoggedIn()) {
                    waiting_list.add(msg_type, promise_obj);
                    is_resolved = false;
                }
            } else if (msg_types.length === 1) {
                promise_obj.resolve(last_response);
            }
        });
        if (is_resolved) {
            promise_obj.resolve();
        }
        return promise_obj.promise;
    };

    const send = function(data, force_send) {
        const promise_obj = new PromiseClass();

        if (!force_send) {
            const msg_type = no_duplicate_requests.find(c => c in data);
            const last_response = State.get(['response', msg_type]);
            if (last_response) {
                promise_obj.resolve(last_response);
                return promise_obj.promise;
            }
        }

        if (!data.req_id) {
            data.req_id = ++req_id;
        }
        promises[data.req_id] = {
            callback : (response) => { promise_obj.resolve(response); },
            subscribe: !!data.subscribe,
        };

        if (isReady()) {
            if (!data.hasOwnProperty('passthrough') && !data.hasOwnProperty('verify_email')) {
                data.passthrough = {};
            }
            // temporary check
            if ((data.contracts_for || data.proposal) && !data.passthrough.hasOwnProperty('dispatch_to') && !State.get('is_mb_trading')) {
                data.passthrough.req_number = ++req_number;
                timeouts[req_number] = setTimeout(function() {
                    if (typeof reloadPage === 'function' && data.contracts_for) {
                        window.alert("The server didn't respond to the request:\n\n" + JSON.stringify(data) + '\n\n');
                        reloadPage();
                    } else {
                        $('.price_container').hide();
                    }
                }, 60 * 1000);
            } else if (data.contracts_for && !data.passthrough.hasOwnProperty('dispatch_to') && State.get('is_mb_trading')) {
                data.passthrough.req_number = ++req_number;
                timeouts[req_number] = setTimeout(function() {
                    MBTradePage.onDisconnect();
                }, 10 * 1000);
            }

            binarySocket.send(JSON.stringify(data));
        } else {
            bufferedSends.push(data);
            if (isClose()) {
                init(1);
            }
        }

        return promise_obj.promise;
    };

    const setResidence = (residence) => {
        if (residence && !Cookies.get('residence')) {
            Client.setCookie('residence', residence);
            Client.set('residence', residence);
            send({ landing_company: residence });
        }
    };

    const init = function (es) {
        if (wrongAppId === getAppId()) {
            return;
        }
        if (!es) {
            events = {};
        }
        if (typeof es === 'object') {
            bufferedSends = [];
            manualClosed = false;
            events = es;
            clearTimeouts();
        }

        if (isClose()) {
            binarySocket = new WebSocket(socketUrl);<commit_msg>fix sending of landing company<commit_after>const MBTradePage          = require('./mb_trade/mb_tradepage');
const TradePage_Beta       = require('./trade/beta/tradepage');
const Highchart            = require('./trade/charts/highchartws').Highchart;
const reloadPage           = require('./trade/common').reloadPage;
const Notifications        = require('./trade/notifications').Notifications;
const WSTickDisplay        = require('./trade/tick_trade').WSTickDisplay;
const TradePage            = require('./trade/tradepage');
const ViewPopupWS          = require('./user/view_popup/view_popupws');
const ViewBalanceUI        = require('./user/viewbalance/viewbalance.ui').ViewBalanceUI;
const Client               = require('../base/client');
const Clock                = require('../base/clock');
const GTM                  = require('../base/gtm');
const Header               = require('../base/header');
const getLanguage          = require('../base/language').get;
const localize             = require('../base/localize').localize;
const Login                = require('../base/login');
const State                = require('../base/storage').State;
const getPropertyValue     = require('../base/utility').getPropertyValue;
const getLoginToken        = require('../common_functions/common_functions').getLoginToken;
const SessionDurationLimit = require('../common_functions/session_duration_limit');
const getAppId             = require('../../config').getAppId;
const getSocketURL         = require('../../config').getSocketURL;
const Cookies              = require('../../lib/js-cookie');

/*
 * It provides a abstraction layer over native javascript Websocket.
 *
 * Provide additional functionality like if connection is close, open
 * it again and process the buffered requests
 *
 *
 * Usage:
 *
 * `BinarySocket.init()` to initiate the connection
 * `BinarySocket.send({contracts_for : 1})` to send message to server
 */
const BinarySocketClass = function() {
    'use strict';

    let binarySocket,
        bufferedSends = [],
        manualClosed = false,
        events = {},
        authorized = false,
        req_number = 0,
        req_id     = 0,
        wrongAppId = 0;

    const timeouts  = {};
    const socketUrl = getSocketURL() + '?app_id=' + getAppId() + '&l=' + getLanguage();
    const promises  = {};
    const no_duplicate_requests = [
        'authorize',
        'get_settings',
        'residence_list',
        'landing_company',
    ];
    const waiting_list = {
        items: {},
        add  : (msg_type, promise_obj) => {
            if (!waiting_list.items[msg_type]) {
                waiting_list.items[msg_type] = [];
            }
            waiting_list.items[msg_type].push(promise_obj);
        },
        resolve: (response) => {
            const msg_type = response.msg_type;
            const this_promises = waiting_list.items[msg_type];
            if (this_promises && this_promises.length) {
                this_promises.forEach((pr) => {
                    if (!waiting_list.another_exists(pr, msg_type)) {
                        pr.resolve(response);
                    }
                });
                waiting_list.items[msg_type] = [];
            }
        },
        another_exists: (pr, msg_type) => (
            Object.keys(waiting_list.items)
                .some(type => (
                    type !== msg_type &&
                    $.inArray(pr, waiting_list.items[type]) >= 0
                ))
        ),
    };

    const clearTimeouts = function() {
        Object.keys(timeouts).forEach(function(key) {
            clearTimeout(timeouts[key]);
            delete timeouts[key];
        });
    };

    const isReady = function () {
        return binarySocket && binarySocket.readyState === 1;
    };

    const isClose = function () {
        return !binarySocket || binarySocket.readyState === 2 || binarySocket.readyState === 3;
    };

    const sendBufferedSends = function () {
        while (bufferedSends.length > 0) {
            binarySocket.send(JSON.stringify(bufferedSends.shift()));
        }
    };

    const wait = (...msg_types) => {
        const promise_obj = new PromiseClass();
        let is_resolved = true;
        msg_types.forEach((msg_type) => {
            const last_response = State.get(['response', msg_type]);
            if (!last_response) {
                if (msg_type !== 'authorize' || Client.isLoggedIn()) {
                    waiting_list.add(msg_type, promise_obj);
                    is_resolved = false;
                }
            } else if (msg_types.length === 1) {
                promise_obj.resolve(last_response);
            }
        });
        if (is_resolved) {
            promise_obj.resolve();
        }
        return promise_obj.promise;
    };

    const send = function(data, force_send) {
        const promise_obj = new PromiseClass();

        if (!force_send) {
            const msg_type = no_duplicate_requests.find(c => c in data);
            const last_response = State.get(['response', msg_type]);
            if (last_response) {
                promise_obj.resolve(last_response);
                return promise_obj.promise;
            }
        }

        if (!data.req_id) {
            data.req_id = ++req_id;
        }
        promises[data.req_id] = {
            callback : (response) => { promise_obj.resolve(response); },
            subscribe: !!data.subscribe,
        };

        if (isReady()) {
            if (!data.hasOwnProperty('passthrough') && !data.hasOwnProperty('verify_email')) {
                data.passthrough = {};
            }
            // temporary check
            if ((data.contracts_for || data.proposal) && !data.passthrough.hasOwnProperty('dispatch_to') && !State.get('is_mb_trading')) {
                data.passthrough.req_number = ++req_number;
                timeouts[req_number] = setTimeout(function() {
                    if (typeof reloadPage === 'function' && data.contracts_for) {
                        window.alert("The server didn't respond to the request:\n\n" + JSON.stringify(data) + '\n\n');
                        reloadPage();
                    } else {
                        $('.price_container').hide();
                    }
                }, 60 * 1000);
            } else if (data.contracts_for && !data.passthrough.hasOwnProperty('dispatch_to') && State.get('is_mb_trading')) {
                data.passthrough.req_number = ++req_number;
                timeouts[req_number] = setTimeout(function() {
                    MBTradePage.onDisconnect();
                }, 10 * 1000);
            }

            binarySocket.send(JSON.stringify(data));
        } else {
            bufferedSends.push(data);
            if (isClose()) {
                init(1);
            }
        }

        return promise_obj.promise;
    };

    const setResidence = (residence) => {
        if (residence) {
            Client.setCookie('residence', residence);
            Client.set('residence', residence);
            send({ landing_company: residence });
        }
    };

    const init = function (es) {
        if (wrongAppId === getAppId()) {
            return;
        }
        if (!es) {
            events = {};
        }
        if (typeof es === 'object') {
            bufferedSends = [];
            manualClosed = false;
            events = es;
            clearTimeouts();
        }

        if (isClose()) {
            binarySocket = new WebSocket(socketUrl);
{'fraction_non_alphanumeric': 0.13257021163316918, 'fraction_numerical': 0.0030613603087980834, 'mean_word_length': 1.799366616989568, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 27, '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': '4145504', 'n_tokens_mistral': 4181, 'n_tokens_neox': 3997, 'n_words': 752}