<commit_before>import { from as arrayFrom } from './array';

/*
 * Element closest polyfill, if needed
 * https://developer.mozilla.org/en-US/docs/Web/API/Element/closest
 * Returns null of not found
 */
if (typeof document !== "undefined" && window.Element && !Element.prototype.closest) {
    Element.prototype.closest = function(s) {
        const matches = (this.document || this.ownerDocument).querySelectorAll(s);
        let el = this;
        let i;
        do {
            i = matches.length;
            // eslint-disable-next-line no-empty
            while (--i >= 0 && matches.item(i) !== el) {}
        } while (i < 0 && (el = el.parentElement));
        return el;
    };
}

const dom = {};

// Determine if an element is an HTML Element
dom.isElement = function(el) {
    return el && el.nodeType === Node.ELEMENT_NODE;
};

// Determine if an HTML element is visible - Faster than CSS check
dom.isVisible = function(el) {
    return dom.isElement(el) &&
           document.body.contains(el) &&
           (el.offsetParent !== null || el.offsetWidth > 0 || el.offsetHeight > 0);
};

// Determine if an element is disabled
dom.isDisabled = function(el) {
    return !dom.isElemetn(el) ||
           el.disabled ||
           el.classList.contains('disabled') ||
           Boolean(el.getAttribute('disabled'));
};

// Select all elements matching selector. Returns [] if none found
dom.selectAll = function(selector, root) {
    if (!dom.isElement(root)) {
        root = document;
    }
    return arrayFrom(root.querySelectorAll(selector));
};

// Select a single element, returns null if not found
dom.select = function(selector, root) {
    if (!dom.isElement(root)) {
        root = document;
    }
    return root.querySelector(selector) || null;
};

// Finds closest element matching selector. Returns null if not found
dom.closest = function(selector, root) {
    if (!dom.isElement(root)) {
        return null;
    }
    const el = root.closest(selector);
    return el === root ? null : el;
};

dom.getById = function(id) {
    return document.getElementById(/^#/.test(id) ? id.slice(1) : id) || null;
};

export const isElement = dom.isElement;
export const isVisible = dom.isVisible;
export const isDisabled = dom.isDisabled;
export const closest = dom.closest;
export const getById = dom.getById;
export const selectAll = dom.selectAll;
export const select = dom.select;
<commit_msg>fix type<commit_after>import { from as arrayFrom } from './array';

/*
 * Element closest polyfill, if needed
 * https://developer.mozilla.org/en-US/docs/Web/API/Element/closest
 * Returns null of not found
 */
if (typeof document !== "undefined" && window.Element && !Element.prototype.closest) {
    Element.prototype.closest = function(s) {
        const matches = (this.document || this.ownerDocument).querySelectorAll(s);
        let el = this;
        let i;
        do {
            i = matches.length;
            // eslint-disable-next-line no-empty
            while (--i >= 0 && matches.item(i) !== el) {}
        } while (i < 0 && (el = el.parentElement));
        return el;
    };
}

const dom = {};

// Determine if an element is an HTML Element
dom.isElement = function(el) {
    return el && el.nodeType === Node.ELEMENT_NODE;
};

// Determine if an HTML element is visible - Faster than CSS check
dom.isVisible = function(el) {
    return dom.isElement(el) &&
           document.body.contains(el) &&
           (el.offsetParent !== null || el.offsetWidth > 0 || el.offsetHeight > 0);
};

// Determine if an element is disabled
dom.isDisabled = function(el) {
    return !dom.isElement(el) ||
           el.disabled ||
           el.classList.contains('disabled') ||
           Boolean(el.getAttribute('disabled'));
};

// Select all elements matching selector. Returns [] if none found
dom.selectAll = function(selector, root) {
    if (!dom.isElement(root)) {
        root = document;
    }
    return arrayFrom(root.querySelectorAll(selector));
};

// Select a single element, returns null if not found
dom.select = function(selector, root) {
    if (!dom.isElement(root)) {
        root = document;
    }
    return root.querySelector(selector) || null;
};

// Finds closest element matching selector. Returns null if not found
dom.closest = function(selector, root) {
    if (!dom.isElement(root)) {
        return null;
    }
    const el = root.closest(selector);
    return el === root ? null : el;
};

dom.getById = function(id) {
    return document.getElementById(/^#/.test(id) ? id.slice(1) : id) || null;
};

export const isElement = dom.isElement;
export const isVisible = dom.isVisible;
export const isDisabled = dom.isDisabled;
export const closest = dom.closest;
export const getById = dom.getById;
export const selectAll = dom.selectAll;
export const select = dom.select;
<|endoftext|>


<commit_before>hqDefine("reports/js/filters/main", [
    'jquery',
    'knockout',
    'hqwebapp/js/main',
    'reports/js/standard_hq_report',
    'reports/js/filters/select2s',
    'reports/js/filters/phone_number',
    'reports/js/filters/button_group',
    'reports/js/filters/schedule_instance',
    'select2-3.5.2-legacy/select2',
], function(
    $,
    ko,
    hqMain,
    standardHQReportModule,
    select2Filter,
    phoneNumberFilter,
    buttonGroup,
    scheduleInstanceFilter
) {
    var init = function() {
        // Datespans
        $('.report-filter-datespan').each(function() {
            var $filterRange = $(this);
            if ($filterRange.data("init")) {
                var separator = $filterRange.data('separator');
                var reportLabels = $filterRange.data('reportLabels');
                var standardHQReport = standardHQReportModule.getStandardHQReport();

                $filterRange.createDateRangePicker(
                    reportLabels, separator,
                    $filterRange.data('startDate'),
                    $filterRange.data('endDate')
                );
                $filterRange.on('change apply', function() {
                    var dates = $(this).val().split(separator);
                    $(standardHQReport.filterAccordion).trigger('hqreport.filter.datespan.startdate', dates[0]);
                    $('#report_filter_datespan_startdate').val(dates[0]);
                    $(standardHQReport.filterAccordion).trigger('hqreport.filter.datespan.enddate', dates[1]);
                    $('#report_filter_datespan_enddate').val(dates[1]);
                });
            }
        });

        // Date selector
        var $dateSelector = $("#filter_date_selector");
        if ($dateSelector.length && $dateSelector.data("init")) {
            $('#filter_date_selector').daterangepicker(
                {
                    locale: {
                        format: 'YYYY-MM-DD',
                    },
                    singleDatePicker: true,
                }
            );
        }

        // Date ranges (used in accounting)
        $('.date-range').each(function() {
            $(this).datepicker({
                changeMonth: true,
                changeYear: true,
                dateFormat: 'yy-mm-dd',
            });
        });

        // Optional date ranges, optional month+year (used in accounting)
        $(".report-filter-optional").each(function() {
            $(this).koApplyBindings({
                showFilterName: ko.observable($(this).data("showFilterName")),
            });
        });

        // Selects
        $('.report-filter-single-option').each(function() {
            select2Filter.initMulti(this);
        });
        $('.report-filter-single-option-paginated').each(function() {
            select2Filter.initSinglePaginated(this);
        });
        $('.report-filter-multi-option').each(function() {
            select2Filter.initMulti(this);
        });

        // Submission type (Raw Forms, Errors, & Duplicates)
        $('.report-filter-button-group').each(function() {
            buttonGroup.link(this);
        });

        // Tags (to filter by CC version in global device logs soft asserts report)
        $('.report-filter-tags').each(function() {
            $(this).select2({tags: $(this).data("tags"), allowClear: true});
        });

        // Initialize any help bubbles
        $('.hq-help-template').each(function () {
            hqMain.transformHelpTemplate($(this), true);
        });

        $(".report-filter-message-type-configuration").each(function (i, el) {
            var $el = $(el),
                data = $el.data();
            var model = scheduleInstanceFilter.model(data.initialValue, data.conditionalAlertChoices);
            $el.koApplyBindings(model);

            $('[name=rule_id]').each(function(i, el) {
                $(el).select2({
                    allowClear: true,
                    placeholder: gettext("All"),
                });
            });
        });
        $(".report-filter-phone-number").each(function (i, el) {
            var $el = $(el),
                data = $el.data();
            var model = phoneNumberFilter.model(data.initialValue, data.groups);
            $el.koApplyBindings(model);
        });
        $('[name=selected_group]').each(function(i, el) {
            $(el).select2({
                allowClear: true,
                placeholder: gettext("Select a group"),
            });
        });
    };

    return {
        init: init,
    };
});
<commit_msg>Calling wrong function<commit_after>hqDefine("reports/js/filters/main", [
    'jquery',
    'knockout',
    'hqwebapp/js/main',
    'reports/js/standard_hq_report',
    'reports/js/filters/select2s',
    'reports/js/filters/phone_number',
    'reports/js/filters/button_group',
    'reports/js/filters/schedule_instance',
    'select2-3.5.2-legacy/select2',
], function(
    $,
    ko,
    hqMain,
    standardHQReportModule,
    select2Filter,
    phoneNumberFilter,
    buttonGroup,
    scheduleInstanceFilter
) {
    var init = function() {
        // Datespans
        $('.report-filter-datespan').each(function() {
            var $filterRange = $(this);
            if ($filterRange.data("init")) {
                var separator = $filterRange.data('separator');
                var reportLabels = $filterRange.data('reportLabels');
                var standardHQReport = standardHQReportModule.getStandardHQReport();

                $filterRange.createDateRangePicker(
                    reportLabels, separator,
                    $filterRange.data('startDate'),
                    $filterRange.data('endDate')
                );
                $filterRange.on('change apply', function() {
                    var dates = $(this).val().split(separator);
                    $(standardHQReport.filterAccordion).trigger('hqreport.filter.datespan.startdate', dates[0]);
                    $('#report_filter_datespan_startdate').val(dates[0]);
                    $(standardHQReport.filterAccordion).trigger('hqreport.filter.datespan.enddate', dates[1]);
                    $('#report_filter_datespan_enddate').val(dates[1]);
                });
            }
        });

        // Date selector
        var $dateSelector = $("#filter_date_selector");
        if ($dateSelector.length && $dateSelector.data("init")) {
            $('#filter_date_selector').daterangepicker(
                {
                    locale: {
                        format: 'YYYY-MM-DD',
                    },
                    singleDatePicker: true,
                }
            );
        }

        // Date ranges (used in accounting)
        $('.date-range').each(function() {
            $(this).datepicker({
                changeMonth: true,
                changeYear: true,
                dateFormat: 'yy-mm-dd',
            });
        });

        // Optional date ranges, optional month+year (used in accounting)
        $(".report-filter-optional").each(function() {
            $(this).koApplyBindings({
                showFilterName: ko.observable($(this).data("showFilterName")),
            });
        });

        // Selects
        $('.report-filter-single-option').each(function() {
            select2Filter.initSingle(this);
        });
        $('.report-filter-single-option-paginated').each(function() {
            select2Filter.initSinglePaginated(this);
        });
        $('.report-filter-multi-option').each(function() {
            select2Filter.initMulti(this);
        });

        // Submission type (Raw Forms, Errors, & Duplicates)
        $('.report-filter-button-group').each(function() {
            buttonGroup.link(this);
        });

        // Tags (to filter by CC version in global device logs soft asserts report)
        $('.report-filter-tags').each(function() {
            $(this).select2({tags: $(this).data("tags"), allowClear: true});
        });

        // Initialize any help bubbles
        $('.hq-help-template').each(function () {
            hqMain.transformHelpTemplate($(this), true);
        });

        $(".report-filter-message-type-configuration").each(function (i, el) {
            var $el = $(el),
                data = $el.data();
            var model = scheduleInstanceFilter.model(data.initialValue, data.conditionalAlertChoices);
            $el.koApplyBindings(model);

            $('[name=rule_id]').each(function(i, el) {
                $(el).select2({
                    allowClear: true,
                    placeholder: gettext("All"),
                });
            });
        });
        $(".report-filter-phone-number").each(function (i, el) {
            var $el = $(el),
                data = $el.data();
            var model = phoneNumberFilter.model(data.initialValue, data.groups);
            $el.koApplyBindings(model);
        });
        $('[name=selected_group]').each(function(i, el) {
            $(el).select2({
                allowClear: true,
                placeholder: gettext("Select a group"),
            });
        });
    };

    return {
        init: init,
    };
});
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {
    return (

Welcome to React

          To get started, edit src/App.js and save to reload.

    );
  }
}

export default App;
<commit_msg>initialize watcher, add login<commit_after>import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { Watcher } from "./fetcher.js";

class App extends Component {
  constructor() {
    super()
    this.state = { watcher: new Watcher() }
    this.bindAll()
  }

  login(e) {
    window.location = "/login"
    //e.preventDefault()
    //this.state.watcher.login()
  }

  bindAll() {
    this.login = this.login.bind(this)
  }

  render() {
    return (

Welcome to React

          To get started, edit src/App.js and save to reload.

          <button onClick={this.login}>
            Login
          </button>

    );
  }
}

export default App;
<|endoftext|>


<commit_before>function gitTagFromFullVersion(version) {
  var match = version.match(/-(\w{7})/);

  if (match) {
    // git sha
    return match[1];
  }

  // git tag
  return 'v' + version;
}

module.exports = function(owner, repo, version) {
  return {
    owner: owner,
    repo: repo,
    version: version,
    tag: gitTagFromFullVersion(version)
  };
};<commit_msg>chore(git util): remove unused file<commit_after><|endoftext|>


<commit_before>/**
 * Feeds
 * @namespace pj-feed.feeds.services
 */

(function () {
    'use strict';

    angular
	.module('pjfeedreader.feeds.services')
	.factory('Feeds', ['$http', Feeds]);

    /**
     * @namespace Feeds
     * @returns {Factory}
     */

    function Feeds($http) {
	var Feeds = {
	    add: add,
	    all: all
	};
	return Feeds;

	/**
	 * @name add
	 * @desc Add new feed
	 * @param
	 * @returns {Promise}
	 * @memberOf pjfeedreader.feeds.services.Feeds
	 */

	function add(url, title, category) {
	    return $http.post('/feedreader/api/v1/feeds/', {
		'url': url,
		'title': title,
		'category': category
	    });
	}

	/**
	 * @name all
	 * @desc get existing feeds
	 * @param
	 * @returns {Promise}
	 * @memberOf pjfeedreader.feeds.services.Feeds
	 */
	function all() {
	    return $http.get('/feedreader/api/v1/feeds/');
	}
    }
})();

<commit_msg>refactor(feed): Feed service is handling http failures<commit_after>/**
 * Feeds
 * @namespace pj-feed.feeds.services
 */

(function () {
    'use strict';

    angular
        .module('pjfeedreader.feeds.services')
        .factory('Feeds', ['$http', Feeds]);

    /**
     * @namespace Feeds
     * @returns {Factory}
     */

    function Feeds($http) {
        var Feeds = {
            add: add,
            all: all
        };
        return Feeds;

	/**
	 * @name add
	 * @desc Add new feed
	 * @param
	 * @returns {Promise}
	 * @memberOf pjfeedreader.feeds.services.Feeds
	 */

        function add(url, title, category) {
            return $http.post('/feedreader/api/v1/feeds/', {
                'url': url,
                'title': title,
                'category': category
            }).then(addFeedSuccessFn, addFeedErrorFn);
        }

        /**
         * @name addFeedSuccessFn
         * @desc Show success message
         */

        function addFeedSuccessFn(data, status, headers, config) {
            console.log('Adding feed succesfully');
        }

        /**
         * @name addCategoryErrorFn
         * @desc Show success message
         */

        function addFeedErrorFn(data, status, headers, config) {
            console.log('Error in adding');
            console.log(data);
            console.log(data.error);
        }

	/**
	 * @name all
	 * @desc get existing feeds
	 * @param
	 * @returns {Promise}
	 * @memberOf pjfeedreader.feeds.services.Feeds
	 */
        function all() {
            return $http.get('/feedreader/api/v1/feeds/');
        }
    }
})();

<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

foam.CLASS({
  package: 'foam.comics',
  name: 'DAOControllerView',
  extends: 'foam.u2.View',

  requires: [
    'foam.comics.DAOController',
    'foam.u2.view.ScrollTableView'
  ],

  imports: [
    'stack',
    'summaryView? as importedSummaryView',
    'data? as importedData'
  ],

  exports: [
    'data.selection as selection',
    'data.data as dao'
  ],

  properties: [
    {
      class: 'FObjectProperty',
      of: 'foam.comics.DAOController',
      name: 'data',
      expression: function(importedData) { return importedData; },
    },
    {
      name: 'cls',
      expression: function(data) { return data.cls_; }
    },
    {
      name: 'summaryView',
      factory: function() {
        return this.importedSummaryView$ ? this.importedSummaryView : { class: 'foam.u2.view.ScrollTableView' };
      }
    },
    {
      class: 'String',
      name: 'title',
      expression: function(data$data$of) {
        return 'Browse ' + data$data$of.name;
      }
    }
  ],

  reactions: [
    [ 'data', 'action.create', 'onCreate' ],
    [ 'data', 'edit', 'onEdit' ],
    [ 'data', 'action.findRelatedObject', 'onFindRelated' ],
    [ 'data', 'finished', 'onFinished']
  ],

  methods: [
    function initE() {
      this.
        start('table').
          start('tr').
            start('td').style({display: 'block', padding: '8px'}).add(this.cls.PREDICATE).end().
            start('td').style({'vertical-align': 'top', 'width': '100%'}).
              start('span').
                style({background: 'rgba(0,0,0,0)'}).
                show(this.mode$.map(function(m) { return m == foam.u2.DisplayMode.RW; })).
                start().
                  style({padding: '4px'}).
                  add(this.cls.getAxiomsByClass(foam.core.Action)).
                end().
              end().
              tag(this.summaryView, {data$: this.data.filteredDAO$}).
            end().
          end().
        end();
    }
  ],

  listeners: [
    function onCreate() {
      this.stack.push({
        class: 'foam.comics.DAOCreateControllerView'
      }, this);
    },

    function onEdit(s, edit, id) {
      this.stack.push({
        class: 'foam.comics.DAOUpdateControllerView',
        key: id
      }, this);
    },

    function onFindRelated() {
      var data = this.DAOController.create({
        data: this.data.relationship.targetDAO,
        addEnabled: true,
        relationship: this.data.relationship
      });

      this.stack.push({
        class: 'foam.comics.DAOControllerView',
        data: data
      }, this);
    },

    function onFinished() {
      this.stack.back();
    }
  ]
});
<commit_msg>Improve DAOController action button CSS.<commit_after>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

foam.CLASS({
  package: 'foam.comics',
  name: 'DAOControllerView',
  extends: 'foam.u2.View',

  requires: [
    'foam.comics.DAOController',
    'foam.u2.view.ScrollTableView'
  ],

  imports: [
    'stack',
    'summaryView? as importedSummaryView',
    'data? as importedData'
  ],

  exports: [
    'data.selection as selection',
    'data.data as dao'
  ],

  css: `
    .net-nanopay-ui-ActionView {
      background: #59aadd;
      color: white;
      margin-right: 4px;
    }
  `,

  properties: [
    {
      class: 'FObjectProperty',
      of: 'foam.comics.DAOController',
      name: 'data',
      expression: function(importedData) { return importedData; },
    },
    {
      name: 'cls',
      expression: function(data) { return data.cls_; }
    },
    {
      name: 'summaryView',
      factory: function() {
        return this.importedSummaryView$ ? this.importedSummaryView : { class: 'foam.u2.view.ScrollTableView' };
      }
    },
    {
      class: 'String',
      name: 'title',
      expression: function(data$data$of) {
        return 'Browse ' + data$data$of.name;
      }
    }
  ],

  reactions: [
    [ 'data', 'action.create', 'onCreate' ],
    [ 'data', 'edit', 'onEdit' ],
    [ 'data', 'action.findRelatedObject', 'onFindRelated' ],
    [ 'data', 'finished', 'onFinished']
  ],

  methods: [
    function initE() {
      this.
        start('table').
          start('tr').
            start('td').style({display: 'block', padding: '8px'}).add(this.cls.PREDICATE).end().
            start('td').style({'vertical-align': 'top', 'width': '100%'}).
              start('span').
                style({background: 'rgba(0,0,0,0)'}).
                show(this.mode$.map(function(m) { return m == foam.u2.DisplayMode.RW; })).
                start().
                  style({padding: '4px'}).
                  add(this.cls.getAxiomsByClass(foam.core.Action)).
                end().
              end().
              tag(this.summaryView, {data$: this.data.filteredDAO$}).
            end().
          end().
        end();
    }
  ],

  listeners: [
    function onCreate() {
      this.stack.push({
        class: 'foam.comics.DAOCreateControllerView'
      }, this);
    },

    function onEdit(s, edit, id) {
      this.stack.push({
        class: 'foam.comics.DAOUpdateControllerView',
        key: id
      }, this);
    },

    function onFindRelated() {
      var data = this.DAOController.create({
        data: this.data.relationship.targetDAO,
        addEnabled: true,
        relationship: this.data.relationship
      });

      this.stack.push({
        class: 'foam.comics.DAOControllerView',
        data: data
      }, this);
    },

    function onFinished() {
      this.stack.back();
    }
  ]
});
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2020 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.auth',
  name: 'PMAuthService',
  extends: 'foam.nanos.auth.ProxyAuthService',

  implements: [
    'foam.nanos.auth.EnabledAware'
  ],

  requires: [
    'foam.nanos.pm.PM'
  ],

  javaImports: [
    'foam.core.X',
    'foam.mlang.order.Comparator',
    'foam.mlang.predicate.Predicate',
    'foam.nanos.pm.PM'
  ],

  properties: [
    {
      name: 'enabled',
      class: 'Boolean',
      value: true
    },
    {
      name: 'classType',
      class: 'Class',
      javaFactory: `
        return PMAuthService.getOwnClassInfo();
      `,
      hidden: true
    }
  ],

  methods: [
    // Methods specific to PM
    {
      name: 'createPM',
      args: [
        {
          name: 'x',
          type: 'X'
        },
        {
          name: 'op',
          type: 'String'
        }
      ],
      javaType: 'PM',
      javaCode: `
    PM pm = null;
    if ( getEnabled() ) {
      pm = (PM) x.get("PM");
      pm.setClassType(this.getClassType());
      pm.setName(op);
      pm.init_();
    }
    return pm;
      `
    },
    {
      name: 'log',
      args: [
        {
          name: 'x',
          type: 'X',
        },
        {
          name: 'pm',
          type: 'PM'
        }
      ],
      javaCode: `
    if ( pm != null ) {
      pm.log(x);
    }
      `
    },
    {
      name: 'getNameFor',
      args: [
        {
          name: 'name',
          type: 'String'
        }
      ],
      type: 'String',
      javaCode: `
        return "auth:" + name;
      `
    },

    // Proxy methods, to be monitored
    {
      name: 'login',
      javaCode: `
      PM pm = createPM(x, getNameFor("login"));
      try {
        return super.login(x, userId, password);
      } finally {
        log(x, pm);
      }
     `
    },
    {
      name: 'loginByEmail',
      javaCode: `
      PM pm = createPM(x, getNameFor("loginByEmail"));
      try {
        return super.loginByEmail(x, email, password);
      } finally {
        log(x, pm);
      }
     `
    },
    {
      name: 'validatePassword',
      javaCode: `
      PM pm = createPM(x, getNameFor("validatePassword"));
      try {
        super.validatePassword(x, user, potentialPassword);
      } finally {
        log(x, pm);
      }
     `
    },
    {
      name: 'checkUser',
      javaCode: `
      PM pm = createPM(x, getNameFor("checkUser"));
      try {
        return super.checkUser(x, user, permission);
      } finally {
        log(x, pm);
      }
     `
    },
    {
      name: 'check',
      javaCode: `
      PM pm = createPM(x, getNameFor("check"));
      try {
        return super.check(x, permission);
      } finally {
        log(x, pm);
      }
     `
    },
    {
      name: 'updatePassword',
      javaCode: `
      PM pm = createPM(x, getNameFor("updatePassword"));
      try {
        return super.updatePassword(x, oldPassword, newPassword);
      } finally {
        log(x, pm);
      }
     `
    },
    {
      name: 'validateUser',
      javaCode: `
      PM pm = createPM(x, getNameFor("validateUser"));
      try {
        super.validateUser(x, user);
      } finally {
        log(x, pm);
      }
     `
    },
    {
      name: 'logout',
      javaCode: `
      PM pm = createPM(x, getNameFor("logout"));
      try {
        super.logout(x);
      } finally {
        log(x, pm);
      }
     `
    },
  ]
});<commit_msg>Add label property<commit_after>/**
 * @license
 * Copyright 2020 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.auth',
  name: 'PMAuthService',
  extends: 'foam.nanos.auth.ProxyAuthService',

  implements: [
    'foam.nanos.auth.EnabledAware'
  ],

  requires: [
    'foam.nanos.pm.PM'
  ],

  javaImports: [
    'foam.core.X',
    'foam.mlang.order.Comparator',
    'foam.mlang.predicate.Predicate',
    'foam.nanos.pm.PM'
  ],

  properties: [
    {
      name: 'enabled',
      class: 'Boolean',
      value: true
    },
    {
      name: 'classType',
      class: 'Class',
      javaFactory: `
        return PMAuthService.getOwnClassInfo();
      `,
      hidden: true
    },
    {
      name: 'label',
      class: 'String'
    }
  ],

  methods: [
    // Methods specific to PM
    {
      name: 'createPM',
      args: [
        {
          name: 'x',
          type: 'X'
        },
        {
          name: 'op',
          type: 'String'
        }
      ],
      javaType: 'PM',
      javaCode: `
    PM pm = null;
    if ( getEnabled() ) {
      pm = (PM) x.get("PM");
      pm.setClassType(this.getClassType());
      pm.setName(op);
      pm.init_();
    }
    return pm;
      `
    },
    {
      name: 'log',
      args: [
        {
          name: 'x',
          type: 'X',
        },
        {
          name: 'pm',
          type: 'PM'
        }
      ],
      javaCode: `
    if ( pm != null ) {
      pm.log(x);
    }
      `
    },
    {
      name: 'getNameFor',
      args: [
        {
          name: 'name',
          type: 'String'
        }
      ],
      type: 'String',
      javaCode: `
        String label = getLabel();
        return "auth" +
          ("".equals(label) ? "" : "/" + label) +
          ":" + name;
      `
    },

    // Proxy methods, to be monitored
    {
      name: 'login',
      javaCode: `
      PM pm = createPM(x, getNameFor("login"));
      try {
        return super.login(x, userId, password);
      } finally {
        log(x, pm);
      }
     `
    },
    {
      name: 'loginByEmail',
      javaCode: `
      PM pm = createPM(x, getNameFor("loginByEmail"));
      try {
        return super.loginByEmail(x, email, password);
      } finally {
        log(x, pm);
      }
     `
    },
    {
      name: 'validatePassword',
      javaCode: `
      PM pm = createPM(x, getNameFor("validatePassword"));
      try {
        super.validatePassword(x, user, potentialPassword);
      } finally {
        log(x, pm);
      }
     `
    },
    {
      name: 'checkUser',
      javaCode: `
      PM pm = createPM(x, getNameFor("checkUser"));
      try {
        return super.checkUser(x, user, permission);
      } finally {
        log(x, pm);
      }
     `
    },
    {
      name: 'check',
      javaCode: `
      PM pm = createPM(x, getNameFor("check"));
      try {
        return super.check(x, permission);
      } finally {
        log(x, pm);
      }
     `
    },
    {
      name: 'updatePassword',
      javaCode: `
      PM pm = createPM(x, getNameFor("updatePassword"));
      try {
        return super.updatePassword(x, oldPassword, newPassword);
      } finally {
        log(x, pm);
      }
     `
    },
    {
      name: 'validateUser',
      javaCode: `
      PM pm = createPM(x, getNameFor("validateUser"));
      try {
        super.validateUser(x, user);
      } finally {
        log(x, pm);
      }
     `
    },
    {
      name: 'logout',
      javaCode: `
      PM pm = createPM(x, getNameFor("logout"));
      try {
        super.logout(x);
      } finally {
        log(x, pm);
      }
     `
    },
  ]
});<|endoftext|>


<commit_before>(function () {
  module.exports = function validator(n) {
    function makeModBy(m, modError) {
      if(n % m === 0) result.push(modError);
    }

    function validateModBy5(n, result) {

      makeModBy(5, 'error.five');
    }

    function validateModBy3(n, result) {
      function makeModBy3(m, modError) {
        if(n % m === 0) result.push(modError);
      }

      makeModBy3(3, 'error.three');
    }

    function validatePositive(n, result) { if(n <= 0) result.push('error.nonpositive'); }

    var result = [];

    validatePositive(n, result);
    validateModBy3(n, result);
    validateModBy5(n, result);

    return result;
  };
})();
<commit_msg>substitute<commit_after>(function () {
  module.exports = function validator(n) {
    function makeModBy(m, modError) {
      if(n % m === 0) result.push(modError);
    }

    function validateModBy5(n, result) {

      makeModBy(5, 'error.five');
    }

    function validateModBy3(n, result) {
      function makeModBy3(m, modError) {
        if(n % m === 0) result.push(modError);
      }

      makeModBy(3, 'error.three');
    }

    function validatePositive(n, result) { if(n <= 0) result.push('error.nonpositive'); }

    var result = [];

    validatePositive(n, result);
    validateModBy3(n, result);
    validateModBy5(n, result);

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


<commit_before>
/**
 * VBR constructor
 * @param {Buffer} buffer
 */
function VBR( buffer ) {

  if( !(this instanceof VBR) )
    return new VBR( buffer )

  // No JMP to bootloader code -> no VBR
  if( buffer[0] !== 0xEB && buffer[0] !== 0xE9 )
    return new Error( 'No VBR detected' );

  // 0x20 padded OEM/System name
  this.systemName = buffer.slice( 0x03, 0x03 + 0x08 )
    .toString( 'ascii' ).trim()

  this.type = buffer.slice( 0x15, 0x16 )

  this.bytesPerSector    = buffer.readUInt16LE( 0x0B )
  this.sectorsPerCluster = buffer.readUInt8( 0x0D )
  this.clusterSize       = this.bytesPerSector * this.sectorsPerCluster
  this.numberOfFATs      = buffer.readUInt8( 0x10 )
  this.maxEntries        = buffer.readUInt8( 0x11 )
  this.sectorsPerFAT     = buffer.readUInt16LE( 0x16 )
  this.sectorsPerTrack   = buffer.readUInt16LE( 0x18 )
  this.headsPerTrack     = buffer.readUInt16LE( 0x1A )
  this.hiddenSectors     = buffer.readUInt16LE( 0x1C )
  this.reservedSectors   = buffer.readUInt16LE( 0x0E )

  this.sectors = buffer.readUInt16LE( 0x13 ) ||
    buffer.readUInt16LE( 0x20 )

}

// Exports
module.exports = VBR

/**
 * VBR prototype
 * @type {Object}
 */
VBR.prototype = {

  constructor: VBR

}
<commit_msg>Updated lib/vbr: Added trim of \u0000, not only \s<commit_after>
/**
 * VBR constructor
 * @param {Buffer} buffer
 */
function VBR( buffer ) {

  if( !(this instanceof VBR) )
    return new VBR( buffer )

  // No JMP to bootloader code -> no VBR
  if( buffer[0] !== 0xEB && buffer[0] !== 0xE9 )
    return new Error( 'No VBR detected' );

  // 0x20 padded OEM/System name
  this.systemName = buffer.slice( 0x03, 0x03 + 0x08 )
    .toString( 'ascii' )
    .replace( /\s|\u0000/g, '' )

  this.type = buffer.slice( 0x15, 0x16 )

  this.bytesPerSector    = buffer.readUInt16LE( 0x0B )
  this.sectorsPerCluster = buffer.readUInt8( 0x0D )
  this.clusterSize       = this.bytesPerSector * this.sectorsPerCluster
  this.numberOfFATs      = buffer.readUInt8( 0x10 )
  this.maxEntries        = buffer.readUInt8( 0x11 )
  this.sectorsPerFAT     = buffer.readUInt16LE( 0x16 )
  this.sectorsPerTrack   = buffer.readUInt16LE( 0x18 )
  this.headsPerTrack     = buffer.readUInt16LE( 0x1A )
  this.hiddenSectors     = buffer.readUInt16LE( 0x1C )
  this.reservedSectors   = buffer.readUInt16LE( 0x0E )

  this.sectors = buffer.readUInt16LE( 0x13 ) ||
    buffer.readUInt16LE( 0x20 )

}

// Exports
module.exports = VBR

/**
 * VBR prototype
 * @type {Object}
 */
VBR.prototype = {

  constructor: VBR

}
<|endoftext|>


<commit_before>"use strict";

const _ = require('underscore');
const util = require('util');
const EventEmitter = require('events');

const NoopLogger = require(__dirname + '/noop-logger');
const EventConsts = require(__dirname + '/event-consts');
const ViberClient = require(__dirname + '/viber-client');
const Middleware = require(__dirname + '/middleware');
const RegexMatcherRouter = require(__dirname + '/regex-matcher-router');

const MessageFactory = require(__dirname + '/message/message-factory');
const MessageValidator = require(__dirname + '/message/message-validator');
const Message = require(__dirname + '/message/message');
const TextMessage = require(__dirname + '/message/text-message');

const UserProfile = require(__dirname + '/user-profile');
const Response = require(__dirname + '/response');

const REQUIRED_CONFIGURATION_FIELDS = ["authToken", "name", "avatar"];
const SUBSCRIBED_EVENTS = ["subscribed", "unsubscribed", "conversation_started", "message", "delivered", "seen"];
const API_URL = "https://chatapi.viber.com/pa";

function ViberBot(loggerOrConfiguration, configuration) {

	// backward compatibility: we are still allowing ctor as (logger, configuration);
	// newer should use (configuration) with logger property in it.
	let logger;
	if (!configuration) {
		// no logger, treat loggerOrConfiguration as configuration
		configuration = loggerOrConfiguration;
		logger = configuration.logger || NoopLogger;
	} else {
		logger = loggerOrConfiguration || NoopLogger;
	}

	if (!configuration) {
		throw new Error(`Invalid configuration`);
	}

	const missingFields = this._getMissingFieldsInConfiguration(configuration);
	if (!_.isEmpty(missingFields)) {
		throw new Error(`Invalid configuration ${configuration}. Missing fields: ${missingFields}`);
	}

	this.authToken = configuration.authToken;
	this.name = configuration.name;
	this.avatar = configuration.avatar;

	this._logger = logger;
	this._client = new ViberClient(this._logger, this, API_URL, configuration.registerToEvents || SUBSCRIBED_EVENTS);
	this._middleware = new Middleware(this._logger, new MessageValidator(this._logger, this.authToken));
	this._messageFactory = new MessageFactory(this._logger);
	this._regexMatcherRouter = new RegexMatcherRouter(this._logger);
	this._callbacks = { [EventConsts.CONVERSATION_STARTED]: [] };

	this._registerStreamAndHandleEvents(this._middleware.getStream());
	this._setupTextMessageReceivedHandler();
	this._setupConversationStartedHandler();
}
util.inherits(ViberBot, EventEmitter);

ViberBot.prototype.getBotProfile = function() {
	return this._client.getAccountInfo();
};

ViberBot.prototype.getUserDetails = function(userProfile) {
	return this._client.getUserDetails(userProfile.id).then(response => Promise.resolve(response.user));
};

ViberBot.prototype.getOnlineStatus = function(viberUserIds) {
	return this._client.getOnlineStatus(viberUserIds);
};

ViberBot.prototype.setWebhook = function(url) {
	return this._client.setWebhook(url);
};

ViberBot.prototype.sendMessage = function(userProfile, messages, optionalTrackingData) {
	if (messages == null) return Promise.resolve();
	messages = _.isArray(messages) ? messages : [messages];

	const self = this;
	const lastMessage = messages.pop();
	const tokens = [];

	const resolveCallback = (response, message, resolve, reject) => {
		if (response.status != 0) reject(response);
		tokens.push(response.message_token);
		self.emit(EventConsts.MESSAGE_SENT, message, userProfile);
		resolve();
	};

	let promise = Promise.resolve();
	_.each(messages, message => {
		promise = promise.then(() => new Promise((resolve, reject) =>
			self._sendMessageFromClient(userProfile, message).then(response => resolveCallback(response, message, resolve, reject))));
	});

	return promise.then(() => new Promise((resolve, reject) =>
		self._sendMessageFromClient(userProfile, lastMessage, optionalTrackingData, lastMessage.keyboard)
			.then(response => resolveCallback(response, lastMessage, resolve, reject))))
		.then(() => Promise.resolve(tokens));
};

ViberBot.prototype.middleware = function() {
	return this._middleware.getIncoming();
};

ViberBot.prototype.onTextMessage = function(regex, callback) {
	this._regexMatcherRouter.newMatcher(regex, callback);
};

ViberBot.prototype.onError = function(callback) {
	this.on(EventConsts.ERROR, callback);
};

ViberBot.prototype.onConversationStarted = function(callback) {
	this._callbacks[EventConsts.CONVERSATION_STARTED].push(callback);
};

ViberBot.prototype.onSubscribe = function(callback) {
	this.on(EventConsts.SUBSCRIBED, callback);
};

ViberBot.prototype.onUnsubscribe = function(callback) {
	this.on(EventConsts.UNSUBSCRIBED, callback);
};

ViberBot.prototype._setupTextMessageReceivedHandler = function() {
	const self = this;
	this.on(EventConsts.MESSAGE_RECEIVED, (message, response) => {
		if (!(message instanceof TextMessage)) return;

		const callback = this._regexMatcherRouter.tryGetCallback(message.text);
		if (!callback) {
			return self._logger.debug(`Could not find regex matcher for ${message.text}`);
		}
		callback(message, response);
	});
};

ViberBot.prototype._setupConversationStartedHandler = function() {
	const self = this;
	this.on(EventConsts.CONVERSATION_STARTED, (response, context) => {
		_.each(self._callbacks[EventConsts.CONVERSATION_STARTED], callback => {
			if (!response) throw new Error("Response from conversation started callback must be message or null");
			if (!context) throw new Error("Response from conversation started callback must be message or null");
			callback(response.userProfile, context);
		});
	});
};

ViberBot.prototype._getMissingFieldsInConfiguration = function(configuration) {
	return _.difference(REQUIRED_CONFIGURATION_FIELDS, Object.keys(configuration));
};

ViberBot.prototype._sendMessageFromClient = function(userProfile, message, optionalTrackingData, optionalKeyboard) {
	const jsonMessage = message.toJson();
	return this._client.sendMessage(userProfile.id, jsonMessage.type, jsonMessage, optionalTrackingData, optionalKeyboard);
};

ViberBot.prototype._registerStreamAndHandleEvents = function(stream) {
	const self = this;
	stream.on("data", data => {
		try {
			const parsedData = JSON.parse(data.toString());
			self._handleEventReceived(parsedData);
		}
		catch (err) {
			self._logger.error(err);
			self.emit(EventConsts.ERROR, err);
		}
	});
};

ViberBot.prototype._handleEventReceived = function(data) {
	const userProfile = this._getUserProfile(data);
	switch (data.event) {
		case EventConsts.MESSAGE_RECEIVED: {
			const message = this._messageFactory.createMessageFromJson(data);
			const response = new Response(this, userProfile);
			this.emit(data.event, message, response);
			break;
		}
		case EventConsts.SUBSCRIBED:
		case EventConsts.CONVERSATION_STARTED: {
			const response = new Response(this, userProfile);
			this.emit(data.event, response, data.context);
			break;
		}
		case EventConsts.UNSUBSCRIBED: {
			this.emit(data.event, data.user_id);
			break;
		}
		case EventConsts.FAILED: {
			this.emit(EventConsts.ERROR, data);
			break;
		}
		default: {
			this.emit(data.event, data);
			break;
		}
	}
};

ViberBot.prototype._getUserProfile = function(data) {
	if (_.has(data, "sender")) return UserProfile.fromJson(data.sender);
	else if (_.has(data, "user")) return UserProfile.fromJson(data.user);
	return null;
};

module.exports = ViberBot;

<commit_msg>Update viber-bot.js<commit_after>"use strict";

const _ = require('underscore');
const util = require('util');
const EventEmitter = require('events');

const NoopLogger = require(__dirname + '/noop-logger');
const EventConsts = require(__dirname + '/event-consts');
const ViberClient = require(__dirname + '/viber-client');
const Middleware = require(__dirname + '/middleware');
const RegexMatcherRouter = require(__dirname + '/regex-matcher-router');

const MessageFactory = require(__dirname + '/message/message-factory');
const MessageValidator = require(__dirname + '/message/message-validator');
const Message = require(__dirname + '/message/message');
const TextMessage = require(__dirname + '/message/text-message');

const UserProfile = require(__dirname + '/user-profile');
const Response = require(__dirname + '/response');

const REQUIRED_CONFIGURATION_FIELDS = ["authToken", "name", "avatar"];
const SUBSCRIBED_EVENTS = ["subscribed", "unsubscribed", "conversation_started", "message", "delivered", "seen"];
const API_URL = "https://chatapi.viber.com/pa";

function ViberBot(loggerOrConfiguration, configuration) {

	// backward compatibility: we are still allowing ctor as (logger, configuration);
	// newer should use (configuration) with logger property in it.
	let logger;
	if (!configuration) {
		// no logger, treat loggerOrConfiguration as configuration
		configuration = loggerOrConfiguration;
		logger = configuration.logger || NoopLogger;
	} else {
		logger = loggerOrConfiguration || NoopLogger;
	}

	if (!configuration) {
		throw new Error(`Invalid configuration`);
	}

	const missingFields = this._getMissingFieldsInConfiguration(configuration);
	if (!_.isEmpty(missingFields)) {
		throw new Error(`Invalid configuration ${configuration}. Missing fields: ${missingFields}`);
	}

	this.authToken = configuration.authToken;
	this.name = configuration.name;
	this.avatar = configuration.avatar;

	this._logger = logger;
	this._client = new ViberClient(this._logger, this, API_URL, configuration.registerToEvents || SUBSCRIBED_EVENTS);
	this._middleware = new Middleware(this._logger, new MessageValidator(this._logger, this.authToken));
	this._messageFactory = new MessageFactory(this._logger);
	this._regexMatcherRouter = new RegexMatcherRouter(this._logger);
	this._callbacks = { [EventConsts.CONVERSATION_STARTED]: [] };

	this._registerStreamAndHandleEvents(this._middleware.getStream());
	this._setupTextMessageReceivedHandler();
	this._setupConversationStartedHandler();
}
util.inherits(ViberBot, EventEmitter);

ViberBot.prototype.getBotProfile = function() {
	return this._client.getAccountInfo();
};

ViberBot.prototype.getUserDetails = function(userProfile) {
	return this._client.getUserDetails(userProfile.id).then(response => Promise.resolve(response.user));
};

ViberBot.prototype.getOnlineStatus = function(viberUserIds) {
	return this._client.getOnlineStatus(viberUserIds);
};

ViberBot.prototype.setWebhook = function(url) {
	return this._client.setWebhook(url);
};

ViberBot.prototype.sendMessage = function(userProfile, messages, optionalTrackingData) {
	if (messages == null) return Promise.resolve();
	messages = _.isArray(messages) ? messages : [messages];

	const self = this;
	const lastMessage = messages.pop();
	const tokens = [];

	const resolveCallback = (response, message, resolve, reject) => {
		if (response.status != 0) reject(response);
		tokens.push(response.message_token);
		self.emit(EventConsts.MESSAGE_SENT, message, userProfile);
		resolve();
	};

	let promise = Promise.resolve();
	_.each(messages, message => {
		promise = promise.then(() => new Promise((resolve, reject) =>
			self._sendMessageFromClient(userProfile, message).then(response => resolveCallback(response, message, resolve, reject))));
	});

	return promise.then(() => new Promise((resolve, reject) =>
		self._sendMessageFromClient(userProfile, lastMessage, optionalTrackingData, lastMessage.keyboard)
			.then(response => resolveCallback(response, lastMessage, resolve, reject))))
		.then(() => Promise.resolve(tokens));
};

ViberBot.prototype.middleware = function() {
	return this._middleware.getIncoming();
};

ViberBot.prototype.onTextMessage = function(regex, callback) {
	this._regexMatcherRouter.newMatcher(regex, callback);
};

ViberBot.prototype.onError = function(callback) {
	this.on(EventConsts.ERROR, callback);
};

ViberBot.prototype.onConversationStarted = function(callback) {
	this._callbacks[EventConsts.CONVERSATION_STARTED].push(callback);
};

ViberBot.prototype.onSubscribe = function(callback) {
	this.on(EventConsts.SUBSCRIBED, callback);
};

ViberBot.prototype.onUnsubscribe = function(callback) {
	this.on(EventConsts.UNSUBSCRIBED, callback);
};

ViberBot.prototype._setupTextMessageReceivedHandler = function() {
	const self = this;
	this.on(EventConsts.MESSAGE_RECEIVED, (message, response) => {
		if (!(message instanceof TextMessage)) return;

		const callback = this._regexMatcherRouter.tryGetCallback(message.text);
		if (!callback) {
			return self._logger.debug(`Could not find regex matcher for ${message.text}`);
		}
		callback(message, response);
	});
};

ViberBot.prototype._setupConversationStartedHandler = function() {
	const self = this;
	this.on(EventConsts.CONVERSATION_STARTED, (response, context) => {
		_.each(self._callbacks[EventConsts.CONVERSATION_STARTED], callback => {
			if (!response) throw new Error("Response from conversation started callback must be message or null");
			if (!context) throw new Error("Response from conversation started callback must be message or null");
			return(response.userProfile, context);
		});
	});
};

ViberBot.prototype._getMissingFieldsInConfiguration = function(configuration) {
	return _.difference(REQUIRED_CONFIGURATION_FIELDS, Object.keys(configuration));
};

ViberBot.prototype._sendMessageFromClient = function(userProfile, message, optionalTrackingData, optionalKeyboard) {
	const jsonMessage = message.toJson();
	return this._client.sendMessage(userProfile.id, jsonMessage.type, jsonMessage, optionalTrackingData, optionalKeyboard);
};

ViberBot.prototype._registerStreamAndHandleEvents = function(stream) {
	const self = this;
	stream.on("data", data => {
		try {
			const parsedData = JSON.parse(data.toString());
			self._handleEventReceived(parsedData);
		}
		catch (err) {
			self._logger.error(err);
			self.emit(EventConsts.ERROR, err);
		}
	});
};

ViberBot.prototype._handleEventReceived = function(data) {
	const userProfile = this._getUserProfile(data);
	switch (data.event) {
		case EventConsts.MESSAGE_RECEIVED: {
			const message = this._messageFactory.createMessageFromJson(data);
			const response = new Response(this, userProfile);
			this.emit(data.event, message, response);
			break;
		}
		case EventConsts.SUBSCRIBED:
		case EventConsts.CONVERSATION_STARTED: {
			const response = new Response(this, userProfile);
			this.emit(data.event, response, data.context);
			break;
		}
		case EventConsts.UNSUBSCRIBED: {
			this.emit(data.event, data.user_id);
			break;
		}
		case EventConsts.FAILED: {
			this.emit(EventConsts.ERROR, data);
			break;
		}
		default: {
			this.emit(data.event, data);
			break;
		}
	}
};

ViberBot.prototype._getUserProfile = function(data) {
	if (_.has(data, "sender")) return UserProfile.fromJson(data.sender);
	else if (_.has(data, "user")) return UserProfile.fromJson(data.user);
	return null;
};

module.exports = ViberBot;

<|endoftext|>


<commit_before>/**
 * Developer: Stepan Burguchev
 * Date: 7/3/2015
 * Copyright: 2009-2015 Comindware®
 *       All Rights Reserved
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF Comindware
 *       The copyright notice above does not evidence any
 *       actual or intended publication of such source code.
 */

/* global define, require, Handlebars, Backbone, Marionette, $, _, Localizer */

define([
        'module/lib',
        'core/utils/utilsApi',
        'module/moduleConfigs',
        'project/module/moduleConfigs',
        'process/module/moduleConfigs'
    ],
    function (lib, utilsApi, moduleConfigs, projectModuleConfigs, processModuleConfigs) {
        'use strict';

        var configs = _.flatten([ moduleConfigs, projectModuleConfigs, processModuleConfigs ]);

        var modules = {
            SETTINGS_WORKSPACE: 'module:settings:workspace',
            SETTINGS_GROUPS: 'module:settings:groups',
            MYTASKS: 'module:myTasks',
            PEOPLE_USERS: 'module:people:users',
            DEMO_CORE: 'module:demo:core',

            PROJECT_ROOMS_SHOWALL: 'module:project:rooms:showAll',
            PROJECT_ROOMS_OVERVIEW: 'module:project:rooms:overview',

            PROCESS_PROCESSTEMPLATES_DESIGNER: 'module:process:processTemplates:designer',
            PROCESS_PROCESSTEMPLATES_ATTRIBUTES: 'module:process:processTemplates:attributes',
            PROCESS_PROCESSTEMPLATES_STATISTICS: 'module:process:processTemplates:statistics',
            PROCESS_PROCESSTEMPLATES_SETTINGS: 'module:process:processTemplates:settings',
            PROCESS_PROCESSTEMPLATES_SHOWALL: 'module:process:processTemplates:showAll',

            PROCESS_PROCESSTEMPLATES_DESIGNER_ACTIVITY_CONTEXT: 'module:process:processTemplates:designer:activity:context',
            PROCESS_PROCESSTEMPLATES_DESIGNER_ACTIVITY_FORMDESIGNER: 'module:process:processTemplates:designer:activity:formDesigner',
            PROCESS_PROCESSTEMPLATES_DESIGNER_ACTIVITY_SETTINGS: 'module:process:processTemplates:designer:activity:settings',
            PROCESS_PROCESSTEMPLATES_DESIGNER_ACTIVITY_RULES: 'module:process:processTemplates:designer:activity:rules',

            PROCESS_ARCHITECTURE_OVERVIEW: 'module:process:architecture:overview',
            PROCESS_ARCHITECTURE_DESIGNER: 'module:process:architecture:designer',
            PROCESS_ARCHITECTURE_DESIGNER_ACTIVITY_SETTINGS: 'module:process:architecture:designer:activity:settings',
            PROCESS_ARCHITECTURE_SHOWALL: 'module:process:architecture:showAll',

            PROCESS_RECORDTYPES_ATTRIBUTES: 'module:process:recordTypes:attributes',
            PROCESS_RECORDTYPES_DIAGRAM: 'module:process:recordTypes:diagram',
            PROCESS_RECORDTYPES_FORMDESIGNER: 'module:process:recordTypes:formDesigner',
            PROCESS_RECORDTYPES_SETTINGS: 'module:process:recordTypes:settings',
            PROCESS_RECORDTYPES_RECORDS: 'module:process:recordTypes:records',
            PROCESS_RECORDTYPES_SHOWALL: 'module:process:recordTypes:showAll',

            PROCESS_PROCESSMONITOR: 'module:process:processMonitor',
            PROCESS_DATADIAGRAM: 'module:process:dataDiagram',

            SUPPORT_GLOBAL_FUNCTIONS: 'module:support:globalFunctions'
        };

        return {
            getDefaultModuleUrl: function (moduleId, options) {
                return this.getModuleUrlByName('default', moduleId, options);
            },

            getModuleUrlByName: function (urlName, moduleId, options) {
                options = options || {};
                var moduleConfig = _.findWhere(configs, { id : moduleId });
                if (!moduleConfig) {
                    utilsApi.helpers.throwError('Failed to find a module with id `' + moduleId + '`.');
                }
                if (!moduleConfig.navigationUrl) {
                    utilsApi.helpers.throwError('The module `' + moduleId + '` is incomplete and doesn`t have navigationUrl.');
                }
                var url = moduleConfig.navigationUrl[urlName];
                if (!url) {
                    utilsApi.helpers.throwError('Failed to find navigation url `' + urlName + '` in the module `' + moduleId + '`');
                }

                var result = [];
                var lastIndex = 0;
                var match;
                var re = /:[^/]+(?=\/|$)/g;
                while (true) {
                    match = re.exec(url);
                    if (!match) {
                        break;
                    }
                    result.push(url.substring(lastIndex, match.index));
                    var param = match[0].substring(1);
                    var opt = options[param];
                    if (!opt) {
                        utilsApi.helpers.throwFormatError('Missing url options `' + param + '`.');
                    }
                    result.push(opt);
                    lastIndex = match.index + param.length + 1;
                }
                result.push(url.substring(lastIndex));
                var resultUrl = result.join('');
                if (resultUrl[0] !== '#') {
                    resultUrl = '#' + resultUrl;
                }
                return resultUrl;
            },

            modules: modules
        };
    });
<commit_msg>Added UI for active directory<commit_after>/**
 * Developer: Stepan Burguchev
 * Date: 7/3/2015
 * Copyright: 2009-2015 Comindware®
 *       All Rights Reserved
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF Comindware
 *       The copyright notice above does not evidence any
 *       actual or intended publication of such source code.
 */

/* global define, require, Handlebars, Backbone, Marionette, $, _, Localizer */

define([
        'module/lib',
        'core/utils/utilsApi',
        'module/moduleConfigs',
        'project/module/moduleConfigs',
        'process/module/moduleConfigs'
    ],
    function (lib, utilsApi, moduleConfigs, projectModuleConfigs, processModuleConfigs) {
        'use strict';

        var configs = _.flatten([ moduleConfigs, projectModuleConfigs, processModuleConfigs ]);

        var modules = {
            SETTINGS_WORKSPACE: 'module:settings:workspace',
            SETTINGS_GROUPS: 'module:settings:groups',
            SETTINGS_ACTIVE_DIRECTORY: 'module:settings:activeDirectory',
            MYTASKS: 'module:myTasks',
            PEOPLE_USERS: 'module:people:users',
            DEMO_CORE: 'module:demo:core',

            PROJECT_ROOMS_SHOWALL: 'module:project:rooms:showAll',
            PROJECT_ROOMS_OVERVIEW: 'module:project:rooms:overview',

            PROCESS_PROCESSTEMPLATES_DESIGNER: 'module:process:processTemplates:designer',
            PROCESS_PROCESSTEMPLATES_ATTRIBUTES: 'module:process:processTemplates:attributes',
            PROCESS_PROCESSTEMPLATES_STATISTICS: 'module:process:processTemplates:statistics',
            PROCESS_PROCESSTEMPLATES_SETTINGS: 'module:process:processTemplates:settings',
            PROCESS_PROCESSTEMPLATES_SHOWALL: 'module:process:processTemplates:showAll',

            PROCESS_PROCESSTEMPLATES_DESIGNER_ACTIVITY_CONTEXT: 'module:process:processTemplates:designer:activity:context',
            PROCESS_PROCESSTEMPLATES_DESIGNER_ACTIVITY_FORMDESIGNER: 'module:process:processTemplates:designer:activity:formDesigner',
            PROCESS_PROCESSTEMPLATES_DESIGNER_ACTIVITY_SETTINGS: 'module:process:processTemplates:designer:activity:settings',
            PROCESS_PROCESSTEMPLATES_DESIGNER_ACTIVITY_RULES: 'module:process:processTemplates:designer:activity:rules',

            PROCESS_ARCHITECTURE_OVERVIEW: 'module:process:architecture:overview',
            PROCESS_ARCHITECTURE_DESIGNER: 'module:process:architecture:designer',
            PROCESS_ARCHITECTURE_DESIGNER_ACTIVITY_SETTINGS: 'module:process:architecture:designer:activity:settings',
            PROCESS_ARCHITECTURE_SHOWALL: 'module:process:architecture:showAll',

            PROCESS_RECORDTYPES_ATTRIBUTES: 'module:process:recordTypes:attributes',
            PROCESS_RECORDTYPES_DIAGRAM: 'module:process:recordTypes:diagram',
            PROCESS_RECORDTYPES_FORMDESIGNER: 'module:process:recordTypes:formDesigner',
            PROCESS_RECORDTYPES_SETTINGS: 'module:process:recordTypes:settings',
            PROCESS_RECORDTYPES_RECORDS: 'module:process:recordTypes:records',
            PROCESS_RECORDTYPES_SHOWALL: 'module:process:recordTypes:showAll',

            PROCESS_PROCESSMONITOR: 'module:process:processMonitor',
            PROCESS_DATADIAGRAM: 'module:process:dataDiagram',

            SUPPORT_GLOBAL_FUNCTIONS: 'module:support:globalFunctions'
        };

        return {
            getDefaultModuleUrl: function (moduleId, options) {
                return this.getModuleUrlByName('default', moduleId, options);
            },

            getModuleUrlByName: function (urlName, moduleId, options) {
                options = options || {};
                var moduleConfig = _.findWhere(configs, { id : moduleId });
                if (!moduleConfig) {
                    utilsApi.helpers.throwError('Failed to find a module with id `' + moduleId + '`.');
                }
                if (!moduleConfig.navigationUrl) {
                    utilsApi.helpers.throwError('The module `' + moduleId + '` is incomplete and doesn`t have navigationUrl.');
                }
                var url = moduleConfig.navigationUrl[urlName];
                if (!url) {
                    utilsApi.helpers.throwError('Failed to find navigation url `' + urlName + '` in the module `' + moduleId + '`');
                }

                var result = [];
                var lastIndex = 0;
                var match;
                var re = /:[^/]+(?=\/|$)/g;
                while (true) {
                    match = re.exec(url);
                    if (!match) {
                        break;
                    }
                    result.push(url.substring(lastIndex, match.index));
                    var param = match[0].substring(1);
                    var opt = options[param];
                    if (!opt) {
                        utilsApi.helpers.throwFormatError('Missing url options `' + param + '`.');
                    }
                    result.push(opt);
                    lastIndex = match.index + param.length + 1;
                }
                result.push(url.substring(lastIndex));
                var resultUrl = result.join('');
                if (resultUrl[0] !== '#') {
                    resultUrl = '#' + resultUrl;
                }
                return resultUrl;
            },

            modules: modules
        };
    });
<|endoftext|>


<commit_before>"use strict";

const _ = require('underscore');
const util = require('util');
const EventEmitter = require('events');

const NoopLogger = require(__dirname + '/noop-logger');
const EventConsts = require(__dirname + '/event-consts');
const ViberClient = require(__dirname + '/viber-client');
const Middleware = require(__dirname + '/middleware');
const RegexMatcherRouter = require(__dirname + '/regex-matcher-router');

const MessageFactory = require(__dirname + '/message/message-factory');
const MessageValidator = require(__dirname + '/message/message-validator');
const Message = require(__dirname + '/message/message');
const TextMessage = require(__dirname + '/message/text-message');

const UserProfile = require(__dirname + '/user-profile');
const Response = require(__dirname + '/response');

const REQUIRED_CONFIGURATION_FIELDS = ["authToken", "name", "avatar"];
const SUBSCRIBED_EVENTS = ["subscribed", "unsubscribed", "conversation_started", "message", "delivered", "seen"];
const API_URL = "https://chatapi.viber.com/pa";

function ViberBot(loggerOrConfiguration, configuration) {

	// backward compatibility: we are still allowing ctor as (logger, configuration);
	// newer should use (configuration) with logger property in it.
	let logger;
	if (!configuration) {
		// no logger, treat loggerOrConfiguration as configuration
		configuration = loggerOrConfiguration;
		logger = configuration.logger || NoopLogger;
	} else {
		logger = loggerOrConfiguration || NoopLogger;
	}

	if (!configuration) {
		throw new Error(`Invalid configuration`);
	}

	const missingFields = this._getMissingFieldsInConfiguration(configuration);
	if (!_.isEmpty(missingFields)) {
		throw new Error(`Invalid configuration ${configuration}. Missing fields: ${missingFields}`);
	}

	this.authToken = configuration.authToken;
	this.name = configuration.name;
	this.avatar = configuration.avatar;

	this._logger = logger;
	this._client = new ViberClient(this._logger, this, API_URL, configuration.registerToEvents || SUBSCRIBED_EVENTS);
	this._middleware = new Middleware(this._logger, new MessageValidator(this._logger, this.authToken));
	this._messageFactory = new MessageFactory(this._logger);
	this._regexMatcherRouter = new RegexMatcherRouter(this._logger);
	this._callbacks = { [EventConsts.CONVERSATION_STARTED]: [] };

	this._registerStreamAndHandleEvents(this._middleware.getStream());
	this._setupTextMessageReceivedHandler();
	this._setupConversationStartedHandler();
}
util.inherits(ViberBot, EventEmitter);

ViberBot.prototype.getBotProfile = function() {
	return this._client.getAccountInfo();
};

ViberBot.prototype.getUserDetails = function(userProfile) {
	return this._client.getUserDetails(userProfile.id).then(response => Promise.resolve(response.user));
};

ViberBot.prototype.getOnlineStatus = function(viberUserIds) {
	return this._client.getOnlineStatus(viberUserIds);
};

ViberBot.prototype.setWebhook = function(url) {
	return this._client.setWebhook(url);
};

ViberBot.prototype.sendMessage = function(userProfile, messages, optionalTrackingData) {
	if (messages == null) return Promise.resolve();
	messages = _.isArray(messages) ? messages : [messages];

	const self = this;
	const lastMessage = messages.pop();
	const tokens = [];

	const resolveCallback = (response, message, resolve, reject) => {
		if (response.status != 0) reject(response);
		tokens.push(response.message_token);
		self.emit(EventConsts.MESSAGE_SENT, message, userProfile);
		resolve();
	};

	let promise = Promise.resolve();
	_.each(messages, message => {
		promise = promise.then(() => new Promise((resolve, reject) =>
			self._sendMessageFromClient(userProfile, message).then(response => resolveCallback(response, message, resolve, reject))));
	});

	return promise.then(() => new Promise((resolve, reject) =>
		self._sendMessageFromClient(userProfile, lastMessage, optionalTrackingData, lastMessage.keyboard)
			.then(response => resolveCallback(response, lastMessage, resolve, reject))))
		.then(() => Promise.resolve(tokens));
};

ViberBot.prototype.middleware = function() {
	return this._middleware.getIncoming();
};

ViberBot.prototype.onTextMessage = function(regex, callback) {
	this._regexMatcherRouter.newMatcher(regex, callback);
};

ViberBot.prototype.onError = function(callback) {
	this.on(EventConsts.ERROR, callback);
};

ViberBot.prototype.onConversationStarted = function(callback) {
	this._callbacks[EventConsts.CONVERSATION_STARTED].push(callback);
};

ViberBot.prototype.onSubscribe = function(callback) {
	this.on(EventConsts.SUBSCRIBED, callback);
};

ViberBot.prototype.onUnsubscribe = function(callback) {
	this.on(EventConsts.UNSUBSCRIBED, callback);
};

ViberBot.prototype._setupTextMessageReceivedHandler = function() {
	const self = this;
	this.on(EventConsts.MESSAGE_RECEIVED, (message, response) => {
		if (!(message instanceof TextMessage)) return;

		const callback = this._regexMatcherRouter.tryGetCallback(message.text);
		if (!callback) {
			return self._logger.debug(`Could not find regex matcher for ${message.text}`);
		}
		callback(message, response);
	});
};

ViberBot.prototype._setupConversationStartedHandler = function() {
	const self = this;
	this.on(EventConsts.CONVERSATION_STARTED, (response, context) => {
		_.each(self._callbacks[EventConsts.CONVERSATION_STARTED], callback => {
			callback(response.userProfile, context => {
				return (response, context);
			});
		});
	});
};

ViberBot.prototype._getMissingFieldsInConfiguration = function(configuration) {
	return _.difference(REQUIRED_CONFIGURATION_FIELDS, Object.keys(configuration));
};

ViberBot.prototype._sendMessageFromClient = function(userProfile, message, optionalTrackingData, optionalKeyboard) {
	const jsonMessage = message.toJson();
	return this._client.sendMessage(userProfile.id, jsonMessage.type, jsonMessage, optionalTrackingData, optionalKeyboard);
};

ViberBot.prototype._registerStreamAndHandleEvents = function(stream) {
	const self = this;
	stream.on("data", data => {
		try {
			const parsedData = JSON.parse(data.toString());
			self._handleEventReceived(parsedData);
		}
		catch (err) {
			self._logger.error(err);
			self.emit(EventConsts.ERROR, err);
		}
	});
};

ViberBot.prototype._handleEventReceived = function(data) {
	const userProfile = this._getUserProfile(data);
	switch (data.event) {
		case EventConsts.MESSAGE_RECEIVED: {
			const message = this._messageFactory.createMessageFromJson(data);
			const response = new Response(this, userProfile);
			this.emit(data.event, message, response);
			break;
		}
		case EventConsts.SUBSCRIBED:
		case EventConsts.CONVERSATION_STARTED: {
			const response = new Response(this, userProfile);
			this.emit(data.event, response, data.context);
			break;
		}
		case EventConsts.UNSUBSCRIBED: {
			this.emit(data.event, data.user_id);
			break;
		}
		case EventConsts.FAILED: {
			this.emit(EventConsts.ERROR, data);
			break;
		}
		default: {
			this.emit(data.event, data);
			break;
		}
	}
};

ViberBot.prototype._getUserProfile = function(data) {
	if (_.has(data, "sender")) return UserProfile.fromJson(data.sender);
	else if (_.has(data, "user")) return UserProfile.fromJson(data.user);
	return null;
};

module.exports = ViberBot;

<commit_msg>Update viber-bot.js<commit_after>"use strict";

const _ = require('underscore');
const util = require('util');
const EventEmitter = require('events');

const NoopLogger = require(__dirname + '/noop-logger');
const EventConsts = require(__dirname + '/event-consts');
const ViberClient = require(__dirname + '/viber-client');
const Middleware = require(__dirname + '/middleware');
const RegexMatcherRouter = require(__dirname + '/regex-matcher-router');

const MessageFactory = require(__dirname + '/message/message-factory');
const MessageValidator = require(__dirname + '/message/message-validator');
const Message = require(__dirname + '/message/message');
const TextMessage = require(__dirname + '/message/text-message');

const UserProfile = require(__dirname + '/user-profile');
const Response = require(__dirname + '/response');

const REQUIRED_CONFIGURATION_FIELDS = ["authToken", "name", "avatar"];
const SUBSCRIBED_EVENTS = ["subscribed", "unsubscribed", "conversation_started", "message", "delivered", "seen"];
const API_URL = "https://chatapi.viber.com/pa";

function ViberBot(loggerOrConfiguration, configuration) {

	// backward compatibility: we are still allowing ctor as (logger, configuration);
	// newer should use (configuration) with logger property in it.
	let logger;
	if (!configuration) {
		// no logger, treat loggerOrConfiguration as configuration
		configuration = loggerOrConfiguration;
		logger = configuration.logger || NoopLogger;
	} else {
		logger = loggerOrConfiguration || NoopLogger;
	}

	if (!configuration) {
		throw new Error(`Invalid configuration`);
	}

	const missingFields = this._getMissingFieldsInConfiguration(configuration);
	if (!_.isEmpty(missingFields)) {
		throw new Error(`Invalid configuration ${configuration}. Missing fields: ${missingFields}`);
	}

	this.authToken = configuration.authToken;
	this.name = configuration.name;
	this.avatar = configuration.avatar;

	this._logger = logger;
	this._client = new ViberClient(this._logger, this, API_URL, configuration.registerToEvents || SUBSCRIBED_EVENTS);
	this._middleware = new Middleware(this._logger, new MessageValidator(this._logger, this.authToken));
	this._messageFactory = new MessageFactory(this._logger);
	this._regexMatcherRouter = new RegexMatcherRouter(this._logger);
	this._callbacks = { [EventConsts.CONVERSATION_STARTED]: [] };

	this._registerStreamAndHandleEvents(this._middleware.getStream());
	this._setupTextMessageReceivedHandler();
	this._setupConversationStartedHandler();
}
util.inherits(ViberBot, EventEmitter);

ViberBot.prototype.getBotProfile = function() {
	return this._client.getAccountInfo();
};

ViberBot.prototype.getUserDetails = function(userProfile) {
	return this._client.getUserDetails(userProfile.id).then(response => Promise.resolve(response.user));
};

ViberBot.prototype.getOnlineStatus = function(viberUserIds) {
	return this._client.getOnlineStatus(viberUserIds);
};

ViberBot.prototype.setWebhook = function(url) {
	return this._client.setWebhook(url);
};

ViberBot.prototype.sendMessage = function(userProfile, messages, optionalTrackingData) {
	if (messages == null) return Promise.resolve();
	messages = _.isArray(messages) ? messages : [messages];

	const self = this;
	const lastMessage = messages.pop();
	const tokens = [];

	const resolveCallback = (response, message, resolve, reject) => {
		if (response.status != 0) reject(response);
		tokens.push(response.message_token);
		self.emit(EventConsts.MESSAGE_SENT, message, userProfile);
		resolve();
	};

	let promise = Promise.resolve();
	_.each(messages, message => {
		promise = promise.then(() => new Promise((resolve, reject) =>
			self._sendMessageFromClient(userProfile, message).then(response => resolveCallback(response, message, resolve, reject))));
	});

	return promise.then(() => new Promise((resolve, reject) =>
		self._sendMessageFromClient(userProfile, lastMessage, optionalTrackingData, lastMessage.keyboard)
			.then(response => resolveCallback(response, lastMessage, resolve, reject))))
		.then(() => Promise.resolve(tokens));
};

ViberBot.prototype.middleware = function() {
	return this._middleware.getIncoming();
};

ViberBot.prototype.onTextMessage = function(regex, callback) {
	this._regexMatcherRouter.newMatcher(regex, callback);
};

ViberBot.prototype.onError = function(callback) {
	this.on(EventConsts.ERROR, callback);
};

ViberBot.prototype.onConversationStarted = function(callback) {
	this._callbacks[EventConsts.CONVERSATION_STARTED].push(callback);
};

ViberBot.prototype.onSubscribe = function(callback) {
	this.on(EventConsts.SUBSCRIBED, callback);
};

ViberBot.prototype.onUnsubscribe = function(callback) {
	this.on(EventConsts.UNSUBSCRIBED, callback);
};

ViberBot.prototype._setupTextMessageReceivedHandler = function() {
	const self = this;
	this.on(EventConsts.MESSAGE_RECEIVED, (message, response) => {
		if (!(message instanceof TextMessage)) return;

		const callback = this._regexMatcherRouter.tryGetCallback(message.text);
		if (!callback) {
			return self._logger.debug(`Could not find regex matcher for ${message.text}`);
		}
		callback(message, response);
	});
};

ViberBot.prototype._setupConversationStartedHandler = function() {
	const self = this;
	this.on(EventConsts.CONVERSATION_STARTED, (response, context) => {
		_.each(self._callbacks[EventConsts.CONVERSATION_STARTED], callback => {
			callback(response.userProfile, context => {
				callback(response, context);
			});
		});
	});
};

ViberBot.prototype._getMissingFieldsInConfiguration = function(configuration) {
	return _.difference(REQUIRED_CONFIGURATION_FIELDS, Object.keys(configuration));
};

ViberBot.prototype._sendMessageFromClient = function(userProfile, message, optionalTrackingData, optionalKeyboard) {
	const jsonMessage = message.toJson();
	return this._client.sendMessage(userProfile.id, jsonMessage.type, jsonMessage, optionalTrackingData, optionalKeyboard);
};

ViberBot.prototype._registerStreamAndHandleEvents = function(stream) {
	const self = this;
	stream.on("data", data => {
		try {
			const parsedData = JSON.parse(data.toString());
			self._handleEventReceived(parsedData);
		}
		catch (err) {
			self._logger.error(err);
			self.emit(EventConsts.ERROR, err);
		}
	});
};

ViberBot.prototype._handleEventReceived = function(data) {
	const userProfile = this._getUserProfile(data);
	switch (data.event) {
		case EventConsts.MESSAGE_RECEIVED: {
			const message = this._messageFactory.createMessageFromJson(data);
			const response = new Response(this, userProfile);
			this.emit(data.event, message, response);
			break;
		}
		case EventConsts.SUBSCRIBED:
		case EventConsts.CONVERSATION_STARTED: {
			const response = new Response(this, userProfile);
			this.emit(data.event, response, data.context);
			break;
		}
		case EventConsts.UNSUBSCRIBED: {
			this.emit(data.event, data.user_id);
			break;
		}
		case EventConsts.FAILED: {
			this.emit(EventConsts.ERROR, data);
			break;
		}
		default: {
			this.emit(data.event, data);
			break;
		}
	}
};

ViberBot.prototype._getUserProfile = function(data) {
	if (_.has(data, "sender")) return UserProfile.fromJson(data.sender);
	else if (_.has(data, "user")) return UserProfile.fromJson(data.user);
	return null;
};

module.exports = ViberBot;

<|endoftext|>


<commit_before>import React, { useState } from "react";
import { StyleSheet, View, FlatList, RefreshControl, Modal, ActivityIndicator } from "react-native";
import { useDispatch, useSelector } from "react-redux";
import { Divider } from "react-native-elements";
import ImageViewer from "react-native-image-zoom-viewer";
import MastoRow from "../components/MastoRow";
import { hide as HideAction, deleting as DeleteAction } from "../actions/actioncreators/main";
import { boost as BoostAction, favourite as FavouriteAction, bookmark as BookmarkAction } from "../actions/actioncreators/mastorow";
import { open as openImageViewerAction, close as closeImageViewerAction } from "../actions/actioncreators/imageviewer";
import * as RouterName from "../constants/RouterName";

import NavigationService from "../services/NavigationService";
import { oldLoadingTimeline, newLoadingTimeline } from "../actions/actioncreators/main";
const reducerSelector = state => ({
    current: state.currentUserReducer,
    main: state.mainReducer,
    streaming: state.streamingReducer,
    imageviewer: state.imageViewerReducer,
});

const REFRESH_TIME = 300;

function MastoList({ navigation, type }) {
    const dispatch = useDispatch();
    const [init, setInit] = useState(false);
    const { current, main, streaming, imageviewer } = useSelector(reducerSelector);
    const listdata = main[type];
    const streamingType = streaming[type];
    if (!init && listdata && listdata.data instanceof Array && listdata.data.length < 1) {
        setInit(true);
        dispatch(newLoadingTimeline(type, listdata.maxId, true));
    }
    const actions = {
        ReplyAction: (id, tootid, user, acct, image, body) => NavigationService.navigate({ name: RouterName.Toot, params: { id, tootid, user, acct, image, body }}),

        BoostAction: (id, tootid, boosted) => {dispatch(BoostAction(id, tootid, boosted))},
        FavouriteAction: (id, tootid, favourited) => {dispatch(FavouriteAction(id, tootid, favourited))},
        BookmarkAction: (id, tootid, bookmarked) => {dispatch(BookmarkAction(id, tootid, bookmarked))},
        HideAction: (id) => {dispatch(HideAction(id))},
        DeleteAction: (id) => {dispatch(DeleteAction(id))},
        openImageViewerAction: (media, index) => {dispatch(openImageViewerAction(media, index))},
        closeImageViewerAction: () => {dispatch(closeImageViewerAction())},
    };
    return (
        <View style={styles.container}>
            <FlatList
                keyExtractor={data => data.id}
                data={listdata.data}
                refreshControl={
                    <RefreshControl
                        enabled={!streamingType}
                        refreshing={listdata.refreshing}
                        onRefresh={() => {
                            if(streamingType){
                                return;
                            }
                            const time = Math.floor(new Date().getTime() / 1000);
                            if(time - listdata.lastUpdate >= REFRESH_TIME){
                                dispatch(newLoadingTimeline(type, null, true));
                            }else{
                                dispatch(newLoadingTimeline(type, listdata.maxId));
                            }
                        }}
                    />}
                renderItem={({ item }) => <MastoRow item={item} current={current} actions={actions} />}
                ItemSeparatorComponent={() => <Divider />}
                onEndReachedThreshold={1.5}
                ListFooterComponent={() =>
                    !listdata.refreshing && listdata.loading &&
                    <View style={styles.loading}>
                        <ActivityIndicator size="large" />
                    </View>
                }
                onEndReached={() => {
                    if(init && listdata && listdata.data instanceof Array && listdata.data.length >= 10 && !listdata.loading){
                        dispatch(oldLoadingTimeline(type, listdata.minId));
                    }
                }}
            />
            <Modal visible={imageviewer.visible} transparent={true} onRequestClose={() => actions.closeImageViewerAction()}>
                <ImageViewer imageUrls={imageviewer.data} index={imageviewer.index}
                    enableSwipeDown={true}
                    loadingRender={() => <ActivityIndicator size="large" color={"#FFFFFF"} />}
                    onSwipeDown={() => { actions.closeImageViewerAction()}} />
            </Modal>
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    loading: {
        paddingTop: 10,
        paddingBottom: 10
    }
});

export default MastoList;<commit_msg>extraData追加<commit_after>import React, { useState } from "react";
import { StyleSheet, View, FlatList, RefreshControl, Modal, ActivityIndicator } from "react-native";
import { useDispatch, useSelector } from "react-redux";
import { Divider } from "react-native-elements";
import ImageViewer from "react-native-image-zoom-viewer";
import MastoRow from "../components/MastoRow";
import { hide as HideAction, deleting as DeleteAction } from "../actions/actioncreators/main";
import { boost as BoostAction, favourite as FavouriteAction, bookmark as BookmarkAction } from "../actions/actioncreators/mastorow";
import { open as openImageViewerAction, close as closeImageViewerAction } from "../actions/actioncreators/imageviewer";
import * as RouterName from "../constants/RouterName";

import NavigationService from "../services/NavigationService";
import { oldLoadingTimeline, newLoadingTimeline } from "../actions/actioncreators/main";
const reducerSelector = state => ({
    current: state.currentUserReducer,
    main: state.mainReducer,
    streaming: state.streamingReducer,
    imageviewer: state.imageViewerReducer,
});

const REFRESH_TIME = 300;

function MastoList({ navigation, type }) {
    const dispatch = useDispatch();
    const [init, setInit] = useState(false);
    const { current, main, streaming, imageviewer } = useSelector(reducerSelector);
    const listdata = main[type];
    const streamingType = streaming[type];
    if (!init && listdata && listdata.data instanceof Array && listdata.data.length < 1) {
        setInit(true);
        dispatch(newLoadingTimeline(type, listdata.maxId, true));
    }
    const actions = {
        ReplyAction: (id, tootid, user, acct, image, body) => NavigationService.navigate({ name: RouterName.Toot, params: { id, tootid, user, acct, image, body }}),

        BoostAction: (id, tootid, boosted) => {dispatch(BoostAction(id, tootid, boosted))},
        FavouriteAction: (id, tootid, favourited) => {dispatch(FavouriteAction(id, tootid, favourited))},
        BookmarkAction: (id, tootid, bookmarked) => {dispatch(BookmarkAction(id, tootid, bookmarked))},
        HideAction: (id) => {dispatch(HideAction(id))},
        DeleteAction: (id) => {dispatch(DeleteAction(id))},
        openImageViewerAction: (media, index) => {dispatch(openImageViewerAction(media, index))},
        closeImageViewerAction: () => {dispatch(closeImageViewerAction())},
    };
    return (
        <View style={styles.container}>
            <FlatList
                keyExtractor={data => data.id}
                data={listdata.data}
                extraData={listdata.data}
                refreshControl={
                    <RefreshControl
                        enabled={!streamingType}
                        refreshing={listdata.refreshing}
                        onRefresh={() => {
                            if(streamingType){
                                return;
                            }
                            const time = Math.floor(new Date().getTime() / 1000);
                            if(time - listdata.lastUpdate >= REFRESH_TIME){
                                dispatch(newLoadingTimeline(type, null, true));
                            }else{
                                dispatch(newLoadingTimeline(type, listdata.maxId));
                            }
                        }}
                    />}
                renderItem={({ item }) => <MastoRow item={item} current={current} actions={actions} />}
                ItemSeparatorComponent={() => <Divider />}
                onEndReachedThreshold={1.5}
                ListFooterComponent={() =>
                    !listdata.refreshing && listdata.loading &&
                    <View style={styles.loading}>
                        <ActivityIndicator size="large" />
                    </View>
                }
                onEndReached={() => {
                    if(init && listdata && listdata.data instanceof Array && listdata.data.length >= 10 && !listdata.loading){
                        dispatch(oldLoadingTimeline(type, listdata.minId));
                    }
                }}
            />
            <Modal visible={imageviewer.visible} transparent={true} onRequestClose={() => actions.closeImageViewerAction()}>
                <ImageViewer imageUrls={imageviewer.data} index={imageviewer.index}
                    enableSwipeDown={true}
                    loadingRender={() => <ActivityIndicator size="large" color={"#FFFFFF"} />}
                    onSwipeDown={() => { actions.closeImageViewerAction()}} />
            </Modal>
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    loading: {
        paddingTop: 10,
        paddingBottom: 10
    }
});

export default MastoList;<|endoftext|>


<commit_before>import Ember from 'ember';
import charts from 'regard-highcharts';

export default Ember.Component.extend({
  draw: function (data, xAxisLabel, yAxisLabel) {
    var chartData = charts.bar(data, xAxisLabel, yAxisLabel);
    this.$().highcharts(chartData);
  },

  update: function () {
    var data = this.get('data');
    var xAxisLabel = this.get('xAxisLabel');
    var yAxisLabel = this.get('yAxisLabel');

    this.draw(data, xAxisLabel, yAxisLabel);
  }.observes('data')
});
<commit_msg>Update points if we can, rather than redrawing the whole chart<commit_after>import Ember from 'ember';
import charts from 'regard-highcharts';

export default Ember.Component.extend({
  draw: function (data, xAxisLabel, yAxisLabel) {
    var data = this.get('data');
    var xAxisLabel = this.get('xAxisLabel');
    var yAxisLabel = this.get('yAxisLabel');

    var chartData = charts.bar(data, xAxisLabel, yAxisLabel);
    chartData.chart.renderTo = this.$()[0];
    var chart = new Highcharts.Chart(chartData);

    this.set('chart', chart);
  },

  redraw: function(data) {
    var chart = this.get('chart');

    if(chart && chart.series[0].data.length === data.length) {
      var newPoints = data.map(x => x.value);

      $.each(chart.series[0].data, function (i, point) {
        point.update(newPoints[i], false);
      });

      chart.redraw();
    } else {
      this.draw();
    }
  },

  update: function () {
    this.redraw();
  }.observes('data')
});
<|endoftext|>


<commit_before>'use strict';

var EE = require('events').EventEmitter;
var async = require('async');
var _ = require('lodash');
var WebSocket = require('ws');
var debug = require('debug')('ws');

module.exports = {
  create: create
};

function create(scenarioSpec, scriptConfig, initialContext) {
  var ee = new EE();
  var ws = new WebSocket(scriptConfig.target);

  var zeroth = function(callback) {
      callback(null, initialContext);
    };

  var tasks = _.foldl(scenarioSpec, function(acc, rs) {
      acc.push(createStep(rs, scriptConfig, ee, ws));
      return acc;
    }, [zeroth]);

  ws.on('error', function onError(err) {
    debug(err);
    ee.emit('error', err.code);
  });

  ws.on('close', function onClose(code, message) {
    debug(code);
    debug(message);
  });

  var scenarioTask = function(callback) {
    ws.on('open', function onOpen() {
      async.waterfall(tasks, function(err, scenarioContext) {
        ws.close();
        return callback(err, scenarioContext);
      });
    });
  };

  ee.launch = function(callback) {
      ee.emit('started');
      scenarioTask(callback);
    };

  return ee;
}

function createStep(requestSpec, scriptConfig, ee, ws) {
  if (typeof requestSpec.think === 'number') {
    return function(context, callback) {
      debug('thinking for ' + requestSpec.think + ' seconds');
      setTimeout(function() {
        callback(null, context);
      }, requestSpec.think * 1000);
    };
  }

  // FIXME: Presuming it's {"send": "payload"} here
  var f = function(context, callback) {
    ee.emit('request');
    var startedAt = process.hrtime();
    ws.send(requestSpec.send, function(err) {
      if (err) {
        debug(err);
        ee.emit('error', err.code);
      } else {
        var endedAt = process.hrtime(startedAt);
        var delta = (endedAt[0] * 1e9) + endedAt[1];
        ee.emit('response', delta / 1e6);
      }
      return callback(err, context);
    });
  };

  return f;
}
<commit_msg>Report latency in ns in ws_worker<commit_after>'use strict';

var EE = require('events').EventEmitter;
var async = require('async');
var _ = require('lodash');
var WebSocket = require('ws');
var debug = require('debug')('ws');

module.exports = {
  create: create
};

function create(scenarioSpec, scriptConfig, initialContext) {
  var ee = new EE();
  var ws = new WebSocket(scriptConfig.target);

  var zeroth = function(callback) {
      callback(null, initialContext);
    };

  var tasks = _.foldl(scenarioSpec, function(acc, rs) {
      acc.push(createStep(rs, scriptConfig, ee, ws));
      return acc;
    }, [zeroth]);

  ws.on('error', function onError(err) {
    debug(err);
    ee.emit('error', err.code);
  });

  ws.on('close', function onClose(code, message) {
    debug(code);
    debug(message);
  });

  var scenarioTask = function(callback) {
    ws.on('open', function onOpen() {
      async.waterfall(tasks, function(err, scenarioContext) {
        ws.close();
        return callback(err, scenarioContext);
      });
    });
  };

  ee.launch = function(callback) {
      ee.emit('started');
      scenarioTask(callback);
    };

  return ee;
}

function createStep(requestSpec, scriptConfig, ee, ws) {
  if (typeof requestSpec.think === 'number') {
    return function(context, callback) {
      debug('thinking for ' + requestSpec.think + ' seconds');
      setTimeout(function() {
        callback(null, context);
      }, requestSpec.think * 1000);
    };
  }

  // FIXME: Presuming it's {"send": "payload"} here
  var f = function(context, callback) {
    ee.emit('request');
    var startedAt = process.hrtime();
    ws.send(requestSpec.send, function(err) {
      if (err) {
        debug(err);
        ee.emit('error', err.code);
      } else {
        var endedAt = process.hrtime(startedAt);
        var delta = (endedAt[0] * 1e9) + endedAt[1];
        ee.emit('response', delta);
      }
      return callback(err, context);
    });
  };

  return f;
}
<|endoftext|>


<commit_before>'use strict';

var async = require('async');
var _ = require('lodash');
var WebSocket = require('ws');
var debug = require('debug')('ws');
var workerUtil = require('./worker_util');

module.exports = {
  compile: compile
};

function compile(scenarioSpec, config, ee) {
  function zero(callback) {
    var ws = new WebSocket(config.target);
    ws.on('open', function() {
      ee.emit('started');
      return callback(null, {ws: ws});
    });
    ws.once('error', function(err) {
      ee.emit('error', err.code);
      return callback(err, {});
    });
  }

  var tasks = _.map(scenarioSpec, function(rs) {
    return createStep(rs, config, ee);
  });

  return function scenario(initialContext, callback) {
    initialContext._successCount = 0;
    initialContext._pendingRequests = _.size(
      _.reject(scenarioSpec, function(rs) {
        return (typeof rs.think === 'number');
      }));

    var steps = _.flatten([
      zero,
      tasks
    ]);

    async.waterfall(
      steps,
      function scenarioWaterfallCb(err, context) {
        return callback(err, context);
      });
  };
}

function createStep(requestSpec, config, ee) {
  if (requestSpec.think) {
    return workerUtil.createThink(requestSpec);
  }

  var f = function(context, callback) {
    ee.emit('request');
    var startedAt = process.hrtime();
    context.ws.send(requestSpec.send, function(err) {
      if (err) {
        debug(err);
        ee.emit('error', err);
      } else {
        var endedAt = process.hrtime(startedAt);
        var delta = (endedAt[0] * 1e9) + endedAt[1];
        ee.emit('response', delta, 0);
      }
      return callback(err, context);
    });
  };

  return f;
}
<commit_msg>Close WS connection when scenario finishes<commit_after>'use strict';

var async = require('async');
var _ = require('lodash');
var WebSocket = require('ws');
var debug = require('debug')('ws');
var workerUtil = require('./worker_util');

module.exports = {
  compile: compile
};

function compile(scenarioSpec, config, ee) {
  function zero(callback) {
    var ws = new WebSocket(config.target);
    ws.on('open', function() {
      ee.emit('started');
      return callback(null, {ws: ws});
    });
    ws.once('error', function(err) {
      ee.emit('error', err.code);
      return callback(err, {});
    });
  }

  var tasks = _.map(scenarioSpec, function(rs) {
    return createStep(rs, config, ee);
  });

  return function scenario(initialContext, callback) {
    initialContext._successCount = 0;
    initialContext._pendingRequests = _.size(
      _.reject(scenarioSpec, function(rs) {
        return (typeof rs.think === 'number');
      }));

    var steps = _.flatten([
      zero,
      tasks
    ]);

    async.waterfall(
      steps,
      function scenarioWaterfallCb(err, context) {
        context.ws.close();
        return callback(err, context);
      });
  };
}

function createStep(requestSpec, config, ee) {
  if (requestSpec.think) {
    return workerUtil.createThink(requestSpec);
  }

  var f = function(context, callback) {
    ee.emit('request');
    var startedAt = process.hrtime();
    context.ws.send(requestSpec.send, function(err) {
      if (err) {
        debug(err);
        ee.emit('error', err);
      } else {
        var endedAt = process.hrtime(startedAt);
        var delta = (endedAt[0] * 1e9) + endedAt[1];
        ee.emit('response', delta, 0);
      }
      return callback(err, context);
    });
  };

  return f;
}
<|endoftext|>


<commit_before>"use strict"; // eslint-disable-line quotes
const XLSX = require('xlsx');
const util = XLSX.utils;
const _ = require('lodash');

class Worksheet {
    constructor(x_ws, name, wb) {
        _.extend(this, x_ws);
        this.name = name;
        this._workbook = wb;
    }

    getCell(cell) {
        return this[cell];
    }

    getCol(col) {
        col = util.decode_col(col);
        return _.pickBy(this, (val, key)=>col==util.decode_cell(key).c);
    }

    getRow(row) {
        row = util.decode_row(row);
        return _.pickBy(this, (val, key)=>row==util.decode_cell(key).r);
    }
}
module.exports = Worksheet;
<commit_msg>Construct worksheet from array<commit_after>"use strict"; // eslint-disable-line quotes
const XLSX = require('xlsx');
const util = XLSX.utils;
const _ = require('lodash');

class Worksheet {
    constructor(data, name, wb) {
        if (data['!ref']) {
            _.extend(this, data);
        } else if (_.isArray(data)) {
            let maxLength = 0;
            data.forEach((row, r)=>{
                row.forEach((cell, c)=>{
                    this[util.encode_cell({c, r})] = cell;
                });
                maxLength = Math.max(maxLength, row.length-1);
            });
            this['!ref'] = util.encode_range({s: util.decode_cell('A1'), e: {c: maxLength, r: Math.max(data.length-1,0)}});
        }

        this.name = name;
        this._workbook = wb;
    }

    getCell(cell) {
        return this[cell];
    }

    getCol(col) {
        col = util.decode_col(col);
        return _.pickBy(this, (val, key)=>col==util.decode_cell(key).c);
    }

    getRow(row) {
        row = util.decode_row(row);
        return _.pickBy(this, (val, key)=>row==util.decode_cell(key).r);
    }
}
module.exports = Worksheet;
<|endoftext|>


<commit_before>var os = require('os');

module.exports = function write(selection, stream, done) {
  var svg = selection.property('outerHTML');
  stream.write('<?xml version="1.0" standalone="yes"?>' + os.EOL);
  stream.write(svg);
  if (stream !== process.stdout) {
    stream.end();
  }
  done();
};
<commit_msg>clean up write-svg<commit_after>const os = require('os');
const prolog = '<?xml version="1.0" standalone="yes"?>' + os.EOL;

module.exports = function write(selection, stream, done) {
  var svg = selection.property('outerHTML');
  stream.write(prolog);
  stream.write(svg);
  if (stream !== process.stdout) {
    stream.end();
  }
  done();
};
<|endoftext|>