<commit_before>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @emails oncall+react_native
 * @format
 */

/* global device, element, by, expect */

const jestExpect = require('expect');
const {
  openComponentWithLabel,
  openExampleWithTitle,
} = require('../e2e-helpers');

describe('Switch', () => {
  beforeAll(async () => {
    await device.reloadReactNative();
    await openComponentWithLabel('<Switch>', '<Switch> Native boolean input');
  });

  describe('Switches can be set to true or false', () => {
    beforeAll(async () => {
      await openExampleWithTitle('Switches can be set to true or false');
    });

    it('Switch that starts off should switch', async () => {
      const testID = 'on-off-initial-off';
      const indicatorID = 'on-off-initial-off-indicator';

      await expect(element(by.id(testID))).toHaveValue('0');
      await expect(element(by.id(indicatorID))).toHaveText('Off');
      await element(by.id(testID)).tap();
      await expect(element(by.id(testID))).toHaveValue('1');
      await expect(element(by.id(indicatorID))).toHaveText('On');
    });

    it('Switch that starts on should switch', async () => {
      const testID = 'on-off-initial-on';
      const indicatorID = 'on-off-initial-on-indicator';

      await expect(element(by.id(testID))).toHaveValue('1');
      await expect(element(by.id(indicatorID))).toHaveText('On');
      await element(by.id(testID)).tap();
      await expect(element(by.id(testID))).toHaveValue('0');
      await expect(element(by.id(indicatorID))).toHaveText('Off');
    });
  });

  describe('Switches can be disabled', () => {
    beforeAll(async () => {
      await openExampleWithTitle('Switches can be disabled');
    });

    it('disabled switch should not toggle', async () => {
      const onTestID = 'disabled-initial-on';
      const offTestID = 'disabled-initial-off';
      const onIndicatorID = 'disabled-initial-on-indicator';
      const offIndicatorID = 'disabled-initial-off-indicator';

      await expect(element(by.id(onTestID))).toHaveValue('1');
      await expect(element(by.id(onIndicatorID))).toHaveText('On');

      try {
        await element(by.id(onTestID)).tap();
        throw new Error('Does not match');
      } catch (err) {
        jestExpect(err.message.message).toEqual(
          jestExpect.stringContaining(
            'Cannot perform action due to constraint(s) failure',
          ),
        );
      }
      await expect(element(by.id(onTestID))).toHaveValue('1');
      await expect(element(by.id(onIndicatorID))).toHaveText('On');

      await expect(element(by.id(offTestID))).toHaveValue('0');
      await expect(element(by.id(offIndicatorID))).toHaveText('Off');
      try {
        await element(by.id(offTestID)).tap();
        throw new Error('Does not match');
      } catch (err) {
        jestExpect(err.message.message).toEqual(
          jestExpect.stringContaining(
            'Cannot perform action due to constraint(s) failure',
          ),
        );
      }
      await expect(element(by.id(offTestID))).toHaveValue('0');
      await expect(element(by.id(offIndicatorID))).toHaveText('Off');
    });
  });
});
<commit_msg>Remove flaky Switch e2e test (#23410)<commit_after>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @emails oncall+react_native
 * @format
 */

/* global device, element, by, expect */

const jestExpect = require('expect');
const {
  openComponentWithLabel,
  openExampleWithTitle,
} = require('../e2e-helpers');

describe('Switch', () => {
  beforeAll(async () => {
    await device.reloadReactNative();
    await openComponentWithLabel('<Switch>', '<Switch> Native boolean input');
  });

  describe('Switches can be set to true or false', () => {
    beforeAll(async () => {
      await openExampleWithTitle('Switches can be set to true or false');
    });

    it('Switch that starts off should switch', async () => {
      const testID = 'on-off-initial-off';
      const indicatorID = 'on-off-initial-off-indicator';

      await expect(element(by.id(testID))).toHaveValue('0');
      await expect(element(by.id(indicatorID))).toHaveText('Off');
      await element(by.id(testID)).tap();
      await expect(element(by.id(testID))).toHaveValue('1');
      await expect(element(by.id(indicatorID))).toHaveText('On');
    });
  });

  describe('Switches can be disabled', () => {
    beforeAll(async () => {
      await openExampleWithTitle('Switches can be disabled');
    });

    it('disabled switch should not toggle', async () => {
      const onTestID = 'disabled-initial-on';
      const offTestID = 'disabled-initial-off';
      const onIndicatorID = 'disabled-initial-on-indicator';
      const offIndicatorID = 'disabled-initial-off-indicator';

      await expect(element(by.id(onTestID))).toHaveValue('1');
      await expect(element(by.id(onIndicatorID))).toHaveText('On');

      try {
        await element(by.id(onTestID)).tap();
        throw new Error('Does not match');
      } catch (err) {
        jestExpect(err.message.message).toEqual(
          jestExpect.stringContaining(
            'Cannot perform action due to constraint(s) failure',
          ),
        );
      }
      await expect(element(by.id(onTestID))).toHaveValue('1');
      await expect(element(by.id(onIndicatorID))).toHaveText('On');

      await expect(element(by.id(offTestID))).toHaveValue('0');
      await expect(element(by.id(offIndicatorID))).toHaveText('Off');
      try {
        await element(by.id(offTestID)).tap();
        throw new Error('Does not match');
      } catch (err) {
        jestExpect(err.message.message).toEqual(
          jestExpect.stringContaining(
            'Cannot perform action due to constraint(s) failure',
          ),
        );
      }
      await expect(element(by.id(offTestID))).toHaveValue('0');
      await expect(element(by.id(offIndicatorID))).toHaveText('Off');
    });
  });
});
<|endoftext|>


<commit_before>const moment              = require('moment');
const BinaryPjax          = require('../../../../base/binary_pjax');
const Client              = require('../../../../base/client');
const Header              = require('../../../../base/header');
const BinarySocket        = require('../../../../base/socket');
const Dialog              = require('../../../../common/attach_dom/dialog');
const jpClient            = require('../../../../common/country_base').jpClient;
const Currency            = require('../../../../common/currency');
const FormManager         = require('../../../../common/form_manager');
const DatePicker          = require('../../../../components/date_picker');
const TimePicker          = require('../../../../components/time_picker');
const dateValueChanged    = require('../../../../../_common/common_functions').dateValueChanged;
const localize            = require('../../../../../_common/localize').localize;
const scrollToHashSection = require('../../../../../_common/scroll').scrollToHashSection;

const SelfExclusion = (() => {
    let $form,
        fields,
        self_exclusion_data,
        set_30day_turnover,
        currency,
        is_gamstop_client,
        has_exclude_until;

    const form_id          = '#frm_self_exclusion';
    const timeout_date_id  = '#timeout_until_date';
    const timeout_time_id  = '#timeout_until_time';
    const exclude_until_id = '#exclude_until';
    const error_class      = 'errorfield';

    const onLoad = () => {
        $form = $(form_id);

        fields = {};
        $form.find('input').each(function () {
            fields[this.name] = '';
        });

        currency = Client.get('currency');

        $('.prepend_currency').parent().prepend(Currency.formatCurrency(currency));

        is_gamstop_client = /gb/.test(Client.get('residence')); // gamstop is only applicable for UK residence

        initDatePicker();
        getData(true);
    };

    const getData = (scroll) => {
        BinarySocket.send({ get_self_exclusion: 1 }).then((response) => {
            if (response.get_self_exclusion.exclude_until) {
                has_exclude_until = response.get_self_exclusion.exclude_until;
            }
            if (response.error) {
                if (response.error.code === 'ClientSelfExclusion') {
                    Client.sendLogoutRequest();
                }
                if (response.error.message) {
                    $('#msg_error').html(response.error.message).setVisibility(1);
                    $form.setVisibility(0);
                }
                return;
            }
            BinarySocket.send({ get_account_status: 1 }).then((data) => {
                const has_to_set_30day_turnover = !has_exclude_until && /ukrts_max_turnover_limit_not_set/.test(data.get_account_status.status);
                if (typeof set_30day_turnover === 'undefined') {
                    set_30day_turnover = has_to_set_30day_turnover;
                }
                $('#frm_self_exclusion').find('fieldset > div.form-row:not(.max_30day_turnover)').setVisibility(!has_to_set_30day_turnover);
                $('#description_max_30day_turnover').setVisibility(has_to_set_30day_turnover);
                $('#description').setVisibility(!has_to_set_30day_turnover);
                $('#gamstop_info_top').setVisibility(is_gamstop_client);
                $('#loading').setVisibility(0);
                $form.setVisibility(1);
                self_exclusion_data = response.get_self_exclusion;
                $.each(self_exclusion_data, (key, value) => {
                    fields[key] = value.toString();
                    if (key === 'timeout_until') {
                        const timeout = moment.unix(value);
                        const date = timeout.format('DD MMM, YYYY');
                        const time = timeout.format('HH:mm');
                        $form.find(timeout_date_id).val(date);
                        $form.find(timeout_time_id).val(time);
                        return;
                    }
                    $form.find(`#${key}`).val(value);
                });
                $form.find('#btn_submit').setVisibility(!has_exclude_until);
                bindValidation();
                if (scroll) scrollToHashSection();
            });
        });
    };

    const bindValidation = () => {
        const validations    = [{ request_field: 'set_self_exclusion', value: 1 }];
        const decimal_places = Currency.getDecimalPlaces(currency);

        $form.find('input[type="text"]').each(function () {
            const id = $(this).attr('id');

            if (/timeout_until|exclude_until/.test(id)) return;

            const checks  = [];
            const options = { min: 0 };
            if (id in self_exclusion_data) {
                checks.push('req');
                options.max = self_exclusion_data[id];
            } else {
                options.allow_empty = true;
            }
            if (!/session_duration_limit|max_open_bets/.test(id)) {
                options.type     = 'float';
                options.decimals = decimal_places;
            }
            checks.push(['number', options]);

            if (id === 'session_duration_limit') {
                checks.push(['custom', { func: validSessionDuration, message: 'Session duration limit cannot be more than 6 weeks.' }]);
            }

            validations.push({
                selector        : `#${id}`,
                validations     : checks,
                exclude_if_empty: 1,
            });
        });

        validations.push(
            {
                selector        : timeout_date_id,
                request_field   : 'timeout_until',
                re_check_field  : timeout_time_id,
                exclude_if_empty: 1,
                value           : getTimeout,
                validations     : [
                    ['custom', { func: () => ($(timeout_time_id).val() ? $(timeout_date_id).val().length : true),                         message: 'This field is required.' }],
                    ['custom', { func: value => !value.length || getMoment(timeout_date_id).isAfter(moment().subtract(1, 'days'), 'day'), message: 'Time out must be after today.' }],
                    ['custom', { func: value => !value.length || getMoment(timeout_date_id).isBefore(moment().add(6, 'weeks')),           message: 'Time out cannot be more than 6 weeks.' }],
                ],
            },
            {
                selector       : timeout_time_id,
                exclude_request: 1,
                re_check_field : timeout_date_id,
                validations    : [
                    ['custom', { func: () => ($(timeout_date_id).val() && getMoment(timeout_date_id).isSame(moment(), 'day') ? $(timeout_time_id).val().length : true), message: 'This field is required.' }],
                    ['custom', { func: value => !value.length || !$(timeout_date_id).attr('data-value') || (getTimeout() > moment().valueOf() / 1000), message: 'Time out cannot be in the past.' }],
                    ['custom', { func: validTime, message: 'Please select a valid time.' }],
                ],
            },
            {
                selector        : exclude_until_id,
                exclude_if_empty: 1,
                value           : () => getDate(exclude_until_id),
                validations     : [
                    ['custom', { func: value => !value.length || getMoment(exclude_until_id).isAfter(moment().add(6, 'months')), message: 'Exclude time cannot be less than 6 months.' }],
                    ['custom', { func: value => !value.length || getMoment(exclude_until_id).isBefore(moment().add(5, 'years')), message: 'Exclude time cannot be for more than 5 years.' }],
                ],
            });

        FormManager.init(form_id, validations);
        FormManager.handleSubmit({
            form_selector       : form_id,
            fnc_response_handler: setExclusionResponse,
            fnc_additional_check: additionalCheck,
            enable_button       : true,
        });
    };

    const validSessionDuration = value => (+value <= moment.duration(6, 'weeks').as('minutes'));
    const validTime            = value => !value.length || moment(value, 'HH:mm', true).isValid();

    const getDate    = (elm_id) => {
        const $elm = $(elm_id);
        return $elm.attr('data-value') || (!isNaN(new Date($elm.val()).getTime()) ? $elm.val() : '');
    };
    const getMoment  = elm_id => moment(new Date(getDate(elm_id)));
    const getTimeout = () => (getDate(timeout_date_id) ? (moment(new Date(`${getDate(timeout_date_id)}T${$(timeout_time_id).val()}`)).valueOf() / 1000).toFixed(0) : '');

    const initDatePicker = () => {
        // timeout_until
        TimePicker.init({ selector: timeout_time_id });
        DatePicker.init({
            selector: timeout_date_id,
            minDate : 0,
            maxDate : 6 * 7, // 6 weeks
        });

        // exclude_until
        DatePicker.init({
            selector: exclude_until_id,
            minDate : moment().add(6, 'months').add(1, 'day').toDate(),
            maxDate : 5 * 365, // 5 years
        });

        $(`${timeout_date_id}, ${exclude_until_id}`).change(function () {
            dateValueChanged(this, 'date');
            $('#gamstop_info_bottom').setVisibility(is_gamstop_client && this.getAttribute('data-value'));
        });
    };

    const additionalCheck = data => (
        new Promise((resolve) => {
            const is_changed = Object.keys(data).some(key => ( // using != in next line since response types is inconsistent
                key !== 'set_self_exclusion' && (!(key in self_exclusion_data) || self_exclusion_data[key] != data[key]) // eslint-disable-line eqeqeq
            ));
            if (!is_changed) {
                showFormMessage('You did not change anything.', false);
                resolve(false);
            }

            if ('timeout_until' in data || 'exclude_until' in data) {
                Dialog.confirm({
                    id     : 'timeout_until_dialog',
                    message: 'When you click "OK" you will be excluded from trading on the site until the selected date.',
                }).then((response) => resolve(response));
            } else {
                resolve(true);
            }
        })
    );

    const setExclusionResponse = (response) => {
        if (response.error) {
            const error_msg = response.error.message;
            let error_fld   = response.error.field;
            if (error_fld) {
                error_fld = /^timeout_until$/.test(error_fld) ? 'timeout_until_date' : error_fld;
                const $error_fld = $(`#${error_fld}`);
                $error_fld.siblings('.error-msg').setVisibility(1).html(error_msg);
                $.scrollTo($error_fld, 500, { offset: -10 });
            } else {
                showFormMessage(localize(error_msg), false);
            }
            return;
        }
        showFormMessage('Your changes have been updated.', true);
        Client.set('session_start', moment().unix()); // used to handle session duration limit
        const {exclude_until, timeout_until} = response.echo_req;
        if (exclude_until || timeout_until) {
            Client.set('excluded_until',
                exclude_until ? moment(exclude_until).unix()
                : timeout_until
            );
        }
        BinarySocket.send({ get_account_status: 1 }).then(() => {
            Header.displayAccountStatus();
            if (set_30day_turnover) {
                BinaryPjax.loadPreviousUrl();
            } else {
                getData();
                if (jpClient()) {
                    // need to update daily_loss_limit value inside jp_settings object
                    BinarySocket.send({ get_settings: 1 }, { forced: true });
                }
            }
        });
    };

    const showFormMessage = (msg, is_success) => {
        $('#msg_form')
            .attr('class', is_success ? 'success-msg' : error_class)
            .html(is_success ? $('<ul/>', { class: 'checked' }).append($('<li/>', { text: localize(msg) })) : localize(msg))
            .css('display', 'block')
            .delay(5000)
            .fadeOut(1000);
    };

    return {
        onLoad,
    };
})();

module.exports = SelfExclusion;
<commit_msg>Check landing company shortcode<commit_after>const moment              = require('moment');
const BinaryPjax          = require('../../../../base/binary_pjax');
const Client              = require('../../../../base/client');
const Header              = require('../../../../base/header');
const BinarySocket        = require('../../../../base/socket');
const Dialog              = require('../../../../common/attach_dom/dialog');
const jpClient            = require('../../../../common/country_base').jpClient;
const Currency            = require('../../../../common/currency');
const FormManager         = require('../../../../common/form_manager');
const DatePicker          = require('../../../../components/date_picker');
const TimePicker          = require('../../../../components/time_picker');
const dateValueChanged    = require('../../../../../_common/common_functions').dateValueChanged;
const localize            = require('../../../../../_common/localize').localize;
const scrollToHashSection = require('../../../../../_common/scroll').scrollToHashSection;

const SelfExclusion = (() => {
    let $form,
        fields,
        self_exclusion_data,
        set_30day_turnover,
        currency,
        is_gamstop_client,
        has_exclude_until;

    const form_id          = '#frm_self_exclusion';
    const timeout_date_id  = '#timeout_until_date';
    const timeout_time_id  = '#timeout_until_time';
    const exclude_until_id = '#exclude_until';
    const error_class      = 'errorfield';

    const onLoad = () => {
        $form = $(form_id);

        fields = {};
        $form.find('input').each(function () {
            fields[this.name] = '';
        });

        currency = Client.get('currency');

        $('.prepend_currency').parent().prepend(Currency.formatCurrency(currency));

        // gamstop is only applicable for UK residence & for MX, MLT clients
        is_gamstop_client = /gb/.test(Client.get('residence')) && /iom|malta/.test(Client.get('landing_company_shortcode'));

        initDatePicker();
        getData(true);
    };

    const getData = (scroll) => {
        BinarySocket.send({ get_self_exclusion: 1 }).then((response) => {
            if (response.get_self_exclusion.exclude_until) {
                has_exclude_until = response.get_self_exclusion.exclude_until;
            }
            if (response.error) {
                if (response.error.code === 'ClientSelfExclusion') {
                    Client.sendLogoutRequest();
                }
                if (response.error.message) {
                    $('#msg_error').html(response.error.message).setVisibility(1);
                    $form.setVisibility(0);
                }
                return;
            }
            BinarySocket.send({ get_account_status: 1 }).then((data) => {
                const has_to_set_30day_turnover = !has_exclude_until && /ukrts_max_turnover_limit_not_set/.test(data.get_account_status.status);
                if (typeof set_30day_turnover === 'undefined') {
                    set_30day_turnover = has_to_set_30day_turnover;
                }
                $('#frm_self_exclusion').find('fieldset > div.form-row:not(.max_30day_turnover)').setVisibility(!has_to_set_30day_turnover);
                $('#description_max_30day_turnover').setVisibility(has_to_set_30day_turnover);
                $('#description').setVisibility(!has_to_set_30day_turnover);
                $('#gamstop_info_top').setVisibility(is_gamstop_client);
                $('#loading').setVisibility(0);
                $form.setVisibility(1);
                self_exclusion_data = response.get_self_exclusion;
                $.each(self_exclusion_data, (key, value) => {
                    fields[key] = value.toString();
                    if (key === 'timeout_until') {
                        const timeout = moment.unix(value);
                        const date = timeout.format('DD MMM, YYYY');
                        const time = timeout.format('HH:mm');
                        $form.find(timeout_date_id).val(date);
                        $form.find(timeout_time_id).val(time);
                        return;
                    }
                    $form.find(`#${key}`).val(value);
                });
                $form.find('#btn_submit').setVisibility(!has_exclude_until);
                bindValidation();
                if (scroll) scrollToHashSection();
            });
        });
    };

    const bindValidation = () => {
        const validations    = [{ request_field: 'set_self_exclusion', value: 1 }];
        const decimal_places = Currency.getDecimalPlaces(currency);

        $form.find('input[type="text"]').each(function () {
            const id = $(this).attr('id');

            if (/timeout_until|exclude_until/.test(id)) return;

            const checks  = [];
            const options = { min: 0 };
            if (id in self_exclusion_data) {
                checks.push('req');
                options.max = self_exclusion_data[id];
            } else {
                options.allow_empty = true;
            }
            if (!/session_duration_limit|max_open_bets/.test(id)) {
                options.type     = 'float';
                options.decimals = decimal_places;
            }
            checks.push(['number', options]);

            if (id === 'session_duration_limit') {
                checks.push(['custom', { func: validSessionDuration, message: 'Session duration limit cannot be more than 6 weeks.' }]);
            }

            validations.push({
                selector        : `#${id}`,
                validations     : checks,
                exclude_if_empty: 1,
            });
        });

        validations.push(
            {
                selector        : timeout_date_id,
                request_field   : 'timeout_until',
                re_check_field  : timeout_time_id,
                exclude_if_empty: 1,
                value           : getTimeout,
                validations     : [
                    ['custom', { func: () => ($(timeout_time_id).val() ? $(timeout_date_id).val().length : true),                         message: 'This field is required.' }],
                    ['custom', { func: value => !value.length || getMoment(timeout_date_id).isAfter(moment().subtract(1, 'days'), 'day'), message: 'Time out must be after today.' }],
                    ['custom', { func: value => !value.length || getMoment(timeout_date_id).isBefore(moment().add(6, 'weeks')),           message: 'Time out cannot be more than 6 weeks.' }],
                ],
            },
            {
                selector       : timeout_time_id,
                exclude_request: 1,
                re_check_field : timeout_date_id,
                validations    : [
                    ['custom', { func: () => ($(timeout_date_id).val() && getMoment(timeout_date_id).isSame(moment(), 'day') ? $(timeout_time_id).val().length : true), message: 'This field is required.' }],
                    ['custom', { func: value => !value.length || !$(timeout_date_id).attr('data-value') || (getTimeout() > moment().valueOf() / 1000), message: 'Time out cannot be in the past.' }],
                    ['custom', { func: validTime, message: 'Please select a valid time.' }],
                ],
            },
            {
                selector        : exclude_until_id,
                exclude_if_empty: 1,
                value           : () => getDate(exclude_until_id),
                validations     : [
                    ['custom', { func: value => !value.length || getMoment(exclude_until_id).isAfter(moment().add(6, 'months')), message: 'Exclude time cannot be less than 6 months.' }],
                    ['custom', { func: value => !value.length || getMoment(exclude_until_id).isBefore(moment().add(5, 'years')), message: 'Exclude time cannot be for more than 5 years.' }],
                ],
            });

        FormManager.init(form_id, validations);
        FormManager.handleSubmit({
            form_selector       : form_id,
            fnc_response_handler: setExclusionResponse,
            fnc_additional_check: additionalCheck,
            enable_button       : true,
        });
    };

    const validSessionDuration = value => (+value <= moment.duration(6, 'weeks').as('minutes'));
    const validTime            = value => !value.length || moment(value, 'HH:mm', true).isValid();

    const getDate    = (elm_id) => {
        const $elm = $(elm_id);
        return $elm.attr('data-value') || (!isNaN(new Date($elm.val()).getTime()) ? $elm.val() : '');
    };
    const getMoment  = elm_id => moment(new Date(getDate(elm_id)));
    const getTimeout = () => (getDate(timeout_date_id) ? (moment(new Date(`${getDate(timeout_date_id)}T${$(timeout_time_id).val()}`)).valueOf() / 1000).toFixed(0) : '');

    const initDatePicker = () => {
        // timeout_until
        TimePicker.init({ selector: timeout_time_id });
        DatePicker.init({
            selector: timeout_date_id,
            minDate : 0,
            maxDate : 6 * 7, // 6 weeks
        });

        // exclude_until
        DatePicker.init({
            selector: exclude_until_id,
            minDate : moment().add(6, 'months').add(1, 'day').toDate(),
            maxDate : 5 * 365, // 5 years
        });

        $(`${timeout_date_id}, ${exclude_until_id}`).change(function () {
            dateValueChanged(this, 'date');
            $('#gamstop_info_bottom').setVisibility(is_gamstop_client && this.getAttribute('data-value'));
        });
    };

    const additionalCheck = data => (
        new Promise((resolve) => {
            const is_changed = Object.keys(data).some(key => ( // using != in next line since response types is inconsistent
                key !== 'set_self_exclusion' && (!(key in self_exclusion_data) || self_exclusion_data[key] != data[key]) // eslint-disable-line eqeqeq
            ));
            if (!is_changed) {
                showFormMessage('You did not change anything.', false);
                resolve(false);
            }

            if ('timeout_until' in data || 'exclude_until' in data) {
                Dialog.confirm({
                    id     : 'timeout_until_dialog',
                    message: 'When you click "OK" you will be excluded from trading on the site until the selected date.',
                }).then((response) => resolve(response));
            } else {
                resolve(true);
            }
        })
    );

    const setExclusionResponse = (response) => {
        if (response.error) {
            const error_msg = response.error.message;
            let error_fld   = response.error.field;
            if (error_fld) {
                error_fld = /^timeout_until$/.test(error_fld) ? 'timeout_until_date' : error_fld;
                const $error_fld = $(`#${error_fld}`);
                $error_fld.siblings('.error-msg').setVisibility(1).html(error_msg);
                $.scrollTo($error_fld, 500, { offset: -10 });
            } else {
                showFormMessage(localize(error_msg), false);
            }
            return;
        }
        showFormMessage('Your changes have been updated.', true);
        Client.set('session_start', moment().unix()); // used to handle session duration limit
        const {exclude_until, timeout_until} = response.echo_req;
        if (exclude_until || timeout_until) {
            Client.set('excluded_until',
                exclude_until ? moment(exclude_until).unix()
                : timeout_until
            );
        }
        BinarySocket.send({ get_account_status: 1 }).then(() => {
            Header.displayAccountStatus();
            if (set_30day_turnover) {
                BinaryPjax.loadPreviousUrl();
            } else {
                getData();
                if (jpClient()) {
                    // need to update daily_loss_limit value inside jp_settings object
                    BinarySocket.send({ get_settings: 1 }, { forced: true });
                }
            }
        });
    };

    const showFormMessage = (msg, is_success) => {
        $('#msg_form')
            .attr('class', is_success ? 'success-msg' : error_class)
            .html(is_success ? $('<ul/>', { class: 'checked' }).append($('<li/>', { text: localize(msg) })) : localize(msg))
            .css('display', 'block')
            .delay(5000)
            .fadeOut(1000);
    };

    return {
        onLoad,
    };
})();

module.exports = SelfExclusion;
<|endoftext|>


<commit_before>import {
    action,
    computed,
    observable }                   from 'mobx';
import { WS }                      from 'Services';
import {
    epochToMoment,
    getDiffDuration }              from 'Utils/Date';
import { formatPortfolioPosition } from './Helpers/format-response';
import {
    getDurationUnitText,
    getDurationUnitValue }         from './Helpers/details';
import {
    getDisplayStatus,
    getEndSpotTime,
    isUserSold,
    isValidToSell }                from '../Contract/Helpers/logic';
import BaseStore                   from '../../base-store';

export default class PortfolioStore extends BaseStore {
    @observable positions  = [];
    @observable is_loading = false;
    @observable error      = '';

    @action.bound
    initializePortfolio = () => {
        if (!this.root_store.client.is_logged_in) return;
        this.is_loading = true;

        WS.portfolio().then(this.portfolioHandler);
        WS.subscribeProposalOpenContract(null, this.proposalOpenContractHandler, false);
        WS.subscribeTransaction(this.transactionHandler, false);
    };

    @action.bound
    clearTable() {
        this.positions  = [];
        this.is_loading = false;
        this.error      = '';
    }

    @action.bound
    portfolioHandler(response) {
        this.is_loading = false;
        if ('error' in response) {
            this.error = response.error.message;
            return;
        }
        this.error = '';
        if (response.portfolio.contracts) {
            this.positions = response.portfolio.contracts
                .map(pos => formatPortfolioPosition(pos))
                .sort((pos1, pos2) => pos2.reference - pos1.reference); // new contracts first
        }
    }

    @action.bound
    transactionHandler(response) {
        if ('error' in response) {
            this.error = response.error.message;
        }
        if (!response.transaction) return;
        const { contract_id, action: act } = response.transaction;

        if (act === 'buy') {
            WS.portfolio().then((res) => {
                const new_pos = res.portfolio.contracts.find(pos => +pos.contract_id === +contract_id);
                if (!new_pos) return;
                this.pushNewPosition(new_pos);
            });
            // subscribe to new contract:
            WS.subscribeProposalOpenContract(contract_id, this.proposalOpenContractHandler, false);
        } else if (act === 'sell') {
            // TODO: Refactor with contract-store and use common helpers to handle contract result
            WS.proposalOpenContract(contract_id).then(action((proposal_response) => {
                // populate result details box for specified positions card
                this.populateResultDetails(proposal_response);
            }));
        }
    }

    @action.bound
    proposalOpenContractHandler(response) {
        if ('error' in response) return;

        const proposal = response.proposal_open_contract;
        const portfolio_position = this.positions.find((position) => +position.id === +proposal.contract_id);

        if (!portfolio_position) return;

        const prev_indicative = portfolio_position.indicative;
        const new_indicative  = +proposal.bid_price;
        const profit_loss     = +proposal.profit;

        portfolio_position.purchase_time = (proposal.is_forward_starting === 1) ?
            proposal.date_start
            :
            proposal.purchase_time;

        portfolio_position.bid_price        = proposal.bid_price;
        portfolio_position.indicative       = new_indicative;
        portfolio_position.underlying_code  = proposal.underlying;
        portfolio_position.underlying_name  = proposal.display_name;
        portfolio_position.profit_loss      = profit_loss;
        portfolio_position.tick_count       = proposal.tick_count;
        portfolio_position.is_valid_to_sell = isValidToSell(proposal);

        if (!proposal.is_valid_to_sell) {
            portfolio_position.status = 'no-resale';
        } else if (new_indicative > prev_indicative) {
            portfolio_position.status = 'price-moved-up';
        } else if (new_indicative < prev_indicative) {
            portfolio_position.status = 'price-moved-down';
        } else {
            portfolio_position.status = 'price-stable';
        }
    }

    @action.bound
    onClickSell(contract_id) {
        const i = this.positions.findIndex(pos => +pos.id === +contract_id);
        const bid_price = this.positions[i].bid_price;
        if (contract_id && bid_price) {
            WS.sell(contract_id, bid_price).then(this.handleSell);
        }
    }

    @action.bound
    handleSell(response) {
        const is_contract_mode = this.root_store.modules.smart_chart.is_contract_mode;
        // TODO: Refactor with ContractStore for re-drawing of chart markers and barriers
        // Toast messages are temporary UI for prompting user of sold contracts
        if (!is_contract_mode && response.error) {
            // If unable to sell due to error, give error via toast message if not in contract mode
            this.root_store.ui.addToastMessage({
                message: response.error.message,
                type   : 'error',
            });
        // Check if still in contract_mode
        } else if (is_contract_mode && !response.error) {
            WS.forget('proposal_open_contract', this.root_store.modules.contract.updateProposal, { contract_id: response.sell.contract_id });
            WS.proposalOpenContract(response.sell.contract_id).then(action((proposal_response) => {
                // update contract store proposal after sell
                this.root_store.modules.contract.updateProposal(proposal_response);
                this.populateResultDetails(proposal_response);
            }));
            // update contract store sell info after sell
            this.root_store.modules.contract.sell_info = {
                sell_price    : response.sell.sold_for,
                transaction_id: response.sell.transaction_id,
            };
        } else if (!is_contract_mode && response.sell.sold_for) {
            this.root_store.ui.addToastMessage({
                message: `Contract was sold for ${response.sell.sold_for}.`,
                type   : 'info',
            });
        }
    }

    populateResultDetails(response) {
        const contract_response = response.proposal_open_contract;
        const i = this.positions.findIndex(pos => +pos.id === +contract_response.contract_id);
        const sell_time = isUserSold(contract_response) ?
            +contract_response.date_expiry
            :
            getEndSpotTime(contract_response);
        const duration_diff =
            getDiffDuration(
                epochToMoment(this.positions[i].purchase_time || this.positions[i].date_start),
                epochToMoment(this.positions[i].expiry_time)
            );
        const duration = this.positions[i].tick_count ?
            this.positions[i].tick_count
            :
            getDurationUnitValue(duration_diff);

        this.positions[i].id_sell       = +contract_response.transaction_ids.sell;
        this.positions[i].barrier       = +contract_response.barrier;
        this.positions[i].duration      = duration;
        this.positions[i].duration_unit = getDurationUnitText(duration_diff);
        this.positions[i].entry_spot    = +contract_response.entry_spot;
        this.positions[i].sell_time     = sell_time;
        this.positions[i].result        = getDisplayStatus(contract_response);
    }

    @action.bound
    pushNewPosition(new_pos) {
        this.positions.unshift(formatPortfolioPosition(new_pos));
    }

    @action.bound
    removePositionById(contract_id) {
        let i = this.positions.findIndex(pos => +pos.id === +contract_id);
        // check if position to be removed is out of range from the maximum amount rendered in drawer
        if (this.positions.length > 4) i += 1;
        this.positions.splice(i, 1);
    }

    @action.bound
    accountSwitcherListener () {
        return new Promise((resolve) => {
            this.clearTable();
            WS.forgetAll('proposal_open_contract', 'transaction');
            return resolve(this.initializePortfolio());
        });
    }

    @action.bound
    onMount() {
        this.onSwitchAccount(this.accountSwitcherListener.bind(null));
        if (this.positions.length === 0) {
            this.initializePortfolio();
        }
    }

    @action.bound
    onUnmount() {
        this.disposeSwitchAccount();
        // keep data and connections for portfolio drawer on desktop
        if (this.root_store.ui.is_mobile) {
            this.clearTable();
            WS.forgetAll('proposal_open_contract', 'transaction');
        }
    }

    @computed
    get totals() {
        let indicative = 0;
        let payout     = 0;
        let purchase   = 0;

        this.positions.forEach((portfolio_pos) => {
            indicative += (+portfolio_pos.indicative);
            payout     += (+portfolio_pos.payout);
            purchase   += (+portfolio_pos.purchase);
        });
        return {
            indicative,
            payout,
            purchase,
        };
    }

    @computed
    get active_positions() {
        return this.positions;
    }

    @computed
    get is_empty() {
        return !this.is_loading && this.active_positions.length === 0;
    }
}
<commit_msg>fixed incorrect condition for showing toast error message<commit_after>import {
    action,
    computed,
    observable }                   from 'mobx';
import { WS }                      from 'Services';
import {
    epochToMoment,
    getDiffDuration }              from 'Utils/Date';
import { formatPortfolioPosition } from './Helpers/format-response';
import {
    getDurationUnitText,
    getDurationUnitValue }         from './Helpers/details';
import {
    getDisplayStatus,
    getEndSpotTime,
    isUserSold,
    isValidToSell }                from '../Contract/Helpers/logic';
import BaseStore                   from '../../base-store';

export default class PortfolioStore extends BaseStore {
    @observable positions  = [];
    @observable is_loading = false;
    @observable error      = '';

    @action.bound
    initializePortfolio = () => {
        if (!this.root_store.client.is_logged_in) return;
        this.is_loading = true;

        WS.portfolio().then(this.portfolioHandler);
        WS.subscribeProposalOpenContract(null, this.proposalOpenContractHandler, false);
        WS.subscribeTransaction(this.transactionHandler, false);
    };

    @action.bound
    clearTable() {
        this.positions  = [];
        this.is_loading = false;
        this.error      = '';
    }

    @action.bound
    portfolioHandler(response) {
        this.is_loading = false;
        if ('error' in response) {
            this.error = response.error.message;
            return;
        }
        this.error = '';
        if (response.portfolio.contracts) {
            this.positions = response.portfolio.contracts
                .map(pos => formatPortfolioPosition(pos))
                .sort((pos1, pos2) => pos2.reference - pos1.reference); // new contracts first
        }
    }

    @action.bound
    transactionHandler(response) {
        if ('error' in response) {
            this.error = response.error.message;
        }
        if (!response.transaction) return;
        const { contract_id, action: act } = response.transaction;

        if (act === 'buy') {
            WS.portfolio().then((res) => {
                const new_pos = res.portfolio.contracts.find(pos => +pos.contract_id === +contract_id);
                if (!new_pos) return;
                this.pushNewPosition(new_pos);
            });
            // subscribe to new contract:
            WS.subscribeProposalOpenContract(contract_id, this.proposalOpenContractHandler, false);
        } else if (act === 'sell') {
            // TODO: Refactor with contract-store and use common helpers to handle contract result
            WS.proposalOpenContract(contract_id).then(action((proposal_response) => {
                // populate result details box for specified positions card
                this.populateResultDetails(proposal_response);
            }));
        }
    }

    @action.bound
    proposalOpenContractHandler(response) {
        if ('error' in response) return;

        const proposal = response.proposal_open_contract;
        const portfolio_position = this.positions.find((position) => +position.id === +proposal.contract_id);

        if (!portfolio_position) return;

        const prev_indicative = portfolio_position.indicative;
        const new_indicative  = +proposal.bid_price;
        const profit_loss     = +proposal.profit;

        portfolio_position.purchase_time = (proposal.is_forward_starting === 1) ?
            proposal.date_start
            :
            proposal.purchase_time;

        portfolio_position.bid_price        = proposal.bid_price;
        portfolio_position.indicative       = new_indicative;
        portfolio_position.underlying_code  = proposal.underlying;
        portfolio_position.underlying_name  = proposal.display_name;
        portfolio_position.profit_loss      = profit_loss;
        portfolio_position.tick_count       = proposal.tick_count;
        portfolio_position.is_valid_to_sell = isValidToSell(proposal);

        if (!proposal.is_valid_to_sell) {
            portfolio_position.status = 'no-resale';
        } else if (new_indicative > prev_indicative) {
            portfolio_position.status = 'price-moved-up';
        } else if (new_indicative < prev_indicative) {
            portfolio_position.status = 'price-moved-down';
        } else {
            portfolio_position.status = 'price-stable';
        }
    }

    @action.bound
    onClickSell(contract_id) {
        const i = this.positions.findIndex(pos => +pos.id === +contract_id);
        const bid_price = this.positions[i].bid_price;
        if (contract_id && bid_price) {
            WS.sell(contract_id, bid_price).then(this.handleSell);
        }
    }

    @action.bound
    handleSell(response) {
        const is_contract_mode = this.root_store.modules.smart_chart.is_contract_mode;
        // TODO: Refactor with ContractStore for re-drawing of chart markers and barriers
        // Toast messages are temporary UI for prompting user of sold contracts
        if (response.error) {
            // If unable to sell due to error, give error via toast message if not in contract mode
            this.root_store.ui.addToastMessage({
                message: response.error.message,
                type   : 'error',
            });
        // Check if still in contract_mode
        } else if (is_contract_mode && !response.error) {
            WS.forget('proposal_open_contract', this.root_store.modules.contract.updateProposal, { contract_id: response.sell.contract_id });
            WS.proposalOpenContract(response.sell.contract_id).then(action((proposal_response) => {
                // update contract store proposal after sell
                this.root_store.modules.contract.updateProposal(proposal_response);
                this.populateResultDetails(proposal_response);
            }));
            // update contract store sell info after sell
            this.root_store.modules.contract.sell_info = {
                sell_price    : response.sell.sold_for,
                transaction_id: response.sell.transaction_id,
            };
            this.root_store.ui.addToastMessage({
                message: `Contract was sold for ${response.sell.sold_for}.`,
                type   : 'info',
            });
        }
    }

    populateResultDetails(response) {
        const contract_response = response.proposal_open_contract;
        const i = this.positions.findIndex(pos => +pos.id === +contract_response.contract_id);
        const sell_time = isUserSold(contract_response) ?
            +contract_response.date_expiry
            :
            getEndSpotTime(contract_response);
        const duration_diff =
            getDiffDuration(
                epochToMoment(this.positions[i].purchase_time || this.positions[i].date_start),
                epochToMoment(this.positions[i].expiry_time)
            );
        const duration = this.positions[i].tick_count ?
            this.positions[i].tick_count
            :
            getDurationUnitValue(duration_diff);

        this.positions[i].id_sell       = +contract_response.transaction_ids.sell;
        this.positions[i].barrier       = +contract_response.barrier;
        this.positions[i].duration      = duration;
        this.positions[i].duration_unit = getDurationUnitText(duration_diff);
        this.positions[i].entry_spot    = +contract_response.entry_spot;
        this.positions[i].sell_time     = sell_time;
        this.positions[i].result        = getDisplayStatus(contract_response);
    }

    @action.bound
    pushNewPosition(new_pos) {
        this.positions.unshift(formatPortfolioPosition(new_pos));
    }

    @action.bound
    removePositionById(contract_id) {
        let i = this.positions.findIndex(pos => +pos.id === +contract_id);
        // check if position to be removed is out of range from the maximum amount rendered in drawer
        if (this.positions.length > 4) i += 1;
        this.positions.splice(i, 1);
    }

    @action.bound
    accountSwitcherListener () {
        return new Promise((resolve) => {
            this.clearTable();
            WS.forgetAll('proposal_open_contract', 'transaction');
            return resolve(this.initializePortfolio());
        });
    }

    @action.bound
    onMount() {
        this.onSwitchAccount(this.accountSwitcherListener.bind(null));
        if (this.positions.length === 0) {
            this.initializePortfolio();
        }
    }

    @action.bound
    onUnmount() {
        this.disposeSwitchAccount();
        // keep data and connections for portfolio drawer on desktop
        if (this.root_store.ui.is_mobile) {
            this.clearTable();
            WS.forgetAll('proposal_open_contract', 'transaction');
        }
    }

    @computed
    get totals() {
        let indicative = 0;
        let payout     = 0;
        let purchase   = 0;

        this.positions.forEach((portfolio_pos) => {
            indicative += (+portfolio_pos.indicative);
            payout     += (+portfolio_pos.payout);
            purchase   += (+portfolio_pos.purchase);
        });
        return {
            indicative,
            payout,
            purchase,
        };
    }

    @computed
    get active_positions() {
        return this.positions;
    }

    @computed
    get is_empty() {
        return !this.is_loading && this.active_positions.length === 0;
    }
}
<|endoftext|>


<commit_before>function Page($page)
{
  // TL.log('Nouvelle page.');
  this.$page = $page;
}

Page.prototype.obtenirMessages = function()
{
  // TL.log('page.obtenirMessages()');
  var msgs = [];
  this.trouver('.bloc-message-forum').each(function() {
    msgs.push(new Message($(this)));
  });
  return msgs;
};

// Appele quand il y a des nouveaux messages
Page.prototype.maj = function()
{
  TL.log('Nouveaux messages ! Execution favicon/son/spoilers');
  if(localStorage.topiclive_son == 'true') {
    try { TL.son.play(); }
    catch(err) { TL.log('### Erreur son : ' + err); }
  }
  try { if(!TL.ongletActif) TL.favicon.maj('' + TL.nvxMessages); }
  catch(err) { TL.log('### Erreur favicon (maj) : ' + err); }
  try { jsli.Transformation(); }
  catch(err) { TL.log('### Erreur jsli.Transformation() : ' + err); }

  TL.log('Envoi de topiclive:doneprocessing');
  dispatchEvent(new CustomEvent('topiclive:doneprocessing', {
    'detail': { jvcake: TL.jvCake }
  }));
};

Page.prototype.scan = function()
{
  TL.log('Scan de la page');
  TL.ajaxTs = this.trouver('#ajax_timestamp_liste_messages').val();
  TL.ajaxHash = this.trouver('#ajax_hash_liste_messages').val();

  if(localStorage.tl_connectes == 'true') {
    $('.nb-connect-fofo').text(this.trouver('.nb-connect-fofo').text());
  }

  if($('.conteneur-message').length === 0 || $('.pagi-fin-actif').length !== 0) {
    TL.log('Pas sur une derniere page : loop');
    TL.loop();
    return;
  }

  TL.formu.maj(TL.formu.obtenirFormulaire(this.$page).clone());
  var maj = false;

  // Liste de messages
  var nvMsgs = this.obtenirMessages();
  var anciensMsgs = TL.messages;

  TL.log('Verification des messages supprimes');
  if(!TL.estMP) {
    for(var i in anciensMsgs) {
      if(!anciensMsgs.hasOwnProperty(i)) continue; // fix chrome
      var supprimer = true;
      for(var j in nvMsgs) {
        if(!nvMsgs.hasOwnProperty(j)) continue; // fix chrome
        if(anciensMsgs[i].id_message == nvMsgs[j].id_message) {
          supprimer = false;
          break;
        }
      }
      if(supprimer) TL.messages[i].supprimer();
    }
  }

  TL.log('Verification des nouveaux messages et editions');
  var estMP = TL.estMP;
  for(var k in nvMsgs) {
    if(!nvMsgs.hasOwnProperty(k)) continue; // fix chrome
    var nv = true;
    for(var l in anciensMsgs) {
      if(!anciensMsgs.hasOwnProperty(l)) continue; // fix chrome
      if(TL.estMP) {
        if(anciensMsgs[l].$message.text() == nvMsgs[k].$message.text()) {
          nv = false;
          break;
        }
      } else {
        if(anciensMsgs[l].id_message == nvMsgs[k].id_message) {
          nv = false;
          anciensMsgs[l].update(nvMsgs[k]);
          break;
        }
      }
    }
    if(nv) {
      TL.log('Nouveau message !');
      TL.messages.push(nvMsgs[k]);
      TL.nvxMessages++;
      nvMsgs[k].afficher();
      maj = true;
    }
  }

  // Doit etre avant TL.charger()
  TL.majUrl(this);

  if(maj) {
    this.maj();
    TL.formu.forcerMaj = false;
  } else {
    TL.log('Aucun nouveau message.');
    if(TL.formu.forcerMaj) TL.charger();
  }

  TL.loop();
};

Page.prototype.trouver = function(chose)
{
  // TL.log('Page.trouver : ' + chose);
  return this.$page.find(chose);
};
<commit_msg>Catch erreurs<commit_after>function Page($page)
{
  // TL.log('Nouvelle page.');
  this.$page = $page;
}

Page.prototype.obtenirMessages = function()
{
  // TL.log('page.obtenirMessages()');
  var msgs = [];
  this.trouver('.bloc-message-forum').each(function() {
    msgs.push(new Message($(this)));
  });
  return msgs;
};

// Appele quand il y a des nouveaux messages
Page.prototype.maj = function()
{
  TL.log('Nouveaux messages ! Execution favicon/son/spoilers');
  if(localStorage.topiclive_son == 'true') {
    try { TL.son.play(); }
    catch(err) { TL.log('### Erreur son : ' + err); }
  }
  try { if(!TL.ongletActif) TL.favicon.maj('' + TL.nvxMessages); }
  catch(err) { TL.log('### Erreur favicon (maj) : ' + err); }
  try { jsli.Transformation(); }
  catch(err) { TL.log('### Erreur jsli.Transformation() : ' + err); }

  TL.log('Envoi de topiclive:doneprocessing');
  dispatchEvent(new CustomEvent('topiclive:doneprocessing', {
    'detail': { jvcake: TL.jvCake }
  }));
};

Page.prototype.scan = function()
{
  TL.log('Scan de la page');
  TL.ajaxTs = this.trouver('#ajax_timestamp_liste_messages').val();
  TL.ajaxHash = this.trouver('#ajax_hash_liste_messages').val();

  if(localStorage.tl_connectes == 'true') {
    $('.nb-connect-fofo').text(this.trouver('.nb-connect-fofo').text());
  }

  if($('.conteneur-message').length === 0 || $('.pagi-fin-actif').length !== 0) {
    TL.log('Pas sur une derniere page : loop');
    TL.loop();
    return;
  }

  TL.formu.maj(TL.formu.obtenirFormulaire(this.$page).clone());
  var maj = false;

  // Liste de messages
  var nvMsgs = this.obtenirMessages();
  var anciensMsgs = TL.messages;

  TL.log('Verification des messages supprimes');
  try {
  if(!TL.estMP) {
    for(var i in anciensMsgs) {
      if(!anciensMsgs.hasOwnProperty(i)) continue; // fix chrome
      var supprimer = true;
      for(var j in nvMsgs) {
        if(!nvMsgs.hasOwnProperty(j)) continue; // fix chrome
        if(anciensMsgs[i].id_message == nvMsgs[j].id_message) {
          supprimer = false;
          break;
        }
      }
      if(supprimer) TL.messages[i].supprimer();
    }
  }
  } catch(err) { TL.log('### Erreur messages supprimes : ' + err); }

  TL.log('Verification des nouveaux messages et editions');
  try {
  var estMP = TL.estMP;
  for(var k in nvMsgs) {
    if(!nvMsgs.hasOwnProperty(k)) continue; // fix chrome
    var nv = true;
    for(var l in anciensMsgs) {
      if(!anciensMsgs.hasOwnProperty(l)) continue; // fix chrome
      if(TL.estMP) {
        if(anciensMsgs[l].$message.text() == nvMsgs[k].$message.text()) {
          nv = false;
          break;
        }
      } else {
        if(anciensMsgs[l].id_message == nvMsgs[k].id_message) {
          nv = false;
          anciensMsgs[l].update(nvMsgs[k]);
          break;
        }
      }
    }
    if(nv) {
      TL.log('Nouveau message !');
      TL.messages.push(nvMsgs[k]);
      TL.nvxMessages++;
      nvMsgs[k].afficher();
      maj = true;
    }
  }
  } catch(err) { TL.log('Erreur nouveaux messages : ' + err); }

  // Doit etre avant TL.charger()
  TL.majUrl(this);

  if(maj) {
    this.maj();
    TL.formu.forcerMaj = false;
  } else {
    TL.log('Aucun nouveau message.');
    if(TL.formu.forcerMaj) TL.charger();
  }

  TL.loop();
};

Page.prototype.trouver = function(chose)
{
  // TL.log('Page.trouver : ' + chose);
  return this.$page.find(chose);
};
<|endoftext|>


<commit_before>angular.module(PKG.name + '.commons')
  .directive('myViewQueries', function () {

    return {
      restrict: 'E',
      scope: {
        panel: '='
      },
      templateUrl: 'view-queries/view-queries.html',
      controller: function ($scope, MyDataSource, $state, EventPipe) {
        var dataSrc = new MyDataSource($scope);
        $scope.queries = [];

        $scope.getQueries = function() {
          dataSrc
            .request({
              _cdapNsPath: '/data/explore/queries',
              method: 'GET'
            })
            .then(function (queries) {

              $scope.queries = queries;

              // Polling for status
              angular.forEach($scope.queries, function(q) {
                if (q.status !== 'FINISHED') {
                  q.pollid = dataSrc.poll({
                    _cdapPath: '/data/explore/queries/' +
                                q.query_handle + '/status',
                    interval: 1000
                  }, function(res) {
                    q.status = res.status;

                    if (res.status === 'FINISHED') {
                      dataSrc.stopPoll(q.pollid);
                    }
                  });
                }
              });

              angular.forEach($scope.queries, function(query) {
                query.isOpen = false;
              });
            });
        };

        EventPipe.on('explore.newQuery', function() {
          $scope.getQueries();
        });

        $scope.getQueries();

        $scope.responses = {};

        $scope.fetchResult = function(query) {
          if (query.status !== 'FINISHED') {
            return;
          }

          // Close other accordion
          angular.forEach($scope.queries, function(q) {
            q.isOpen = false;
          });

          query.isOpen = !query.isOpen;

          if (query.isOpen) {
            $scope.responses.request = query;

            // request schema
            dataSrc
              .request({
                _cdapPath: '/data/explore/queries/' +
                              query.query_handle + '/schema'
              })
              .then(function (result) {
                angular.forEach(result, function(v) {
                  v.name = v.name.split('.')[1];
                });

                $scope.responses.schema = result;
              });

            // request preview
            dataSrc
              .request({
                _cdapPath: '/data/explore/queries/' +
                              query.query_handle + '/preview',
                method: 'POST'
              })
              .then(function (result) {
                $scope.responses.results = result;
              });
          }

        };

        $scope.download = function(query) {
          dataSrc
            .request({
              _cdapPath: '/data/explore/queries/' +
                              query.query_handle + '/download',
              method: 'POST'
            })
            .then(function (res) {
              var element = angular.element('<a/>');
              element.attr({
                href: 'data:atachment/csv,' + encodeURIComponent(res),
                target: '_self',
                download: 'result.csv'
              })[0].click();
            });
        };

      }

    };

  });
<commit_msg>update event listener callback<commit_after>angular.module(PKG.name + '.commons')
  .directive('myViewQueries', function () {

    return {
      restrict: 'E',
      scope: {
        panel: '='
      },
      templateUrl: 'view-queries/view-queries.html',
      controller: function ($scope, MyDataSource, $state, EventPipe) {
        var dataSrc = new MyDataSource($scope);
        $scope.queries = [];

        $scope.getQueries = function() {
          dataSrc
            .request({
              _cdapNsPath: '/data/explore/queries',
              method: 'GET'
            })
            .then(function (queries) {

              $scope.queries = queries;

              // Polling for status
              angular.forEach($scope.queries, function(q) {
                if (q.status !== 'FINISHED') {
                  q.pollid = dataSrc.poll({
                    _cdapPath: '/data/explore/queries/' +
                                q.query_handle + '/status',
                    interval: 1000
                  }, function(res) {
                    q.status = res.status;

                    if (res.status === 'FINISHED') {
                      dataSrc.stopPoll(q.pollid);
                    }
                  });
                }
              });

              angular.forEach($scope.queries, function(query) {
                query.isOpen = false;
              });
            });
        };

        EventPipe.on('explore.newQuery', $scope.getQueries);

        $scope.getQueries();

        $scope.responses = {};

        $scope.fetchResult = function(query) {
          if (query.status !== 'FINISHED') {
            return;
          }

          // Close other accordion
          angular.forEach($scope.queries, function(q) {
            q.isOpen = false;
          });

          query.isOpen = !query.isOpen;

          if (query.isOpen) {
            $scope.responses.request = query;

            // request schema
            dataSrc
              .request({
                _cdapPath: '/data/explore/queries/' +
                              query.query_handle + '/schema'
              })
              .then(function (result) {
                angular.forEach(result, function(v) {
                  v.name = v.name.split('.')[1];
                });

                $scope.responses.schema = result;
              });

            // request preview
            dataSrc
              .request({
                _cdapPath: '/data/explore/queries/' +
                              query.query_handle + '/preview',
                method: 'POST'
              })
              .then(function (result) {
                $scope.responses.results = result;
              });
          }

        };

        $scope.download = function(query) {
          dataSrc
            .request({
              _cdapPath: '/data/explore/queries/' +
                              query.query_handle + '/download',
              method: 'POST'
            })
            .then(function (res) {
              var element = angular.element('<a/>');
              element.attr({
                href: 'data:atachment/csv,' + encodeURIComponent(res),
                target: '_self',
                download: 'result.csv'
              })[0].click();
            });
        };

      }

    };

  });
<|endoftext|>


<commit_before>'use strict';

module.exports.util = function(){
    var mkdirp = require('mkdirp');
    var fs = require('fs');
    var getDirName = require('path').dirname;

    return {
        generate_random_string: function(){
            return Math.random().toString(36).slice(2);
        },
        writeFile: function(path, contents, format){
            mkdirp(getDirName(path), function(err){
                if (err) throw err;
                if (typeof format !== 'undefined'){
                    fs.writeFileSync(path, contents, format);
                }
                else{
                    fs.writeFileSync(path, contents);
                }
            });
        },
        removeFile: function(fileNameWithFullPath){
            fs.unlinkSync(fileNameWithFullPath);
        }
    }

}<commit_msg>'Util.js' deleted<commit_after><|endoftext|>


<commit_before>var through = require('through')
var asyncMap = require('slide').asyncMap
var uglifyJS = require('uglify-js')
var stylus = require('stylus')
var fs = require('fs')

var browserify = require('browserify')

module.exports = Compiler

function Compiler (opts) {
  if (opts.path_wilds[opts.path_wilds.length-1] !== '/') opts.path_wilds += '/'
  var Self = this
  var Wilds = opts.path_wilds
  var WildsProcessed = false
  var CSS = ''

  var b = browserify()
  b.add(opts.path_env)

  fs.readFile(opts.path_styl, function (e, buf) {
    if (e) console.error(e)
    if (!e) CSS += buf.toString()
  })

  this.s = through(HandleModule, Compile, {autoDestroy:false})

  function HandleModule (chunk) {
    var s = this
    var mod = JSON.parse(chunk.toString())

    // if module is updated make it fresh!
    if (WildsProcessed === true) mod.fresh = true

    // kind of hacky :(
    b.require(Wilds+mod.id+'.js',{expose:mod.id.toUpperCase()})

    // doesn't make sense...but for consistency...
    if (!mod.deps) s.queue(JSON.stringify(mod))

    function handleDep (file, next) {
      var dep = ''
      var ext = file.split('.')[1]
      fs.readFile(Wilds+file, function (e,buf) {
        if (e) console.error(e)
        dep = buf.toString()
        if (ext==='styl') CSS += dep
        if (ext==='html') mod[ext] = dep
        next()
      })
    }

    if (mod.deps) asyncMap(mod.deps, handleDep, function () {
      s.queue(JSON.stringify(mod))
    })
  }

  function Compile () {
    WildsProcessed = true
    Self.s.emit('data', JSON.stringify({stat:'mapReady'}))

    var bundleFile = fs.createWriteStream(opts.path_bundle)
    b.bundle().pipe(bundleFile)

    bundleFile.on('close', function () {
      console.log('wrote '+opts.path_bundle)
      if (opts.compress === true) {
        var min = uglifyJS.minify(opts.path_bundle)
        fs.writeFile(opts.path_bundle, min.code, function (e) {
          if (!e) console.log('wrote minified _bundle.js')
        })
      }
    })
    bundleFile.on('error', function (e) {
      console.error(e)
    })

    stylus.render(CSS, {filename:opts.path_css}, function (e, compiledCSS) {
      if (e) console.error(e)
      fs.writeFile(opts.path_css, compiledCSS, function (e) {
        if (e) cosole.error(e)
        console.log('wrote '+opts.path_css)
      })
    })
  }
}
<commit_msg>cleaned up<commit_after>// COMPILER

var through = require('through')
var asyncMap = require('slide').asyncMap
var uglifyJS = require('uglify-js')
var stylus = require('stylus')
var fs = require('fs')

var browserify = require('browserify')

module.exports = Compiler

function Compiler (opts) {
  if (opts.path_wilds[opts.path_wilds.length-1] !== '/') opts.path_wilds += '/'
  var Self = this
  var Wilds = opts.path_wilds
  var WildsProcessed = false
  var CSS = ''

  var b = browserify()
  b.add(opts.path_env)

  fs.readFile(opts.path_styl, function (e, buf) {
    if (e) console.error(e)
    if (!e) CSS += buf.toString()
  })

  this.s = through(HandleModule, Compile, {autoDestroy:false})

  function HandleModule (chunk) {
    var s = this
    var mod = JSON.parse(chunk.toString())

    b.require(Wilds+mod.id+'.js',{expose:mod.id})

    // if module is updated make it fresh!
    if (WildsProcessed === true) mod.fresh = true

    // handle deps
    if (!mod.deps) s.queue(chunk.toString())
    if (mod.deps) asyncMap(mod.deps, handleDep, function () {
      s.queue(JSON.stringify(mod))
      if (mod.fresh===true) Compile()
    })
    function handleDep (file, next) {
      var dep = ''
      var ext = file.split('.')[1]
      fs.readFile(Wilds+file, function (e,buf) {
        if (e) console.error(e)
        dep = buf.toString()
        if (ext==='styl') CSS += dep
        if (ext==='html') mod[ext] = dep
        next()
      })
    }
  }

  function Compile () {
    WildsProcessed = true
    Self.s.emit('data', JSON.stringify({stat:'mapReady'}))

    var bundleFile = fs.createWriteStream(opts.path_bundle)
    b.bundle().pipe(bundleFile)

    bundleFile.on('error', function (e) {
      console.error(e)
    })
    bundleFile.on('close', function () {
      console.log('wrote '+opts.path_bundle)
      if (opts.compress === true) {
        var min = uglifyJS.minify(opts.path_bundle)
        fs.writeFile(opts.path_bundle, min.code, function (e) {
          if (!e) console.log('wrote minified _bundle.js')
        })
      }
    })

    stylus.render(CSS, {filename:opts.path_css}, function (e, compiledCSS) {
      if (e) console.error(e)
      fs.writeFile(opts.path_css, compiledCSS, function (e) {
        if (e) cosole.error(e)
        console.log('wrote '+opts.path_css)
      })
    })
  }
}
<|endoftext|>


<commit_before>'use strict';
//greeting---------------------------------------------------------------------

var user = prompt('Hello there!  Before we begin, please tell me your name.');

alert('Welcome ' + user + '!');

var ready = confirm('Now, we are going to play a quick game.  I am going to ask you 7 questions about myself and you will make a guess as to the answers. The first 5 will be yes or no questions.  If you think it is true, type \'yes\' or \'y\' and if you think it is false type \'no\' or \'n\'.  Question 6 will have you guess a number and question 7 a place.  Ready to play?');

if(ready === true){
  alert('Alright, here we go!');
  console.log('user is ready');
} else {
  alert('Too bad.  We are playing anyway');
  console.log('user said not ready.  lol');
}

//questions, answers, arrays, counters-----------------------------------------

var question1 = 'Am I a native to Seattle?';
var question2 = 'Have I served in the military?';
var question3 = 'Do I have pets?';
var question4 = 'Is my favorite color green?';
var question5 = 'Can I play an instrument?';
var question6 = 'How old am I?';
var question7 = 'I have lived in 9 states besides Washington.  Can you guess one of them?';

var question1Correct = 'Correct!  I moved here 7 years ago.';
var question2Correct = 'Correct!  I served 4 years in the Air Force.';
var question3Correct = 'Correct!  I have two cats.  Well technically they are my roommate\'s cats, but since I take care of them and they love me more they are kind of mine.';
var question4Correct = 'Correct!  My favorite color is white.';
var question5Correct = 'Correct!  I can play the guitar.';

var question1Incorrect = 'Incorrect!  I moved here 7 years ago.';
var question2Incorrect = 'Incorrect!  I served 4 years in the Air Force.';
var question3Incorrect = 'Incorrect!  I have 2 cats';
var question4Incorrect = 'Incorrect!  My favorite color is white.';
var question5Incorrect = 'Incorrect!  I can play the guitar.';

var invalid1 = 'That is an invalid answer.  Please only type \'yes\', \'y\', \'no\' or \'n\'.';
var invalid2 = 'Again, that is invalid.  \'Yes\', \'y\', \'no\' or \'n\'.';
var invalid3 = 'Okay, you don\'t seem to understand this really simple concept.  Literally the only thing you should be typing is \'YES\', \'Y\', \'NO\' or \'N\'.  I\'m giving you one more chance to get it right then I am ending the game with all unanswered questions marked as wrong.';
var invalid4 = 'That\'s it.  Game over man.  Game over.';

var correct = 0;
var incorrect = 0;
var invalid = 0;
var ageCountdown = 4;
var placeGuesses = 6;

var allQuestions = [question1, question2, question3, question4, question5];
var allAnswers = ['no', 'yes', 'yes', 'no', 'yes'];
var allAnswersAlt = ['n', 'y', 'y', 'n', 'y'];
var incorrectAnswers = ['yes', 'no', 'no', 'yes', 'no'];
var incorrectAnswersAlt = ['y', 'n', 'n', 'y', 'n'];
var correctResponse = [question1Correct, question2Correct, question3Correct, question4Correct, question5Correct];
var incorrectResponse = [question1Incorrect, question2Incorrect, question3Incorrect, question4Incorrect, question5Incorrect];
var invalidResponse = [invalid1, invalid2, invalid3, invalid4];
var reviewAnswers = [];
var allResponse = [];
var placesLived = ['alaska', 'montana', 'connecticut', 'maine', 'arizona', 'texas', 'florida', 'nevada', 'idaho'];

//for loop questions 1-5 (the machine)-------------------------------------------------------
for(var i = 0; i < allQuestions.length; i++){
  var response = prompt(allQuestions[i]);
  allResponse.push(response);
  if(allResponse[i].toLowerCase() === allAnswers[i] || allResponse[i].toLowerCase() === allAnswersAlt[i]){
    correct++;
    console.log('Question ' + [i + 1] + ' answer correct');
    reviewAnswers.push('correct');
    alert(correctResponse[i]);
  } else if(allResponse[i].toLowerCase() === incorrectAnswers[i] || allResponse[i].toLowerCase() === incorrectAnswersAlt[i]){
      incorrect++;
      console.log('Question ' + [i + 1] + ' answer incorrect');
      reviewAnswers.push('incorrect');
      alert(incorrectResponse[i]);
  } else {
      console.log('answer invalid');
      alert(invalidResponse[invalid]);
      invalid++;
      allResponse.pop();
      if(invalid < 4){
        i--;
      } else {
        i+= 10;
    }
  }
}

//for loop question 6 ---------------------------------------------------------

for(var i = 0; i < 4; i++){
  var ageGuess = prompt(question6 + '  ' + ageCountdown + ' guess(es) left!');
  console.log('Question 6 guessed: ' + ageGuess);
  if(ageGuess == 35){
    alert('Good job!  You got it right!');
    reviewAnswers.push('correct');
    correct++;
    i+=5;
  } else if(ageGuess < 35){
      alert('Higher!  I\'m kinda old.');
      ageCountdown--;
  } else if(ageGuess > 35){
      alert('Hey!  I aint that old.  I still consider myself young.  Guess lower.');
      ageCountdown--;
  } else {
      alert('That is not a number.  That takes away one of your guesses.');
      ageCountdown--;
    }
}

if(ageCountdown === 0){
  alert('Sorry, out of guesses.');
  reviewAnswers.push('incorrect');
}

//question 7--------------------------------------------------------------------

while(placeGuesses > 0){
  var placeResponse = prompt(question7 + '  You have ' + placeGuesses + ' guess(es) left!');
  console.log('Question 7 guessed: ' + placeResponse);
  for(var i = 0; i < placesLived.length; i++){
    if(placeResponse.toLowerCase() === placesLived[i]){
      alert('Correct!  I have lived there!');
      i+=10;
      placeGuesses = 0;
      reviewAnswers.push('correct');
    } else {
      alert('Nope!  Guess Again!');
      placeGuesses--;
      if(placeGuesses === 0){
        alert('Sorry, out of guesses.');
        reviewAnswers.push('incorrect');
      }
    }
  }
}

//debugging loops--------------------------------------------------------------

for(var i = 0; i < allResponse.length; i++){
  console.log('Response ' + (i + 1) + ': ' + allResponse[i]);
}

//review-----------------------------------------------------------------------

alert('Okay ' + user + '. Let\'s see how you did.  Your answers are at the bottom of the page.');

document.write('You got ' + correct + ' out of 7 correct ' + user + '!
');

for(var i = 0; i < reviewAnswers.length; i++){
  document.write('Question ' + (i + 1) +': ' + reviewAnswers[i] + '
');
}
<commit_msg>refactored question 7.  it works now.<commit_after>'use strict';
//greeting---------------------------------------------------------------------

var user = prompt('Hello there!  Before we begin, please tell me your name.');

alert('Welcome ' + user + '!');

var ready = confirm('Now, we are going to play a quick game.  I am going to ask you 7 questions about myself and you will make a guess as to the answers. The first 5 will be yes or no questions.  If you think it is true, type \'yes\' or \'y\' and if you think it is false type \'no\' or \'n\'.  Question 6 will have you guess a number and question 7 a place.  Ready to play?');

if(ready === true){
  alert('Alright, here we go!');
  console.log('user is ready');
} else {
  alert('Too bad.  We are playing anyway');
  console.log('user said not ready.  lol');
}

//questions, answers, arrays, counters-----------------------------------------

var question1 = 'Am I a native to Seattle?';
var question2 = 'Have I served in the military?';
var question3 = 'Do I have pets?';
var question4 = 'Is my favorite color green?';
var question5 = 'Can I play an instrument?';
var question6 = 'How old am I?';
var question7 = 'I have lived in 9 states besides Washington.  Can you guess one of them?';

var question1Correct = 'Correct!  I moved here 7 years ago.';
var question2Correct = 'Correct!  I served 4 years in the Air Force.';
var question3Correct = 'Correct!  I have two cats.  Well technically they are my roommate\'s cats, but since I take care of them and they love me more they are kind of mine.';
var question4Correct = 'Correct!  My favorite color is white.';
var question5Correct = 'Correct!  I can play the guitar.';

var question1Incorrect = 'Incorrect!  I moved here 7 years ago.';
var question2Incorrect = 'Incorrect!  I served 4 years in the Air Force.';
var question3Incorrect = 'Incorrect!  I have 2 cats';
var question4Incorrect = 'Incorrect!  My favorite color is white.';
var question5Incorrect = 'Incorrect!  I can play the guitar.';

var invalid1 = 'That is an invalid answer.  Please only type \'yes\', \'y\', \'no\' or \'n\'.';
var invalid2 = 'Again, that is invalid.  \'Yes\', \'y\', \'no\' or \'n\'.';
var invalid3 = 'Okay, you don\'t seem to understand this really simple concept.  Literally the only thing you should be typing is \'YES\', \'Y\', \'NO\' or \'N\'.  I\'m giving you one more chance to get it right then I am ending the game with all unanswered questions marked as wrong.';
var invalid4 = 'That\'s it.  Game over man.  Game over.';

var correct = 0;
var incorrect = 0;
var invalid = 0;
var ageCountdown = 4;
var placeGuesses = 6;

var allQuestions = [question1, question2, question3, question4, question5];
var allAnswers = ['no', 'yes', 'yes', 'no', 'yes'];
var allAnswersAlt = ['n', 'y', 'y', 'n', 'y'];
var incorrectAnswers = ['yes', 'no', 'no', 'yes', 'no'];
var incorrectAnswersAlt = ['y', 'n', 'n', 'y', 'n'];
var correctResponse = [question1Correct, question2Correct, question3Correct, question4Correct, question5Correct];
var incorrectResponse = [question1Incorrect, question2Incorrect, question3Incorrect, question4Incorrect, question5Incorrect];
var invalidResponse = [invalid1, invalid2, invalid3, invalid4];
var reviewAnswers = [];
var allResponse = [];
var placesLived = ['alaska', 'montana', 'connecticut', 'maine', 'arizona', 'texas', 'florida', 'nevada', 'idaho'];

//for loop questions 1-5 (the machine)-------------------------------------------------------
for(var i = 0; i < allQuestions.length; i++){
  var response = prompt(allQuestions[i]);
  allResponse.push(response);
  if(allResponse[i].toLowerCase() === allAnswers[i] || allResponse[i].toLowerCase() === allAnswersAlt[i]){
    correct++;
    console.log('Question ' + [i + 1] + ' answer correct');
    reviewAnswers.push('correct');
    alert(correctResponse[i]);
  } else if(allResponse[i].toLowerCase() === incorrectAnswers[i] || allResponse[i].toLowerCase() === incorrectAnswersAlt[i]){
      incorrect++;
      console.log('Question ' + [i + 1] + ' answer incorrect');
      reviewAnswers.push('incorrect');
      alert(incorrectResponse[i]);
  } else {
      console.log('answer invalid');
      alert(invalidResponse[invalid]);
      invalid++;
      allResponse.pop();
      if(invalid < 4){
        i--;
      } else {
        i+= 10;
    }
  }
}

//for loop question 6 ---------------------------------------------------------

for(var i = 0; i < 4; i++){
  var ageGuess = prompt(question6 + '  ' + ageCountdown + ' guess(es) left!');
  console.log('Question 6 guessed: ' + ageGuess);
  if(ageGuess == 35){
    alert('Good job!  You got it right!');
    reviewAnswers.push('correct');
    correct++;
    i+=5;
  } else if(ageGuess < 35){
      alert('Higher!  I\'m kinda old.');
      ageCountdown--;
  } else if(ageGuess > 35){
      alert('Hey!  I aint that old.  I still consider myself young.  Guess lower.');
      ageCountdown--;
  } else {
      alert('That is not a number.  That takes away one of your guesses.');
      ageCountdown--;
    }
}

if(ageCountdown === 0){
  alert('Sorry, out of guesses.');
  reviewAnswers.push('incorrect');
}

//question 7--------------------------------------------------------------------

while(placeGuesses > 0){
  var placeResponse = prompt(question7 + '  You have ' + placeGuesses + ' guess(es) left!');
  console.log('Question 7 guessed: ' + placeResponse);
  for(var i = 0; i < placesLived.length; i++){
    if(placeResponse.toLowerCase() === placesLived[i]){
      alert('Correct!  I have lived there!');
      i+=10;
      placeGuesses = -10;
      reviewAnswers.push('correct');
    }
  }
  placeGuesses--;
  if(placeGuesses === 0){
    alert('Sorry!  Out of guesses!');
    reviewAnswers.push('incorrect');
  }
}

//debugging loops--------------------------------------------------------------

for(var i = 0; i < allResponse.length; i++){
  console.log('Response ' + (i + 1) + ': ' + allResponse[i]);
}

//review-----------------------------------------------------------------------

alert('Okay ' + user + '. Let\'s see how you did.  Your answers are at the bottom of the page.');

document.write('You got ' + correct + ' out of 7 correct ' + user + '!
');

for(var i = 0; i < reviewAnswers.length; i++){
  document.write('Question ' + (i + 1) +': ' + reviewAnswers[i] + '
');
}
<|endoftext|>


<commit_before>function createTreeItem(title, type) {
	return $('

').addClass(type).append($('').attr('href', '#').attr('title', ' ' + title + ' ').text(title));
}

function createDraggableTreeItem(title, type) {
	var item = createTreeItem(title, type);

	item.draggable({
		revert: 'invalid',
		helper: 'clone',
		cursor: 'move',
	});

	return item;
}

function createSeriesTree(seasons, options, now) {
	var list = $('

');

	$.each(seasons, function(key, value) {
		var tree = createSeasonTree(value.episodes, options, now);
		if (tree.children().size() == 0)
			return;

		var item = createTreeItem('Season ' + value.season, 'directory').append(tree);
		list.append(item);
	});

	return list.hide();
}

function createSeasonTree(episodes, options, now) {
	var list = $('

');

	$.each(episodes, function(key, value) {
		var state = getEpisodeState(value, now);

		if (!options.showSD && state === 'media_sd') return;
		if (!options.showHD && state === 'media_hd') return;
		if (!options.showUnknown && state === 'unknown') return;
		if (!options.showMissing && state === 'missing') return;
		if (!options.showUnaired && state === 'unaired') return;

		var item = createTreeItem(value.info.episode + ' ' + value.info.title, state);
		list.append(item);
	});

	return list.hide();
}

function getEpisodeState(episode, now) {
	if (typeof episode.file === 'undefined') {
		if (typeof epsiode.info.date !== 'undefined' && Date.parse(episode.info.date) > now)
			return 'unaired';

		return 'missing';
	}

	return fileExtToType(episode.file.fileExt);
}

function getFileState(filename) {
	var ext = filename.split('.').pop();
	return fileExtToType(ext);
}

function fileExtToType(ext) {
	switch (ext) {
		case 'mkv': {
			return 'media_hd';
		}

		case 'avi': {
			return 'media_sd';
		}

		default: {
			return 'unknown';
		}
	}
}

function log(msg, type) {
	var time = new Date();

	time = $('').addClass('date').text(time.format('dd/mm/yy HH:MM:ss'));
	msg = $('').text(msg);

	$('#log').prepend($('

').addClass(type).append(time).append(msg));
}

function createMediaTree(options) {
	var list = $('#leftbox > ul.filetree').empty();

	var now = new Date().getTime();

	if (typeof options === 'undefined')
		options = {};

	if (typeof options.showSD === 'undefined') options.showSD = true;
	if (typeof options.showHD === 'undefined') options.showHD = true;
	if (typeof options.showUnknown === 'undefined') options.showUnknown = true;
	if (typeof options.showMissing === 'undefined') options.showMissing = true;
	if (typeof options.showUnaired === 'undefined') options.showUnaired = true;

	$.each(library, function(key, value) {
		var tree = createSeriesTree(value.seasons, options, now);
		if (tree.children().size() == 0)
			return;

		var item = createTreeItem(value.title, 'directory').append(tree);
		list.append(item);
	});

	list.find('a').click(function() {
		$(this).parent().children('ul').slideToggle();
		return false;
	});

	// Find all missing episodes, and create drop targets
	list.find('li.missing a').droppable({
		accept: '#extramedia > ul > li, #extradls > ul > li',
		drop: function(event, ui) {
			var src = $(ui.draggable);
			var dest = $(this);

			console.log(dest);
			// TODO
		},
	});
}

var websocket_uri = 'ws://' + window.location.hostname + ':8990/socket';

// Array holding information for all of our episodes
var library = [];

// Options used when creating the media tree
var options = {
	showSD: true,
	showHD: true,
	showUnkown: true,
	showMissing: true,
	showUnaired: true,
};

$(document).ready( function() {
	$.getJSON('library.json', function(d) {
		library = d;

		createMediaTree(options);

		$('#buttons > li > input:checkbox').change(function() {
			var key = $(this).attr('name');

			if (typeof options[key] === 'undefined')
				return;

			options[key] = $(this).prop('checked');

			createMediaTree(options);
		});
	});

	$.getJSON('extramedia.json', function(d) {
		var list = $('#extramedia > ul.filetree');

		$.each(d, function(key, value) {
			var state = getFileState(value);
			var item = createDraggableTreeItem(value.substring(1), state);
			list.append(item);
		});

		list.find('a').click(function() {
			return false;
		})
	});

	$.getJSON('extradls.json', function(d) {
		var list = $('#extradls > ul.filetree');

		$.each(d, function(key, value) {
			var state = getFileState(value);
			var item = createDraggableTreeItem(value.substring(1), state);
			list.append(item);
		});

		list.find('a').click(function() {
			return false;
		})
	});

	var ws = new WebSocket(websocket_uri);
	ws.onopen = function() {
		log('Connection opened', 'connection');
	}

	ws.onmessage = function(e) {
		var msg = JSON.parse(e.data);
		switch (msg.type) {
			case 'LogMessage': {
				log(msg.value.message, msg.value.type.toLowerCase());
				break;
			}
		}
	};

	ws.onclose = function() {
		log('Connection closed', 'connection');
	}
});
<commit_msg>Fixing typo in last commit...<commit_after>function createTreeItem(title, type) {
	return $('

').addClass(type).append($('').attr('href', '#').attr('title', ' ' + title + ' ').text(title));
}

function createDraggableTreeItem(title, type) {
	var item = createTreeItem(title, type);

	item.draggable({
		revert: 'invalid',
		helper: 'clone',
		cursor: 'move',
	});

	return item;
}

function createSeriesTree(seasons, options, now) {
	var list = $('

');

	$.each(seasons, function(key, value) {
		var tree = createSeasonTree(value.episodes, options, now);
		if (tree.children().size() == 0)
			return;

		var item = createTreeItem('Season ' + value.season, 'directory').append(tree);
		list.append(item);
	});

	return list.hide();
}

function createSeasonTree(episodes, options, now) {
	var list = $('

');

	$.each(episodes, function(key, value) {
		var state = getEpisodeState(value, now);

		if (!options.showSD && state === 'media_sd') return;
		if (!options.showHD && state === 'media_hd') return;
		if (!options.showUnknown && state === 'unknown') return;
		if (!options.showMissing && state === 'missing') return;
		if (!options.showUnaired && state === 'unaired') return;

		var item = createTreeItem(value.info.episode + ' ' + value.info.title, state);
		list.append(item);
	});

	return list.hide();
}

function getEpisodeState(episode, now) {
	if (typeof episode.file === 'undefined') {
		if (typeof episode.info.date !== 'undefined' && Date.parse(episode.info.date) > now)
			return 'unaired';

		return 'missing';
	}

	return fileExtToType(episode.file.fileExt);
}

function getFileState(filename) {
	var ext = filename.split('.').pop();
	return fileExtToType(ext);
}

function fileExtToType(ext) {
	switch (ext) {
		case 'mkv': {
			return 'media_hd';
		}

		case 'avi': {
			return 'media_sd';
		}

		default: {
			return 'unknown';
		}
	}
}

function log(msg, type) {
	var time = new Date();

	time = $('').addClass('date').text(time.format('dd/mm/yy HH:MM:ss'));
	msg = $('').text(msg);

	$('#log').prepend($('

').addClass(type).append(time).append(msg));
}

function createMediaTree(options) {
	var list = $('#leftbox > ul.filetree').empty();

	var now = new Date().getTime();

	if (typeof options === 'undefined')
		options = {};

	if (typeof options.showSD === 'undefined') options.showSD = true;
	if (typeof options.showHD === 'undefined') options.showHD = true;
	if (typeof options.showUnknown === 'undefined') options.showUnknown = true;
	if (typeof options.showMissing === 'undefined') options.showMissing = true;
	if (typeof options.showUnaired === 'undefined') options.showUnaired = true;

	$.each(library, function(key, value) {
		var tree = createSeriesTree(value.seasons, options, now);
		if (tree.children().size() == 0)
			return;

		var item = createTreeItem(value.title, 'directory').append(tree);
		list.append(item);
	});

	list.find('a').click(function() {
		$(this).parent().children('ul').slideToggle();
		return false;
	});

	// Find all missing episodes, and create drop targets
	list.find('li.missing a').droppable({
		accept: '#extramedia > ul > li, #extradls > ul > li',
		drop: function(event, ui) {
			var src = $(ui.draggable);
			var dest = $(this);

			console.log(dest);
			// TODO
		},
	});
}

var websocket_uri = 'ws://' + window.location.hostname + ':8990/socket';

// Array holding information for all of our episodes
var library = [];

// Options used when creating the media tree
var options = {
	showSD: true,
	showHD: true,
	showUnkown: true,
	showMissing: true,
	showUnaired: true,
};

$(document).ready( function() {
	$.getJSON('library.json', function(d) {
		library = d;

		createMediaTree(options);

		$('#buttons > li > input:checkbox').change(function() {
			var key = $(this).attr('name');

			if (typeof options[key] === 'undefined')
				return;

			options[key] = $(this).prop('checked');

			createMediaTree(options);
		});
	});

	$.getJSON('extramedia.json', function(d) {
		var list = $('#extramedia > ul.filetree');

		$.each(d, function(key, value) {
			var state = getFileState(value);
			var item = createDraggableTreeItem(value.substring(1), state);
			list.append(item);
		});

		list.find('a').click(function() {
			return false;
		})
	});

	$.getJSON('extradls.json', function(d) {
		var list = $('#extradls > ul.filetree');

		$.each(d, function(key, value) {
			var state = getFileState(value);
			var item = createDraggableTreeItem(value.substring(1), state);
			list.append(item);
		});

		list.find('a').click(function() {
			return false;
		})
	});

	var ws = new WebSocket(websocket_uri);
	ws.onopen = function() {
		log('Connection opened', 'connection');
	}

	ws.onmessage = function(e) {
		var msg = JSON.parse(e.data);
		switch (msg.type) {
			case 'LogMessage': {
				log(msg.value.message, msg.value.type.toLowerCase());
				break;
			}
		}
	};

	ws.onclose = function() {
		log('Connection closed', 'connection');
	}
});
<|endoftext|>


<commit_before>var passport = require('passport')
    , BasicStrategy = require('passport-http').BasicStrategy
    , ClientPasswordStrategy = require('passport-oauth2-client-password').Strategy
    , BearerStrategy = require('passport-http-bearer').Strategy
    , db = require('./db').db()
    , crypto = require('crypto')

/**
 * These strategies are used to authenticate registered OAuth clients.
 * The authentication data may be delivered using the basic authentication scheme (recommended)
 * or the client strategy, which means that the authentication data is in the body of the request.
 */
passport.use("clientBasic", new BasicStrategy(
    function (clientId, clientSecret, done) {
        db.collection('clients').findOne({clientId: clientId}, function (err, client) {
            if (err) return done(err)
            if (!client) return done(null, false)
            if (!client.trustedClient) return done(null, false)

            if (client.clientSecret == clientSecret) return done(null, client)
            else return done(null, false)
        });
    }
));

passport.use("clientPassword", new ClientPasswordStrategy(
    function (clientId, clientSecret, done) {
        db.collection('clients').findOne({clientId: clientId}, function (err, client) {
            if (err) return done(err)
            if (!client) return done(null, false)
            if (!client.trustedClient) return done(null, false)

            if (client.clientSecret == clientSecret) return done(null, client)
            else return done(null, false)
        });
    }
));

/**
 * This strategy is used to authenticate users based on an access token (aka a
 * bearer token).
 */
passport.use("accessToken", new BearerStrategy(
    function (accessToken, done) {
        var accessTokenHash = crypto.createHash('sha1').update(accessToken).digest('hex')
        db.collection('accessTokens').findOne({token: accessTokenHash}, function (err, token) {
            if (err) return done(err)
            if (!token) return done(null, false)
            if (new Date() > token.expirationDate) {
                db.collection('accessTokens').delete({token: accessTokenHash}, function (err) { return done(err) })
            }

            db.collection('users').findOne({username: token.userId}, function (err, user) {
                if (err) return done(err)
                if (!user) return done(null, false)
                // no use of scopes for no
                var info = { scope: '*' }
                done(null, user, info);
            });
        });
    }
))
<commit_msg>Changed function call from delete to remove<commit_after>var passport = require('passport')
    , BasicStrategy = require('passport-http').BasicStrategy
    , ClientPasswordStrategy = require('passport-oauth2-client-password').Strategy
    , BearerStrategy = require('passport-http-bearer').Strategy
    , db = require('./db').db()
    , crypto = require('crypto')

/**
 * These strategies are used to authenticate registered OAuth clients.
 * The authentication data may be delivered using the basic authentication scheme (recommended)
 * or the client strategy, which means that the authentication data is in the body of the request.
 */
passport.use("clientBasic", new BasicStrategy(
    function (clientId, clientSecret, done) {
        db.collection('clients').findOne({clientId: clientId}, function (err, client) {
            if (err) return done(err)
            if (!client) return done(null, false)
            if (!client.trustedClient) return done(null, false)

            if (client.clientSecret == clientSecret) return done(null, client)
            else return done(null, false)
        });
    }
));

passport.use("clientPassword", new ClientPasswordStrategy(
    function (clientId, clientSecret, done) {
        db.collection('clients').findOne({clientId: clientId}, function (err, client) {
            if (err) return done(err)
            if (!client) return done(null, false)
            if (!client.trustedClient) return done(null, false)

            if (client.clientSecret == clientSecret) return done(null, client)
            else return done(null, false)
        });
    }
));

/**
 * This strategy is used to authenticate users based on an access token (aka a
 * bearer token).
 */
passport.use("accessToken", new BearerStrategy(
    function (accessToken, done) {
        var accessTokenHash = crypto.createHash('sha1').update(accessToken).digest('hex')
        db.collection('accessTokens').findOne({token: accessTokenHash}, function (err, token) {
            if (err) return done(err)
            if (!token) return done(null, false)
            if (new Date() > token.expirationDate) {
                db.collection('accessTokens').remove({token: accessTokenHash}, function (err) { return done(err) })
            }

            db.collection('users').findOne({username: token.userId}, function (err, user) {
                if (err) return done(err)
                if (!user) return done(null, false)
                // no use of scopes for no
                var info = { scope: '*' }
                done(null, user, info);
            });
        });
    }
))
<|endoftext|>