<commit_before>/**
 * Create self executing function to avoid global scope creation
 */
(function (angular, tinymce,buildfire) {
    'use strict';
    angular
        .module('placesContent')
        .controller('ContentItemCtrl', ['$scope', 'Buildfire', 'DB', 'COLLECTIONS', '$routeParams', 'Location', 'Utils', '$timeout', 'EVENTS', 'PATHS', 'Messaging', 'item', 'placesInfo', 'DEFAULT_DATA',
            function ($scope, Buildfire, DB, COLLECTIONS, $routeParams, Location, Utils, $timeout, EVENTS, PATHS, Messaging, item, placesInfo, DEFAULT_DATA) {

                //Hide the INT header part.
                Buildfire.appearance.setHeaderVisibility(false);

                //Scroll current view to top when page loaded.
                buildfire.navigation.scrollTop();

                var tmrDelayForItem = null
                    , Items = new DB(COLLECTIONS.Items)
                    , PlaceInfo = new DB(COLLECTIONS.PlaceInfo)
                    , updating = false;

                var background = new Buildfire.components.images.thumbnail("#background");

                var placeInfoData;
                if (placesInfo) {
                    placeInfoData = placesInfo;
                }
                else {
                    placeInfoData = DEFAULT_DATA.PLACE_INFO;
                }

                $scope.itemShow = 'Content';

                var ContentItem = this;
                ContentItem.currentAddress = null;
                ContentItem.validCoordinatesFailure = false;
                ContentItem.currentCoordinates = null;

                if (item) {
                    ContentItem.item = item;
                    ContentItem.masterItem = angular.copy(ContentItem.item);
                }
                else {
                    ContentItem.item = angular.copy(DEFAULT_DATA.ITEM);
                    if ($routeParams.sectionId != 'allitems')
                        ContentItem.item.data.sections.push($routeParams.sectionId);
                    ContentItem.masterItem = angular.copy(ContentItem.item);
                }

                if (ContentItem.item.data && ContentItem.item.data.backgroundImage) {
                    background.loadbackground(ContentItem.item.data.backgroundImage);
                }

                background.onChange = function (url) {
                    ContentItem.item.data.backgroundImage = url;
                    if (!$scope.$$phase && !$scope.$root.$$phase) {
                        $scope.$apply();
                    }
                };

                background.onDelete = function (url) {
                    ContentItem.item.data.backgroundImage = "";
                    if (!$scope.$$phase && !$scope.$root.$$phase) {
                        $scope.$apply();
                    }
                };

                //option for wysiwyg
                ContentItem.bodyWYSIWYGOptions = {
                    plugins: 'advlist autolink link image lists charmap print preview',
                    skin: 'lightgray',
                    trusted: true,
                    theme: 'modern'
                };
                // create a new instance of the buildfire action Items
                ContentItem.linkEditor = new Buildfire.components.actionItems.sortableList("#actionItems");
                // this method will be called when a new item added to the list
                ContentItem.linkEditor.onAddItems = function (items) {
                    if (!ContentItem.item.data.links)
                        ContentItem.item.data.links = [];
                    ContentItem.item.data.links.push(items);
                    if (!$scope.$$phase)$scope.$digest();
                };
                // this method will be called when an item deleted from the list
                ContentItem.linkEditor.onDeleteItem = function (item, index) {
                    ContentItem.item.data.links.splice(index, 1);
                    if (!$scope.$$phase)$scope.$digest();
                };
                // this method will be called when you edit item details
                ContentItem.linkEditor.onItemChange = function (item, index) {
                    ContentItem.item.data.links.splice(index, 1, item);
                    if (!$scope.$$phase)$scope.$digest();
                };
                // this method will be called when you change the order of items
                ContentItem.linkEditor.onOrderChange = function (item, oldIndex, newIndex) {
                    var temp = ContentItem.item.data.links[oldIndex];
                    ContentItem.item.data.links[oldIndex] = ContentItem.item.data.links[newIndex];
                    ContentItem.item.data.links[newIndex] = temp;
                    if (!$scope.$$phase)$scope.$digest();
                };

                /**
                 * Initialize the carousel and links
                 */
                if (ContentItem.item.data.links)
                    ContentItem.linkEditor.loadItems(ContentItem.item.data.links);
                if (ContentItem.item.data.address && ContentItem.item.data.address.aName) {
                    ContentItem.currentAddress = ContentItem.item.data.address.aName;
                    ContentItem.currentCoordinates = [ContentItem.item.data.address.lng, ContentItem.item.data.address.lat];
                }

                /**
                 * This updateMasterItem will update the ContentMedia.masterItem with passed item
                 * @param item
                 */
                function updateMasterItem(item) {
                    ContentItem.masterItem = angular.copy(item);
                }

                /**
                 * This resetItem will reset the ContentMedia.item with ContentMedia.masterItem
                 */
                function resetItem() {
                    ContentItem.item = angular.copy(ContentItem.masterItem);
                }

                /**
                 * isUnChanged to check whether there is change in controller media item or not
                 * @param item
                 * @returns {*|boolean}
                 */
                function isUnChanged(item) {
                    return angular.equals(item, ContentItem.masterItem);
                }

                function insertAndUpdate(_item) {
                    updating = true;
                    if (_item.id) {
                        console.log('--------------------------------------insertAndUpdate _item.id',_item.id);
                        console.info('****************Item exist***********************');
                        Items.update(_item.id, _item.data).then(function (data) {
                            console.info('$$$$$$$$$$$$$$$$$ UPDATE CALLED $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$',_item.id, _item.data);
                            updating = false;
                            console.log('Data updated successfully---', data);
                        }, function (err) {
                            updating = false;
                            console.log('Error while updating data---', err);
                        });
                    }
                    else {
                        console.info('****************Item inserted***********************');
                        _item.data.rank = (placeInfoData.data.content.rankOfLastItemItems || 0) + 10;
                        _item.data.dateCreated = new Date();
                        console.log('--------------------------------------insertAndUpdate _item.data.dateCreated',_item.data.dateCreated);

                        Items.insert(_item.data).then(function (data) {
                            console.info('$$$$$$$$$$$$$$$$$ INSERT CALLED $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$',_item.data);
                       //     console.info('$$$$$$$$$$$$$$$$$ INSERT CALLED $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$',_item.data);
                            updating = false;
                            if (data && data.id) {
                                ContentItem.item.data.deepLinkUrl = Buildfire.deeplink.createLink({id: data.id});
                                console.log('--------------------------------------insertAndUpdate  ContentItem.item.data.deepLinkUrl ', ContentItem.item.data.deepLinkUrl );
                                ContentItem.item.id = data.id;
                                updateMasterItem(ContentItem.item);
                                placeInfoData.data.content.rankOfLastItemItems = _item.data.rank;
                                PlaceInfo.save(placeInfoData.data).then(function (data) {
                                    console.log('--------------------------------------insertAndUpdate   PlaceInfo.save(placeInfoData.data).then(function (data) ', data);
                                }, function (err) {
                                    console.log('--------------------------------------insertAndUpdate  resetItem ');

                                    resetItem();
                                    console.error('Error while getting----------', err);
                                });
                            }
                            else {
                                resetItem();
                            }
                        }, function (err) {
                            updating = false;
                            console.log('Error---', err);
                        });
                    }
                }

                /**
                 * updateItemsWithDelay called when ever there is some change in current media item
                 * @param _item
                 */
                function updateItemsWithDelay(_item) {
                    console.log('--------------------------------------updateItemsWithDelay item',item);
                    if (updating)
                        return;
                    if (tmrDelayForItem) {
                        clearTimeout(tmrDelayForItem);
                    }
                    ContentItem.isItemValid = isValidItem(ContentItem.item.data);
                    console.log('--------------------------------------ContentItem.isItemValid',ContentItem.isItemValid);
                    if (_item && !isUnChanged(_item) && ContentItem.isItemValid) {
                        console.log('--------------------------------------isUnChanged ',isUnChanged(_item));
                        tmrDelayForItem = setTimeout(function () {
                            console.log('--------------------------------------insertAndUpdate called');
                            insertAndUpdate(_item);
                        }, 1000);
                    }
                }

                //init();
                ContentItem.addListImage = function () {
                    var options = {showIcons: false, multiSelection: false},
                        listImgCB = function (error, result) {
                            if (error) {
                                console.error('Error:', error);
                            } else {
                                ContentItem.item.data.listImage = result.selectedFiles && result.selectedFiles[0] || null;
                                if (!$scope.$$phase)$scope.$digest();
                            }
                        };
                    Buildfire.imageLib.showDialog(options, listImgCB);
                };
                ContentItem.removeListImage = function () {
                    ContentItem.item.data.listImage = null;
                };
                /**
                 * done will close the single item view
                 */
                ContentItem.done = function () {
                    if ($routeParams.sectionId != 'allitems') {
                        Location.go('#/items/' + $routeParams.sectionId);
                    }
                    else {
                        Location.go('#/allitems')
                    }
                };
                ContentItem.setLocation = function (data) {
                    ContentItem.item.data.address = {
                        lng: data.coordinates[0],
                        lat: data.coordinates[1],
                        aName: data.location
                    };
                    ContentItem.currentAddress = data.location;
                    ContentItem.currentCoordinates = data.coordinates;
                    if (!$scope.$$phase)$scope.$digest();
                };
                ContentItem.setDraggedLocation = function (data) {
                    ContentItem.item.data.address = {
                        lng: data.coordinates[0],
                        lat: data.coordinates[1],
                        aName: data.location
                    };
                    ContentItem.currentAddress = data.location;
                    ContentItem.currentCoordinates = data.coordinates;
                    if (!$scope.$$phase)$scope.$digest();
                };
                ContentItem.setCoordinates = function () {
                    function successCallback(resp) {
                        if (resp) {
                            ContentItem.item.data.address = {
                                lng: ContentItem.currentAddress.split(",")[0].trim(),
                                lat: ContentItem.currentAddress.split(",")[1].trim(),
                                aName: ContentItem.currentAddress
                            };
                            ContentItem.currentCoordinates = [ContentItem.currentAddress.split(",")[0].trim(), ContentItem.currentAddress.split(",")[1].trim()];
                        } else {
                            errorCallback();
                        }
                    }

                    function errorCallback(err) {
                        ContentItem.validCoordinatesFailure = true;
                        $timeout(function () {
                            ContentItem.validCoordinatesFailure = false;
                        }, 5000);
                    }

                    Utils.validLongLats(ContentItem.currentAddress).then(successCallback, errorCallback);
                };
                ContentItem.clearData = function () {
                    if (!ContentItem.currentAddress) {
                        ContentItem.item.data.address = {
                            lng: '',
                            lat: '',
                            aName: ''
                        };
                        ContentItem.currentCoordinates = null;
                    }
                };

                //to validate the item
                function isValidItem(item) {
                    return item.itemTitle;
                }

                //syn with widget
                Messaging.sendMessageToWidget({
                    name: EVENTS.ROUTE_CHANGE,
                    message: {
                        path: PATHS.ITEM,
                        //id: ContentItem.item ? ContentItem.item.id : "",
                        id: $routeParams.itemId,
                        secId: $routeParams.sectionId
                    }
                });

                $scope.$watch(function () {
                    return ContentItem.item;
                }, updateItemsWithDelay, true);
            }]);
})(window.angular, window.tinymce,window.buildfire);<commit_msg>Made the changes for multiple items<commit_after>/**
 * Create self executing function to avoid global scope creation
 */
(function (angular, tinymce,buildfire) {
    'use strict';
    angular
        .module('placesContent')
        .controller('ContentItemCtrl', ['$scope', 'Buildfire', 'DB', 'COLLECTIONS', '$routeParams', 'Location', 'Utils', '$timeout', 'EVENTS', 'PATHS', 'Messaging', 'item', 'placesInfo', 'DEFAULT_DATA',
            function ($scope, Buildfire, DB, COLLECTIONS, $routeParams, Location, Utils, $timeout, EVENTS, PATHS, Messaging, item, placesInfo, DEFAULT_DATA) {

                //Hide the INT header part.
                Buildfire.appearance.setHeaderVisibility(false);

                //Scroll current view to top when page loaded.
                buildfire.navigation.scrollTop();

                var tmrDelayForItem = null
                    , Items = new DB(COLLECTIONS.Items)
                    , PlaceInfo = new DB(COLLECTIONS.PlaceInfo)
                    , updating = false;

                var background = new Buildfire.components.images.thumbnail("#background");

                var placeInfoData;
                if (placesInfo) {
                    placeInfoData = placesInfo;
                }
                else {
                    placeInfoData = DEFAULT_DATA.PLACE_INFO;
                }

                $scope.itemShow = 'Content';

                var ContentItem = this;
                ContentItem.currentAddress = null;
                ContentItem.validCoordinatesFailure = false;
                ContentItem.currentCoordinates = null;

                if (item) {
                    ContentItem.item = item;
                    ContentItem.masterItem = angular.copy(ContentItem.item);
                }
                else {
                    ContentItem.item = angular.copy(DEFAULT_DATA.ITEM);
                    if ($routeParams.sectionId != 'allitems')
                        ContentItem.item.data.sections.push($routeParams.sectionId);
                    ContentItem.masterItem = angular.copy(ContentItem.item);
                }

                if (ContentItem.item.data && ContentItem.item.data.backgroundImage) {
                    background.loadbackground(ContentItem.item.data.backgroundImage);
                }

                background.onChange = function (url) {
                    ContentItem.item.data.backgroundImage = url;
                    if (!$scope.$$phase && !$scope.$root.$$phase) {
                        $scope.$apply();
                    }
                };

                background.onDelete = function (url) {
                    ContentItem.item.data.backgroundImage = "";
                    if (!$scope.$$phase && !$scope.$root.$$phase) {
                        $scope.$apply();
                    }
                };

                //option for wysiwyg
                ContentItem.bodyWYSIWYGOptions = {
                    plugins: 'advlist autolink link image lists charmap print preview',
                    skin: 'lightgray',
                    trusted: true,
                    theme: 'modern'
                };
                // create a new instance of the buildfire action Items
                ContentItem.linkEditor = new Buildfire.components.actionItems.sortableList("#actionItems");
                // this method will be called when a new item added to the list
                ContentItem.linkEditor.onAddItems = function (items) {
                    if (!ContentItem.item.data.links)
                        ContentItem.item.data.links = [];
                    ContentItem.item.data.links.push(items);
                    if (!$scope.$$phase)$scope.$digest();
                };
                // this method will be called when an item deleted from the list
                ContentItem.linkEditor.onDeleteItem = function (item, index) {
                    ContentItem.item.data.links.splice(index, 1);
                    if (!$scope.$$phase)$scope.$digest();
                };
                // this method will be called when you edit item details
                ContentItem.linkEditor.onItemChange = function (item, index) {
                    ContentItem.item.data.links.splice(index, 1, item);
                    if (!$scope.$$phase)$scope.$digest();
                };
                // this method will be called when you change the order of items
                ContentItem.linkEditor.onOrderChange = function (item, oldIndex, newIndex) {
                    var temp = ContentItem.item.data.links[oldIndex];
                    ContentItem.item.data.links[oldIndex] = ContentItem.item.data.links[newIndex];
                    ContentItem.item.data.links[newIndex] = temp;
                    if (!$scope.$$phase)$scope.$digest();
                };

                /**
                 * Initialize the carousel and links
                 */
                if (ContentItem.item.data.links)
                    ContentItem.linkEditor.loadItems(ContentItem.item.data.links);
                if (ContentItem.item.data.address && ContentItem.item.data.address.aName) {
                    ContentItem.currentAddress = ContentItem.item.data.address.aName;
                    ContentItem.currentCoordinates = [ContentItem.item.data.address.lng, ContentItem.item.data.address.lat];
                }

                /**
                 * This updateMasterItem will update the ContentMedia.masterItem with passed item
                 * @param item
                 */
                function updateMasterItem(item) {
                    ContentItem.masterItem = angular.copy(item);
                }

                /**
                 * This resetItem will reset the ContentMedia.item with ContentMedia.masterItem
                 */
                function resetItem() {
                    ContentItem.item = angular.copy(ContentItem.masterItem);
                }

                /**
                 * isUnChanged to check whether there is change in controller media item or not
                 * @param item
                 * @returns {*|boolean}
                 */
                function isUnChanged(item) {
                    return angular.equals(item, ContentItem.masterItem);
                }

                function insertAndUpdate(_item) {
                    updating = true;
                    if (_item.id) {
                        console.log('--------------------------------------insertAndUpdate _item.id',_item.id);
                        console.info('****************Item exist***********************');
                        Items.update(_item.id, _item.data).then(function (data) {
                            console.info('$$$$$$$$$$$$$$$$$ UPDATE CALLED $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$',_item.id, _item.data);
                            updating = false;
                            console.log('Data updated successfully---', data);
                        }, function (err) {
                            updating = false;
                            console.log('Error while updating data---', err);
                        });
                    }
                    else {
                        console.info('****************Item inserted***********************');
                        _item.data.rank = (placeInfoData.data.content.rankOfLastItemItems || 0) + 10;
                        _item.data.dateCreated = new Date();
                        console.log('--------------------------------------insertAndUpdate _item.data.dateCreated',_item.data.dateCreated);

                        Items.insert(_item.data).then(function (data) {
                            console.info('$$$$$$$$$$$$$$$$$ INSERT CALLED $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$',data);
                       //     console.info('$$$$$$$$$$$$$$$$$ INSERT CALLED $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$',_item.data);
                            if (data && data.id) {
                                ContentItem.item.data.deepLinkUrl = Buildfire.deeplink.createLink({id: data.id});
                                console.log('--------------------------------------insertAndUpdate  ContentItem.item.data.deepLinkUrl ', ContentItem.item.data.deepLinkUrl );
                                ContentItem.item.id = data.id;
                                updateMasterItem(ContentItem.item);
                                placeInfoData.data.content.rankOfLastItemItems = _item.data.rank;
                                PlaceInfo.save(placeInfoData.data).then(function (data) {
                                    updating = false;
                                    console.log('--------------------------------------insertAndUpdate   PlaceInfo.save(placeInfoData.data).then(function (data) ', data);
                                }, function (err) {
                                    console.log('--------------------------------------insertAndUpdate  resetItem ');
                                    resetItem();
                                    updating = false;
                                    console.error('Error while getting----------', err);
                                });
                            }
                            else {
                                resetItem();
                                updating = false;
                            }
                        }, function (err) {
                            updating = false;
                            console.log('Error---', err);
                        });
                    }
                }

                /**
                 * updateItemsWithDelay called when ever there is some change in current media item
                 * @param _item
                 */
                function updateItemsWithDelay(_item) {
                    console.log('--------------------------------------updateItemsWithDelay item',item);
                    if (updating)
                        return;
                    if (tmrDelayForItem) {
                        clearTimeout(tmrDelayForItem);
                    }
                    ContentItem.isItemValid = isValidItem(ContentItem.item.data);
                    console.log('--------------------------------------ContentItem.isItemValid',ContentItem.isItemValid);
                    if (_item && !isUnChanged(_item) && ContentItem.isItemValid) {
                        console.log('--------------------------------------isUnChanged ',isUnChanged(_item));
                        tmrDelayForItem = setTimeout(function () {
                            console.log('--------------------------------------insertAndUpdate called');
                            insertAndUpdate(_item);
                        }, 1000);
                    }
                }

                //init();
                ContentItem.addListImage = function () {
                    var options = {showIcons: false, multiSelection: false},
                        listImgCB = function (error, result) {
                            if (error) {
                                console.error('Error:', error);
                            } else {
                                ContentItem.item.data.listImage = result.selectedFiles && result.selectedFiles[0] || null;
                                if (!$scope.$$phase)$scope.$digest();
                            }
                        };
                    Buildfire.imageLib.showDialog(options, listImgCB);
                };
                ContentItem.removeListImage = function () {
                    ContentItem.item.data.listImage = null;
                };
                /**
                 * done will close the single item view
                 */
                ContentItem.done = function () {
                    if ($routeParams.sectionId != 'allitems') {
                        Location.go('#/items/' + $routeParams.sectionId);
                    }
                    else {
                        Location.go('#/allitems')
                    }
                };
                ContentItem.setLocation = function (data) {
                    ContentItem.item.data.address = {
                        lng: data.coordinates[0],
                        lat: data.coordinates[1],
                        aName: data.location
                    };
                    ContentItem.currentAddress = data.location;
                    ContentItem.currentCoordinates = data.coordinates;
                    if (!$scope.$$phase)$scope.$digest();
                };
                ContentItem.setDraggedLocation = function (data) {
                    ContentItem.item.data.address = {
                        lng: data.coordinates[0],
                        lat: data.coordinates[1],
                        aName: data.location
                    };
                    ContentItem.currentAddress = data.location;
                    ContentItem.currentCoordinates = data.coordinates;
                    if (!$scope.$$phase)$scope.$digest();
                };
                ContentItem.setCoordinates = function () {
                    function successCallback(resp) {
                        if (resp) {
                            ContentItem.item.data.address = {
                                lng: ContentItem.currentAddress.split(",")[0].trim(),
                                lat: ContentItem.currentAddress.split(",")[1].trim(),
                                aName: ContentItem.currentAddress
                            };
                            ContentItem.currentCoordinates = [ContentItem.currentAddress.split(",")[0].trim(), ContentItem.currentAddress.split(",")[1].trim()];
                        } else {
                            errorCallback();
                        }
                    }

                    function errorCallback(err) {
                        ContentItem.validCoordinatesFailure = true;
                        $timeout(function () {
                            ContentItem.validCoordinatesFailure = false;
                        }, 5000);
                    }

                    Utils.validLongLats(ContentItem.currentAddress).then(successCallback, errorCallback);
                };
                ContentItem.clearData = function () {
                    if (!ContentItem.currentAddress) {
                        ContentItem.item.data.address = {
                            lng: '',
                            lat: '',
                            aName: ''
                        };
                        ContentItem.currentCoordinates = null;
                    }
                };

                //to validate the item
                function isValidItem(item) {
                    return item.itemTitle;
                }

                //syn with widget
                Messaging.sendMessageToWidget({
                    name: EVENTS.ROUTE_CHANGE,
                    message: {
                        path: PATHS.ITEM,
                        //id: ContentItem.item ? ContentItem.item.id : "",
                        id: $routeParams.itemId,
                        secId: $routeParams.sectionId
                    }
                });

                $scope.$watch(function () {
                    return ContentItem.item;
                }, updateItemsWithDelay, true);
            }]);
})(window.angular, window.tinymce,window.buildfire);<|endoftext|>


<commit_before>(function() {
  'use strict';

  var http = require('http');
  var https = require('https');
  var urlparse = require('url').parse;

  function XMLHttpRequest() {
    if (!(this instanceof XMLHttpRequest)) {
      throw new TypeError('DOM object constructor cannot be called as a function.');
    }

    // attributes
    this.readyState = XMLHttpRequest.UNSENT;;

    // request attributes
    this.timeout = null; // todo
    this.withCredentials = false; // todo
    this.upload = null; // todo

    // response attributes
    this.status = 0;
    this.statusText = '';
    this.responseType = ''; // todo
    this.response = ''; // todo
    this.responseText = '';
    this.responseXML = null;
  }

  (function(proto) {
    // private properties
    var _async = true;
    var _client = null;
    var _options = {};
    var _requestHeaders = {};
    var _responseHeaders = {};

    // states values
    (function(states) {
      var _objs = [XMLHttpRequest, proto];
      Object.keys(states).forEach(function(prop) {
        var _value = states[prop];
        _objs.forEach(function(_obj) {
          Object.defineProperty(_obj, prop, {
            value: _value,
            writable: false,
            enumerable: true,
            configurable: false
          });
        });
      });
    })({
      UNSENT: 0,
      OPENED: 1,
      HEADERS_RECEIVED: 2,
      LOADING: 3,
      DONE: 4
    });

    // callback listeners
    (function(types) {
      var _eventListeners = {};
      types.forEach(function(type) {
        Object.defineProperty(proto, 'on' + type, {
          get: function() {
            var _listener;
            return ((typeof (_listener = _eventListeners[type])) === 'undefined') ? null : _listener;
          },
          set: function(listener) {
            return _eventListeners[type] = listener;
          },
          enumerble: false,
          configurable: false
        });
      });
    })([
      'readystatechange',
      'loadstart',
      'progress', // todo
      'abort',
      'error', // todo
      'load',
      'timeout', // todo
      'loadend'
    ]);

    // methods
    proto.addEventListener = function addEventListener(type, listener, userCapture) {
      this['on' + type] = listener;
    };

    // request methods
    proto.open = function open(method, url, async, user, password) {
      if ((typeof method) === 'undefined' || (typeof url) === 'undefined') {
        throw new TypeError('Not enought arguments');
      }
      _options.method = method;
      (function(_parsedUrlObj) {
        _options.protocol = _parsedUrlObj.protocol || 'http:';
        _options.agent = ((_options.protocol === 'https:') ? https : http).globalAgent;
        _options.host = _parsedUrlObj.hostname || 'localhost';
        _options.port = _parsedUrlObj.port || ((_options.protocol === 'https:') ? 443 : 80);
        _options.path = _parsedUrlObj.path || '/';
      })(urlparse(url));
      if ((typeof async) !== 'undefined') {
        _async = async;
      }
      if ((typeof user) === 'string' && (typeof password) === 'string') {
        _options.auth = [user, password].join(':');
      }
      _readyStateChange.call(this, XMLHttpRequest.OPENED);
    };

    proto.setRequestHeader = function setRequestHeader(header, value) {
      if (this.readyState === XMLHttpRequest.UNSENT) {
        throw Error(''); // todo
      }
      _requestHeaders[header] = value;
    };

    proto.send = function send(body) {
      _client = new http.ClientRequest(_options);
      _client.on('response', _receiveResponse.bind(this));
      Object.keys(_requestHeaders).forEach(function(key) {
        _client.setHeader(key, _requestHeaders[key]);
      });
      _readyStateChange.call(this, XMLHttpRequest.HEADERS_RECEIVED);
      if ((typeof body) !== 'undefined' && body !== null) {
        _client.write(body);
      }
      _client.end();
    };

    proto.abort = function abort() {
      if (!(_client instanceof http.ClientRequest)) {
        return;
      }
      _client.abort();
      _dispatchEvent.call(this, 'abort');
    };

    // response methods
    proto.getResponseHeader = function getResponseHeader(header) {
      if (this.readyState === XMLHttpRequest.UNSENT || this.readyState === XMLHttpRequest.OPENED) {
        throw new Error(''); // todo;
      }
      return _responseHeaders[header.toLowerCase()] || null;
    };

    proto.getAllResponseHeaders = function getAllResponseHeaders() {
      if (this.readyState === XMLHttpRequest.UNSENT || this.readyState === XMLHttpRequest.OPENED) {
        throw new Error(''); // todo
      }
      return Object.keys(_responseHeaders).map(function(key) {
        return [key, _responseHeaders[key]].join(': ');
      }).join('\n');
    };

    proto.overrideMimeType = function overrideMimeType() {
      // todo
    };

    // private methods
    var _init = function _init() {
      _client = null;
      _options = {};
      _requestHeaders = {};
      _responseHeaders = {};
    };

    var _readyStateChange = function _readyStateChange(readyState) {
      this.readyState = readyState;
      _dispatchEvent.call(this, 'readystatechange');
    };

    var _dispatchEvent = function _dispatchEvent(type) {
      var _listener;
      if ((typeof (_listener = this['on'+type])) === 'function') {
        _listener.apply(this, [].slice(arguments, 1));
      }
    };

    var _receiveResponse = function _receiveResponse(response) {
      this.status = response.statusCode;
      this.statusText = http.STATUS_CODES[this.status];
      _responseHeaders = response.headers;
      _dispatchEvent.call(this, 'loadstart');
      _readyStateChange.call(this, XMLHttpRequest.LOADING);
      response.addListener('data', function(chunk) {
        _dispatchEvent.call(this, 'progress');
        this.responseText = chunk.toString();
      }.bind(this));
      response.addListener('end', function() {
        _dispatchEvent.call(this, 'load');
        _dispatchEvent.call(this, 'loadend');
        _readyStateChange.call(this, XMLHttpRequest.DONE);
        _init.call(this);
      }.bind(this));
    };
  })(XMLHttpRequest.prototype);

  function FormData() {
    if (!(this instanceof FormData)) {
      throw new TypeError('DOM object constructor cannot be called as a function.');
    }
  }

  (function(proto) {
    proto.append = function append(name, value, filename) {
      // todo
    };
  })(FormData.prototype);

  XMLHttpRequest.XMLHttpRequest = XMLHttpRequest;
  XMLHttpRequest.FormData = FormData;
  module.exports = XMLHttpRequest;
})();
<commit_msg>To the function must be ignored.<commit_after>(function() {
  'use strict';

  var http = require('http');
  var https = require('https');
  var urlparse = require('url').parse;

  function XMLHttpRequest() {
    if (!(this instanceof XMLHttpRequest)) {
      throw new TypeError('DOM object constructor cannot be called as a function.');
    }

    // attributes
    this.readyState = XMLHttpRequest.UNSENT;;

    // request attributes
    this.timeout = null; // todo
    this.withCredentials = false; // todo
    this.upload = null; // todo

    // response attributes
    this.status = 0;
    this.statusText = '';
    this.responseType = ''; // todo
    this.response = ''; // todo
    this.responseText = '';
    this.responseXML = null;
  }

  (function(proto) {
    // private properties
    var _async = true;
    var _client = null;
    var _options = {};
    var _requestHeaders = {};
    var _responseHeaders = {};

    // states values
    (function(states) {
      var _objs = [XMLHttpRequest, proto];
      Object.keys(states).forEach(function(prop) {
        var _value = states[prop];
        _objs.forEach(function(_obj) {
          Object.defineProperty(_obj, prop, {
            value: _value,
            writable: false,
            enumerable: true,
            configurable: false
          });
        });
      });
    })({
      UNSENT: 0,
      OPENED: 1,
      HEADERS_RECEIVED: 2,
      LOADING: 3,
      DONE: 4
    });

    // callback listeners
    (function(types) {
      var _eventListeners = {};
      types.forEach(function(type) {
        Object.defineProperty(proto, 'on' + type, {
          get: function() {
            var _listener = _eventListeners[type];
            if ((typeof _listener) !== 'function') {
              return null;
            }
            return _listener;
          },
          set: function(listener) {
            if ((typeof listener) !== 'function') {
              return listener;
            }
            return _eventListeners[type] = listener;
          },
          enumerble: false,
          configurable: false
        });
      });
    })([
      'readystatechange',
      'loadstart',
      'progress', // todo
      'abort',
      'error', // todo
      'load',
      'timeout', // todo
      'loadend'
    ]);

    // methods
    proto.addEventListener = function addEventListener(type, listener, userCapture) {
      this['on' + type] = listener;
    };

    // request methods
    proto.open = function open(method, url, async, user, password) {
      if ((typeof method) === 'undefined' || (typeof url) === 'undefined') {
        throw new TypeError('Not enought arguments');
      }
      _options.method = method;
      (function(_parsedUrlObj) {
        _options.protocol = _parsedUrlObj.protocol || 'http:';
        _options.agent = ((_options.protocol === 'https:') ? https : http).globalAgent;
        _options.host = _parsedUrlObj.hostname || 'localhost';
        _options.port = _parsedUrlObj.port || ((_options.protocol === 'https:') ? 443 : 80);
        _options.path = _parsedUrlObj.path || '/';
      })(urlparse(url));
      if ((typeof async) !== 'undefined') {
        _async = async;
      }
      if ((typeof user) === 'string' && (typeof password) === 'string') {
        _options.auth = [user, password].join(':');
      }
      _readyStateChange.call(this, XMLHttpRequest.OPENED);
    };

    proto.setRequestHeader = function setRequestHeader(header, value) {
      if (this.readyState === XMLHttpRequest.UNSENT) {
        throw Error(''); // todo
      }
      _requestHeaders[header] = value;
    };

    proto.send = function send(body) {
      _client = new http.ClientRequest(_options);
      _client.on('response', _receiveResponse.bind(this));
      Object.keys(_requestHeaders).forEach(function(key) {
        _client.setHeader(key, _requestHeaders[key]);
      });
      _readyStateChange.call(this, XMLHttpRequest.HEADERS_RECEIVED);
      if ((typeof body) !== 'undefined' && body !== null) {
        _client.write(body);
      }
      _client.end();
    };

    proto.abort = function abort() {
      if (!(_client instanceof http.ClientRequest)) {
        return;
      }
      _client.abort();
      _dispatchEvent.call(this, 'abort');
    };

    // response methods
    proto.getResponseHeader = function getResponseHeader(header) {
      if (this.readyState === XMLHttpRequest.UNSENT || this.readyState === XMLHttpRequest.OPENED) {
        throw new Error(''); // todo;
      }
      return _responseHeaders[header.toLowerCase()] || null;
    };

    proto.getAllResponseHeaders = function getAllResponseHeaders() {
      if (this.readyState === XMLHttpRequest.UNSENT || this.readyState === XMLHttpRequest.OPENED) {
        throw new Error(''); // todo
      }
      return Object.keys(_responseHeaders).map(function(key) {
        return [key, _responseHeaders[key]].join(': ');
      }).join('\n');
    };

    proto.overrideMimeType = function overrideMimeType() {
      // todo
    };

    // private methods
    var _init = function _init() {
      _client = null;
      _options = {};
      _requestHeaders = {};
      _responseHeaders = {};
    };

    var _readyStateChange = function _readyStateChange(readyState) {
      this.readyState = readyState;
      _dispatchEvent.call(this, 'readystatechange');
    };

    var _dispatchEvent = function _dispatchEvent(type) {
      var _listener;
      if ((typeof (_listener = this['on'+type])) === 'function') {
        _listener.apply(this, [].slice(arguments, 1));
      }
    };

    var _receiveResponse = function _receiveResponse(response) {
      this.status = response.statusCode;
      this.statusText = http.STATUS_CODES[this.status];
      _responseHeaders = response.headers;
      _dispatchEvent.call(this, 'loadstart');
      _readyStateChange.call(this, XMLHttpRequest.LOADING);
      response.addListener('data', function(chunk) {
        _dispatchEvent.call(this, 'progress');
        this.responseText = chunk.toString();
      }.bind(this));
      response.addListener('end', function() {
        _dispatchEvent.call(this, 'load');
        _dispatchEvent.call(this, 'loadend');
        _readyStateChange.call(this, XMLHttpRequest.DONE);
        _init.call(this);
      }.bind(this));
    };
  })(XMLHttpRequest.prototype);

  function FormData() {
    if (!(this instanceof FormData)) {
      throw new TypeError('DOM object constructor cannot be called as a function.');
    }
  }

  (function(proto) {
    proto.append = function append(name, value, filename) {
      // todo
    };
  })(FormData.prototype);

  XMLHttpRequest.XMLHttpRequest = XMLHttpRequest;
  XMLHttpRequest.FormData = FormData;
  module.exports = XMLHttpRequest;
})();
<|endoftext|>


<commit_before>/* global describe, it, xit */
/* jslint node: true, esnext: true */

'use strict';

const chai = require('chai'),
  assert = chai.assert,
  expect = chai.expect,
  should = chai.should(),
  path = require('path'),
  child_process = require('child_process');

describe('cluster_node', function () {
  this.timeout(10000);

  it('simple start', done => {
    const child = child_process.spawn(
      path.join(__dirname, '../bin/cluster_node'), ['--trace', '--config', path.join(__dirname,
        '../config.json')], {
        cwd: path.join(__dirname, '..')
      }, (err, stdout, stderr) => {
        console.log(err);
        done();
      });

    child.stdout.on('data', data => {
      data = `${data}`;
      data = data.substring(0, data.length - 1);

      console.log(data);
      if (data.match(/running/) && data.match(/kronos/)) {
        done();
      }
    });

    child.stderr.on('data', data => {
      data = `${data}`;
      data.trim();
      console.log(`stderr: ${data}`);
    });

    child.on('close', code => {
      console.log(`child process exited with code ${code}`);
    });

    //console.log(`child:`, child);
    setTimeout(() => child.kill('SIGKILL'), 5000);
  });
});
<commit_msg>test: cleanup<commit_after>/* global describe, it, xit */
/* jslint node: true, esnext: true */

'use strict';

const chai = require('chai'),
  assert = chai.assert,
  expect = chai.expect,
  should = chai.should(),
  path = require('path'),
  child_process = require('child_process');

describe('cluster_node', function () {
  this.timeout(10000);

  it('simple start', done => {
    const child = child_process.spawn(
      path.join(__dirname, '../bin/cluster_node'), ['--trace', '--config', path.join(__dirname, '..',
        'config.json')], {
        cwd: path.join(__dirname, '..')
      }, (err, stdout, stderr) => {
        console.error(err);
        done();
      });

    child.stdout.on('data', data => {
      data = `${data}`;
      data = data.substring(0, data.length - 1);

      console.log(data);
      if (data.match(/running/) && data.match(/kronos/)) {
        done();
      }
    });

    child.stderr.on('data', data => {
      data = `${data}`;
      data.trim();
      console.log(`stderr: ${data}`);
    });

    child.on('close', code => {
      console.log(`child process exited with code ${code}`);
    });

    //console.log(`child:`, child);
    setTimeout(() => child.kill('SIGKILL'), 5000);
  });
});
<|endoftext|>


<commit_before>var testShortcut = {
    application: 'testApplication',
    operatingSystem: 'testOperatingSystem',
    keyset: 'testKeyset',
    description: 'testDescription'
}

var indexes = [];

describe('search page', function() {
    it('should find a shortcut by all fields', function() {
        addTestShortcut();
        browser.get('http://localhost:3000/#/partials/search');
        //esablish indexes

        element(by.id('searchType')).all(by.tagName('option'))
            .then(function(options) {
                for (var element in options) {
                    options[element].getText().then(function(value) {
                        indexes.push(value);
                    });
                }
            });

        for (var property in testShortcut) {
            element(by.id('searchCriteria')).clear().sendKeys(testShortcut[property]);
            selectDropdownByNum(element(by.id('searchType')), property);
            element(by.id('search')).click();
            var results = element.all(by.css('.shortcut')).count();
            expect(results).toBeGreaterThan(0);
        }

        deleteLastShortcut();
    });
});

function addTestShortcut() {
    browser.get('http://localhost:3000/#/partials/shortcuts');
    element.all(by.css('.shortcut')).then(function(elements) {
        for (var property in testShortcut) {
            element(by.id(property + 'Field')).sendKeys(testShortcut[property]);
        }
        element(by.id('submitNew')).click();
    });
};

function deleteLastShortcut() {
    browser.get('http://localhost:3000/#/partials/shortcuts');
    element.all(by.css('.deleteLink')).last().click();
}

function selectDropdownByNum(element, searchType) {
    if (searchType) {
        element.all(by.tagName('option'))
            .then(function(options) {
                options[indexes.indexOf(searchType)].click();
            });
    }
};<commit_msg>Improved testing code structure<commit_after>var testShortcut = {
    application: 'testApplication',
    operatingSystem: 'testOperatingSystem',
    keyset: 'testKeyset',
    description: 'testDescription'
}

describe('search page', function() {
    var indexes = [];
    beforeEach(function() {
        addTestShortcut();
        browser.get('http://localhost:3000/#/partials/search');
        indexes = establishIndexes();
    });

    it('should find a shortcut by all fields', function() {
        for (var property in testShortcut) {
            element(by.id('searchCriteria')).clear().sendKeys(testShortcut[property]);
            selectDropdownByNum(element(by.id('searchType')), property, indexes);
            element(by.id('search')).click();
            var results = element.all(by.css('.shortcut')).count();
            expect(results).toBeGreaterThan(0);
        }
    });

    afterEach(function() {
        deleteLastShortcut();
    });
});

//helper functions
function establishIndexes() {
    var indexes = [];
    element(by.id('searchType')).all(by.tagName('option'))
        .then(function(options) {
            for (var element in options) {
                options[element].getText().then(function(value) {
                    indexes.push(value);
                });
            }
        });
    return indexes;
}

function addTestShortcut() {
    browser.get('http://localhost:3000/#/partials/shortcuts');
    element.all(by.css('.shortcut')).then(function(elements) {
        for (var property in testShortcut) {
            element(by.id(property + 'Field')).sendKeys(testShortcut[property]);
        }
        element(by.id('submitNew')).click();
    });
};

function deleteLastShortcut() {
    browser.get('http://localhost:3000/#/partials/shortcuts');
    element.all(by.css('.deleteLink')).last().click();
}

function selectDropdownByNum(element, searchType, indexes) {
    if (searchType) {
        element.all(by.tagName('option'))
            .then(function(options) {
                options[indexes.indexOf(searchType)].click();
            });
    }
};<|endoftext|>


<commit_before>'use strict';
// gulp
var gulp = require('gulp');
var paths = gulp.paths;
// plugins
var $ = require('gulp-load-plugins')();

// all linting tasks
gulp.task('linting', ['eslint', 'jsonlint']);
gulp.task('linting-throw', ['eslint', 'jsonlint-throw']);

// check for eslint errors
var eslint = function (fail) {
  return function () {
    return gulp.src(paths.jsFiles.concat(paths.karma).concat(paths.protractor))
      .pipe($.eslint())
      .pipe($.eslint.format())
      .pipe($.if(fail, $.eslint.failOnError()));
  }
};
gulp.task('eslint', eslint());
gulp.task('eslint-throw', eslint(true));

// check for jsonlint errors
var jsonlint = function (fail) {
  var failReporter = function (file) {
    throw new Error(file.path + '\n' + file.jsonlint.message);
  };
  return function () {
    return gulp.src(paths.jsonFiles)
      .pipe($.jsonlint())
      .pipe($.jsonlint.reporter(fail ? failReporter : undefined));
  };
};
gulp.task('jsonlint', jsonlint());
gulp.task('jsonlint-throw', jsonlint(true));
<commit_msg>fixes #252: linting-throw not working as expected<commit_after>'use strict';
// gulp
var gulp = require('gulp');
var paths = gulp.paths;
// plugins
var $ = require('gulp-load-plugins')();

// all linting tasks
gulp.task('linting', ['eslint', 'jsonlint']);
gulp.task('linting-throw', ['eslint-throw', 'jsonlint-throw']);

// check for eslint errors
var eslint = function (fail) {
  return function () {
    return gulp.src(paths.jsFiles.concat(paths.karma).concat(paths.protractor))
      .pipe($.eslint())
      .pipe($.eslint.format())
      .pipe($.if(fail, $.eslint.failOnError()));
  }
};
gulp.task('eslint', eslint());
gulp.task('eslint-throw', eslint(true));

// check for jsonlint errors
var jsonlint = function (fail) {
  var failReporter = function (file) {
    throw new Error(file.path + '\n' + file.jsonlint.message);
  };
  return function () {
    return gulp.src(paths.jsonFiles)
      .pipe($.jsonlint())
      .pipe($.jsonlint.reporter(fail ? failReporter : undefined));
  };
};
gulp.task('jsonlint', jsonlint());
gulp.task('jsonlint-throw', jsonlint(true));
<|endoftext|>


<commit_before>//NOT OFFICIAL PART OF SPEEDTEST This is Beta Assets. Anything Js, and is part of the beta -
//will be here. Everything essential to proper working will remain in the Beta.js file.
var testStatus=0,dlStatus="",ulStatus="",pingStatus="";
var settings={time_ul:15,time_dl:15,count_ping:35,url_dl:"garbage.dat",url_ul:"empty.dat",url_ping:"empty.dat"};
var xhr=null;
function ulTest(done){
    var firstTick=true,startT=new Date().getTime(), prevT=new Date().getTime(),prevLoaded=0,speed=0.0;
    xhr=new XMLHttpRequest();
    xhr.upload.onprogress=function(event){
        var instspd=event.loaded<=0?speed:((event.loaded-prevLoaded)/((new Date().getTime()-prevT)/1000.0));
        if(isNaN(instspd)||!isFinite(instspd)) return;
        if(firstTick){
            firstTick=false;
        }else{
            speed=instspd<speed?(speed*0.4+instspd*0.6):(speed*0.8+instspd*0.2);
        }
        prevLoaded=event.loaded;
        prevT=new Date().getTime();
        ulStatus=((speed*8)/1048576.0).toFixed(2);
        if(((prevT-startT)/1000.0)>settings.time_ul){try{xhr.abort();}catch(e){} xhr=null; done();}
    }.bind(this);
    xhr.onload=function(){
		prevT=new Date().getTime(); prevLoaded=0; fistTick=true;
        xhr.open("POST",settings.url_ul+"?r="+Math.random(),true);
		xhr.send(r);
    }.bind(this);
    xhr.onerror=function(){
        ulStatus="Fail";
		xhr=null;
        done();
    }.bind(this);
    xhr.open("POST",settings.url_ul+"?r="+Math.random(),true);
	xhr.setRequestHeader('Content-Encoding','identity');
	var r=new ArrayBuffer(10485760);
	try{var w=new Float32Array(r);for(var i=0;i<w.length;i++)w[i]=Math.random();}catch(e){}
    xhr.send(r);
}
<commit_msg>Update assets.js<commit_after>//NOT OFFICIAL PART OF SPEEDTEST This is Beta Assets. Anything Js, and is part of the beta -
//will be here. Everything essential to proper working will remain in the Beta.js file.
<|endoftext|>


<commit_before>import { extend } from 'flarum/extend';
import LinkButton from 'flarum/components/LinkButton';
import IndexPage from 'flarum/components/IndexPage';
import DiscussionListState from 'flarum/states/DiscussionListState';

export default function addSubscriptionFilter() {
  extend(IndexPage.prototype, 'navItems', function(items) {
    if (app.session.user) {
      const params = app.search.stickyParams();

      items.add('following', LinkButton.component({
        href: app.route('following', params),
        icon: 'fas fa-star'
      }, app.translator.trans('flarum-subscriptions.forum.index.following_link')), 50);
    }
  });

  extend(IndexPage.prototype, 'setTitle', function () {
    if (app.current.get('routeName') === 'following') {
      app.setTitle(app.translator.trans('flarum-subscriptions.forum.following.meta_title_text'));
    }
  });

  extend(DiscussionListState.prototype, 'requestParams', function(params) {
    if (app.current.get('routeName') === 'following') {
      params.filter.q = (params.filter.q || '') + ' is:following';
    }
  });
}
<commit_msg>Add an `onFollowing` param to GlobalSearchState (#38)<commit_after>import { extend } from 'flarum/extend';
import LinkButton from 'flarum/components/LinkButton';
import IndexPage from 'flarum/components/IndexPage';
import DiscussionListState from 'flarum/states/DiscussionListState';
import GlobalSearchState from 'flarum/states/GlobalSearchState';

export default function addSubscriptionFilter() {
  extend(IndexPage.prototype, 'navItems', function(items) {
    if (app.session.user) {
      const params = app.search.stickyParams();

      items.add('following', LinkButton.component({
        href: app.route('following', params),
        icon: 'fas fa-star'
      }, app.translator.trans('flarum-subscriptions.forum.index.following_link')), 50);
    }
  });

  extend(IndexPage.prototype, 'setTitle', function () {
    if (app.current.get('routeName') === 'following') {
      app.setTitle(app.translator.trans('flarum-subscriptions.forum.following.meta_title_text'));
    }
  });

  extend(GlobalSearchState.prototype, 'params', function (params) {
    // We can't set `q` here directly, as that would make the search bar
    // think that text has been entered, and display the "clear" button.
    params.onFollowing = app.current.get('routeName') === 'following';
  });

  extend(DiscussionListState.prototype, 'requestParams', function (params) {
    if (this.params.onFollowing) {
      params.filter.q = (params.filter.q || '') + ' is:following';
    }
  });
}
<|endoftext|>


<commit_before>'use strict'

// ----------------------------------------------------------------------------

const log       = require ('ololog')
    , ansi      = require ('ansicolor').nice
    , chai      = require ('chai')
    , expect    = chai.expect
    , assert    = chai.assert

/*  ------------------------------------------------------------------------ */

module.exports = async (exchange) => {

    if (!(exchange.has.watchBalance)) {
        log (exchange.id.green, 'does not have watchBalance')
        return
    }

    log ('watching balance...')

    let balance = await exchange.watchBalance ()

    let currencies = [
        'USD',
        'CNY',
        'EUR',
        'BTC',
        'ETH',
        'JPY',
        'LTC',
        'DASH',
        'DOGE',
        'UAH',
        'RUB',
        'XRP',
    ]

    assert (typeof balance['total'] === 'object')
    assert (typeof balance['free'] === 'object')
    assert (typeof balance['used'] === 'object')

    for (let currency of Object.keys (balance['total'])) {
        let total = balance['total'][currency]
        let free = balance['free'][currency]
        let used = balance['used'][currency]
        if (total !== undefined && free !== undefined && used !== undefined) {
            assert (total === free + used, 'free and used do not sum to total ' + exchange.id)
        }
    }

    let result = currencies
        .filter (currency => (currency in balance) &&
            (balance[currency]['total'] !== undefined))

    if (result.length > 0) {
        result = result.map (currency => currency + ': ' + balance[currency]['total'])
        if (exchange.currencies.length > result.length)
            result = result.join (', ') + ' + more...'
        else
            result = result.join (', ')

    } else {

        result = 'zero balance'
    }

    log (result)

    return balance
}
<commit_msg>test.watchBalance.js<commit_after>'use strict'

// ----------------------------------------------------------------------------

const log = require ('ololog')

/*  ------------------------------------------------------------------------ */

module.exports = async (exchange) => {

    const method = 'watchBalance'

    if (!exchange.has[method]) {
        log (exchange.id, 'does not support', method + '() method')
        return
    }

    log ('watching balance...')

    let balance = await exchange[method] ()

    let currencies = [
        'USD',
        'CNY',
        'EUR',
        'BTC',
        'ETH',
        'JPY',
        'LTC',
        'DASH',
        'DOGE',
        'UAH',
        'RUB',
        'XRP',
    ]

    assert (typeof balance['total'] === 'object')
    assert (typeof balance['free'] === 'object')
    assert (typeof balance['used'] === 'object')

    for (let currency of Object.keys (balance['total'])) {
        let total = balance['total'][currency]
        let free = balance['free'][currency]
        let used = balance['used'][currency]
        if (total !== undefined && free !== undefined && used !== undefined) {
            assert (total === free + used, 'free and used do not sum to total ' + exchange.id)
        }
    }

    let result = currencies
        .filter (currency => (currency in balance) &&
            (balance[currency]['total'] !== undefined))

    if (result.length > 0) {
        result = result.map (currency => currency + ': ' + balance[currency]['total'])
        if (exchange.currencies.length > result.length)
            result = result.join (', ') + ' + more...'
        else
            result = result.join (', ')

    } else {

        result = 'zero balance'
    }

    log (result)

    return balance
}
<|endoftext|>


<commit_before>'use strict'

const express = require('express');
const router = express.Router();
const sampleData = require('../sample-data/rc2.json');
const multer = require('multer');
const upload = multer();

function readFile(filename) {
  return JSON.parse(filename);
}

// POST /graph/burndown
// Analyse the received raincatchDump.json & return a json dataset to feed a sprint burndown chart
router.post('/burndown', function (req, res) {
  //res.send('You have just hit the route: /graph/burndown');
  let data = require('../sample-data/rc2.json');
  let sprintTickets = data.map(function (obj) {

  });

  res.json(sampleData);
  // TODO overview - accept & validate name of sprint & return json dataset to populate a burndown chart returned
  // TODO retrieve date range for sprint
  // TODO retrieve all issues that correspond to dates in sprint
  // TODO map all issues by date and storypoint value
  // TODO take account of any issues that drop in & out of sprint
  // TODO validate name of sprint
});

// POST /graph/sprintReport
// Analyse the received raincatchDump.json & return a json dataset to feed a sprint report
router.post('/sprintReport', function (req, res) {
  res.send('You have just hit the route: /graph/sprintReport');
  // TODO overview - accept & validate name of a sprint & return json dataset to populate a JIRA sprint reports
  // TODO return same data as for /burndown along with data table of issues in burndown
});

// POST /graph/velocity
// Analyse the received raincatchDump.json & return a json dataset to feed a sprint velocity chart
router.post('/velocity', function (req, res) {
  res.send('You have just hit the route: /graph/velocity');
  // TODO overview - accept a team & return a json dataset to populate a JIRA velocity chart
  // TODO map all sprints that correspond to the team/ board in question
  // TODO map all sprints by total storypoints & completed storypoints; order by date of sprint
});

// POST /graph/averageAge
// Analyse the received raincatchDump.json & return a json dataset to feed a sprint average age chart
router.post('/averageAge', function (req, res) {
  res.send('You have just hit the route: /graph/averageAge');
  // TODO overview - accept a date range, and return a json dataset to populate a JIRA average-age report
  // TODO retrieve all open issues that correspond to date range
  // TODO for each date in query range map that date to the issues that were open on that date
  // TODO for each date calculate the age of each issue, sum them all, and divide by the total number of issues on that date
  // TODO return a json dataset where each date in query range will be mapped to the average age of all open issues on that date
});

// POST /graph/createdResolved
// Analyse the received raincatchDump.json & return a json dataset to feed a sprint created vs resolved chart
router.post('/createdResolved', upload.fields([]), function (req, res) {
  //res.send('You have just hit the route: /graph/createdResolved');
  let data = require('../sample-data/rc2.json');

  const startDate = request.body.start;
  const endDate = request.body.end;

  let sprints = data;

  let sprintTickets = data.map(function (obj) {

  });

  res.send('start:  ' + startDate + '\nend: ' + endDate);
  // TODO overview - accept a date range, and produce a dataset that populate a JIRA created-vs-resolved report
  // TODO retrieve all issues which have a created or a resolved date that corresponds to the query date range
  // TODO return a json dataset that maps each date in the query range to the number of issues created that day, and also the number of issues resolved that day
});

module.exports = router;
<commit_msg>implements dataset handlers in graph routes<commit_after>'use strict'

const express = require('express');
const router = express.Router();
const sampleData = require('../sample-data/rc2.json');
var multer = require('multer');
var upload = multer();
const utils = require('../utils/data.js');
const burndown = require('../utils/burndown');
const velocity = require('../utils/velocity');
const createdresolved = require('../utils/createdresolved');
const averageage = require('../utils/averageage');

router.post('/issue', upload.array(), function (req, res) {
  /*var issue = sampleData.filter(issue => {
    issue.id === request.body.id;
  });
  console.log(issue);*/
  //console.log('request: ' + request);
  console.log('req: ' + req);
  res.json(req.body);
});

// POST /graph/burndown
// Analyse the received raincatchDump.json & return a json dataset to feed a sprint burndown chart
router.post('/burndown', upload.array(), function (req, res) {
  res.json(burndown.burndownReportData(req.body.sprint));
});

// POST /graph/sprintReport
// Analyse the received raincatchDump.json & return a json dataset to feed a sprint report
router.post('/sprintReport', upload.array(), function (req, res) {
  res.json(burndown.burndownReportData(req.body.sprint));
});

// POST /graph/velocity
// Analyse the received raincatchDump.json & return a json dataset to feed a sprint velocity chart
router.post('/velocity', function (req, res) {
  res.json(velocity.velocity());
});

// POST /graph/averageAge
// Analyse the received raincatchDump.json & return a json dataset to feed a sprint average age chart
router.post('/averageAge', upload.array(), function (req, res) {
  /*console.log(req.body.start);
  console.log(req.body.end);
  req.body.start = '2017-01-01';
  req.body.end = '2017-03-31';*/
  var start = req.body.start;
  var end = req.body.end;
  res.json(averageage.averageAge(start, end));
  //res.json(averageage.averageAge('2017-01-01', '2017-03-31'));
});

// POST /graph/createdResolved
// Analyse the received raincatchDump.json & return a json dataset to feed a sprint created vs resolved chart
router.post('/createdResolved', upload.array(), function (req, res) {
  //res.send('You have just hit the route: /graph/createdResolved');
  res.json(createdresolved.createdResolved(req.body.start, req.body.end));
});

module.exports = router;
<|endoftext|>


<commit_before>/*
 * HOMER 5 UI (Xenophon)
 *
 * Copyright (C) 2011-2015 Alexandr Dubovikov <alexandr.dubovikov@gmail.com>
 * Copyright (C) 2011-2015 Lorenzo Mangani <lorenzo.mangani@gmail.com> QXIP B.V.
 * License AGPL-3.0 http://opensource.org/licenses/AGPL-3.0
 *
*/

'use strict';

angular.module('homer.widgets.quicksearch', ['adf.provider'])
  .config(function(dashboardProvider){
    dashboardProvider
      .widget('quicksearch', {
        title: 'Search Form Builder',
        group: 'Search',
        name: 'quicksearch',
        description: 'Display Search Form component',
        templateUrl: 'js/widgets/quicksearch/quicksearch.html',
        controller: 'quicksearchCtrl',
        controllerAs: 'qsearch',
	edit: {
           templateUrl: 'js/widgets/quicksearch/edit.html',
           controller: 'quicksearchEditCtrl'
      	}
      });
  })
  .controller('quicksearchCtrl', [
     '$scope',
     'config',
     '$location',
     homer.modules.core.services.profile,
     '$log',
     homer.modules.core.services.search,
     '$q',
     function($scope, config, $location, userProfile, $log, search, $q){

          var self = this;

          $scope.methodString = "AA";

          /* workaround */
          if(userProfile.profileScope.search && userProfile.profileScope.search instanceof Array)
                userProfile.profileScope.search={};

	  $scope.newObject = userProfile.profileScope.search;
	  $scope.newTransaction = userProfile.profileScope.transaction;
	  $scope.newResult = userProfile.profileScope.result;
	  $scope.newNode = userProfile.profileScope.node;

	  if (!config.fields){
	      config.fields = [
	                {name:"from_user",selection:"From"},
	                {name:"to_user",selection:"To"},
	                {name:"callid",selection:"Call-ID"}
                    ];

              config.searchbutton = true;
          }

	  this.fields = config.fields;

	  $scope.toggleSearchButton = function() {
	      $scope.showSearchButton = !$scope.showSearchButton;
	      config.searchbutton = !config.searchbutton;
	  }

	  $scope.timerange = userProfile.profileScope.timerange;

                /* update if timerange will be changed */
                (function () {
                      $scope.$watch(function () {
                            return userProfile.profileScope.search;
                      }, function (newVal, oldVal) {
                            if ( newVal !== oldVal ) {
                                $scope.newObject = newVal;
                            }
                        });
          }());

          $scope.nullSafe = function ( field ) {
             if ( !$scope.newObject[field] ) {
                   $scope.newObject[field] = "";
             }
          };

	  // process the form
          $scope.processSearchForm = function(t) {

                if($scope.newObject instanceof Array) $scope.newObject={};

                console.log($scope.newObject);
		userProfile.setProfile("search", $scope.newObject);
		userProfile.setProfile("transaction", $scope.newTransaction);
		userProfile.setProfile("result", $scope.newResult);
		userProfile.setProfile("node", $scope.newNode);

                var tres = $scope.newResult['restype'].name;

                if(tres == "pcap") {
                     $scope.processSearchResult(0);
                }
		else if(tres == "text") {
                     $scope.processSearchResult(1);
                }
                else if(tres == "cloud") {
                     $scope.processSearchResult(2);
                }
		else $location.path('/result');
	  };

	  $scope.clearSearchForm = function(t) {

	        /* should be {} */
	        /*
	        userProfile.profileScope.transaction = [$scope.type_transaction[0], $scope.type_transaction[1]];
	        userProfile.profileScope.result = [$scope.type_result[0]];
	        $scope.newTransaction = [$scope.type_transaction[0], $scope.type_transaction[1]];
	        $scope.newResult = [$scope.type_result[0]];
	        $scope.newNode = [$scope.db_node[0]];
		userProfile.setProfile("transaction", $scope.newTransaction);
		userProfile.setProfile("result", $scope.newResult);
		userProfile.setProfile("node", $scope.newNode);
		*/

		userProfile.profileScope.search = {};
		userProfile.setProfile("search", $scope.newObject);
	  };

	  $scope.processSearchResult = function(type) {

		  /* save data for next search */
		  var data = {param:{}, timestamp:{}};

                  var transaction = userProfile.getProfile("transaction");
                  var limit = userProfile.getProfile("limit");
                  var timedate = userProfile.getProfile("timerange");
                  var value = userProfile.getProfile("search");
                  var node = userProfile.getProfile("node").dbnode;

                  /* make construct of query */
                  data.param.transaction = {};
                  data.param.limit = limit;
                  data.param.search = value;
                  data.param.node = node;
                  data.timestamp.from = timedate.from.getTime();
		  data.timestamp.to = timedate.to.getTime();

		  angular.forEach(transaction.transaction, function(v, k) {
			data.param.transaction[v.name] = true;
		  });

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

		  search.makePcapTextData(data, type).then( function (msg) {

		              if(type == 0) {
                                  var filename = "HOMER5_"+ts+".pcap";
                                  var content_type = "application/pcap";
                              }
                              else if(type == 1) {
                                    filename = "HOMER5_"+ts+".txt";
                                    content_type = "attachment/text;charset=utf-8";
                              }
                              else if(type == 2) {
                                  if(msg.data.hasOwnProperty("url")) {
				      window.sweetAlert({   title: "Export Done!",   text: "Your PCAP can be accessed here",   html: true });
                                  }
                                  else {
                                     var error = "Please check your settings";
                                      if(msg.data.hasOwnProperty("exceptions")) error = msg.data.exceptions;
                                      window.sweetAlert({   title: "Error", type: "error",  text: "Your PCAP couldn't be uploaded!
"+error,   html: true });
                                  }
                                  return;
                              }
                              var blob = new Blob([msg], {type: content_type});
                              saveAs(blob, filename);
        	  });
	  };

	  $scope.type_transaction = [
 		{ name:'call', value:'CALLS'},
    		{ name:'registration', value:'REGISTRATIONS'},
    		{ name:'rest', value:'OTHER'}
	  ];

	  $scope.type_result = [
 		{ name:'table', value:'TABLE'},
    		{ name:'pcap', value:'PCAP'},
    		{ name:'text', value:'TEXT'},
    		{ name:'cloud', value:'CLOUD'}
	  ];

          $scope.method_list = [ 'INVITE','REGISTER','BYE','CANCEL','OPTIONS','ACK','PRACK','SUBSCRIBE',
                                 'NOTIFY','PUBLISH','INFO','REFER','MESSAGE','UPDATE'
          ];

	  $scope.db_node_selected = [];
	  $scope.db_node = [
 		{ name:'localhost', id:'localhost'}
	  ];

	  search.loadNode().then( function (data) {
	           $scope.db_node = data;
          });

          $scope.filterStringList = function(userInput) {
            var filter = $q.defer();
            var normalisedInput = userInput.toLowerCase();
            var filteredArray = $scope.method_list.filter(function(method) {
              return method.toLowerCase().indexOf(normalisedInput) === 0;
            });
            $scope.newObject.method = userInput;
            filter.resolve(filteredArray);
            return filter.promise;
          };

	  $scope.itemMethodSelected = function(item) {
            console.log('Handle item string selected in controller:', item);
            //$scope.newObject.method = item;
            //self.stringMessage = 'String item selected: ' + item;
          };

	  //$scope.type_result_selected = $scope.type_result[0];
	  $scope.newResult['restype'] =  $scope.type_result[0];
	  $scope.newNode['node'] =  $scope.db_node[0];
 	//$scope.newTransaction = [$scope.type_transaction[0], $scope.type_transaction[1]];

	$scope.type_method_selected = [];
	$scope.type_method = [
 		{ id:1, value:'INVITE', checked: false },
    		{ id:2, value:'REGISTER', checked: false },
    		{ id:3, value:'BYE', checked: false },
    		{ id:4, value:'CANCEL', checked: false },
    		{ id:5, value:'OPTIONS', checked: false },
    		{ id:6, value:'ACK', checked: false },
    		{ id:7, value:'PRACK', checked: false },
    		{ id:8, value:'SUBSCRIBE', checked: false },
    		{ id:9, value:'NOTIFY', checked: false },
    		{ id:10, value:'PUBLISH', checked: false },
    		{ id:11, value:'INFO', checked: false },
    		{ id:12, value:'REFER', checked: false },
    		{ id:13, value:'MESSAGE', checked: false },
    		{ id:14, value:'UPDATE', checked: false },
    		{ id:15, value:'1xx', checked: false },
    		{ id:16, value:'2xx', checked: false },
    		{ id:17, value:'3xx', checked: false },
    		{ id:18, value:'4xx', checked: false },
    		{ id:19, value:'5xx', checked: false },
    		{ id:20, value:'6xx', checked: false },
    		{ id:21, value:'', checked: false }
	];

   }])
  .controller('quicksearchEditCtrl', function($scope){

	  var counter = 0;
	  function getFields(){
	      if (!$scope.config.fields){
	        $scope.config.fields = [];
	      }

	      return $scope.config.fields;
	   }

	   $scope.addField = function(){
		getFields().push({ name: "default"+counter} );
	   };

	   $scope.removeField = function(index){
		getFields().splice(index, 1);
	   };

	   $scope.headers = [

                   {name:'from_user', selection:'From User'},
                   {name:'from_domain', selection:'From Domain'},
                   {name:'to_user', selection:'To User'},
                   {name:'to_domain', selection:'To Domain'},
                   {name:'ruri_user', selection:'RURI User'},
                   {name:'ruri_domain', selection:'RURI Domain'},
                   {name:'callid', selection:'Call-ID'},
                   {name:'callid_aleg', selection:'B2B CID'},
                   {name:'custom_field1', selection:'Custom F1'},
                   {name:'custom_field2', selection:'Custom F2'},
                   {name:'custom_field3', selection:'Custom F3'},
                   {name:'contact_user', selection:'Contact User'},
                   {name:'pid_user', selection:'PID User'},
                   {name:'auth_user', selection:'Auth User'},
                   {name:'user_agent', selection:'User-Agent'},
                   {name:'method', selection:'Method'},
                   {name:'cseq', selection:'CSeq'},
                   {name:'reason', selection:'Reason'},
                   {name:'msg', selection:'Message'},
                   {name:'diversion', selection:'Diversion'},
                   {name:'via_1', selection:'VIA'},
                   {name:'source_ip', selection:'Source IP'},
                   {name:'destination_ip', selection:'Dest. IP'},
                   {name:'source_port', selection:'Source Port'},
                   {name:'destination_port', selection:'Dest. Port'},
                   {name:'node', selection:'Node'},
                   {name:'uniq', selection:'Unique'},
                   {name:'orand', selection:'Logic OR'},
                   {name:'proto', selection:'Protocol'},
                   {name:'family', selection:'Family'},
                   {name:'limit', selection:'Limit Query'},
                   {name:'transaction', selection:'Transaction'},
                   //{name:'methodtype', selection:'Methodtype'},
                   {name:'dbnode', selection:'DB Node'},
                   {name:'b2b', selection:'B2B ext'},
                   {name:'restype', selection:'Result Type'}
            ];
  })
  .directive('ngEnter', function() {
   return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if(event.which === 13) {
                scope.$apply(function (){
                    scope.$eval(attrs.ngEnter);
                });

                event.preventDefault();
            }
        });
    };
  })
  .directive('fieldDisplay', function($compile) {
  return {
    scope: {
      fieldDisplay: "=", //import referenced model to our directives scope
      fieldName: "=", //import referenced model to our directives scope
      fieldHeaders: "="
    },
    templateUrl: 'js/widgets/quicksearch/template.html',
    link: function(scope, elem, attr, ctrl) {

      scope.selectedItem = {name: scope.fieldName, selection: scope.fieldDisplay};

      scope.$watch('selectedItem', function(val) {
           scope.fieldDisplay = val.selection;
           scope.fieldName = val.name;
      }, true);

    }
  }

});

<commit_msg>fixed msg.data<commit_after>/*
 * HOMER 5 UI (Xenophon)
 *
 * Copyright (C) 2011-2015 Alexandr Dubovikov <alexandr.dubovikov@gmail.com>
 * Copyright (C) 2011-2015 Lorenzo Mangani <lorenzo.mangani@gmail.com> QXIP B.V.
 * License AGPL-3.0 http://opensource.org/licenses/AGPL-3.0
 *
*/

'use strict';

angular.module('homer.widgets.quicksearch', ['adf.provider'])
  .config(function(dashboardProvider){
    dashboardProvider
      .widget('quicksearch', {
        title: 'Search Form Builder',
        group: 'Search',
        name: 'quicksearch',
        description: 'Display Search Form component',
        templateUrl: 'js/widgets/quicksearch/quicksearch.html',
        controller: 'quicksearchCtrl',
        controllerAs: 'qsearch',
	edit: {
           templateUrl: 'js/widgets/quicksearch/edit.html',
           controller: 'quicksearchEditCtrl'
      	}
      });
  })
  .controller('quicksearchCtrl', [
     '$scope',
     'config',
     '$location',
     homer.modules.core.services.profile,
     '$log',
     homer.modules.core.services.search,
     '$q',
     function($scope, config, $location, userProfile, $log, search, $q){

          var self = this;

          $scope.methodString = "AA";

          /* workaround */
          if(userProfile.profileScope.search && userProfile.profileScope.search instanceof Array)
                userProfile.profileScope.search={};

	  $scope.newObject = userProfile.profileScope.search;
	  $scope.newTransaction = userProfile.profileScope.transaction;
	  $scope.newResult = userProfile.profileScope.result;
	  $scope.newNode = userProfile.profileScope.node;

	  if (!config.fields){
	      config.fields = [
	                {name:"from_user",selection:"From"},
	                {name:"to_user",selection:"To"},
	                {name:"callid",selection:"Call-ID"}
                    ];

              config.searchbutton = true;
          }

	  this.fields = config.fields;

	  $scope.toggleSearchButton = function() {
	      $scope.showSearchButton = !$scope.showSearchButton;
	      config.searchbutton = !config.searchbutton;
	  }

	  $scope.timerange = userProfile.profileScope.timerange;

                /* update if timerange will be changed */
                (function () {
                      $scope.$watch(function () {
                            return userProfile.profileScope.search;
                      }, function (newVal, oldVal) {
                            if ( newVal !== oldVal ) {
                                $scope.newObject = newVal;
                            }
                        });
          }());

          $scope.nullSafe = function ( field ) {
             if ( !$scope.newObject[field] ) {
                   $scope.newObject[field] = "";
             }
          };

	  // process the form
          $scope.processSearchForm = function(t) {

                if($scope.newObject instanceof Array) $scope.newObject={};

                console.log($scope.newObject);
		userProfile.setProfile("search", $scope.newObject);
		userProfile.setProfile("transaction", $scope.newTransaction);
		userProfile.setProfile("result", $scope.newResult);
		userProfile.setProfile("node", $scope.newNode);

                var tres = $scope.newResult['restype'].name;

                if(tres == "pcap") {
                     $scope.processSearchResult(0);
                }
		else if(tres == "text") {
                     $scope.processSearchResult(1);
                }
                else if(tres == "cloud") {
                     $scope.processSearchResult(2);
                }
		else $location.path('/result');
	  };

	  $scope.clearSearchForm = function(t) {

	        /* should be {} */
	        /*
	        userProfile.profileScope.transaction = [$scope.type_transaction[0], $scope.type_transaction[1]];
	        userProfile.profileScope.result = [$scope.type_result[0]];
	        $scope.newTransaction = [$scope.type_transaction[0], $scope.type_transaction[1]];
	        $scope.newResult = [$scope.type_result[0]];
	        $scope.newNode = [$scope.db_node[0]];
		userProfile.setProfile("transaction", $scope.newTransaction);
		userProfile.setProfile("result", $scope.newResult);
		userProfile.setProfile("node", $scope.newNode);
		*/

		userProfile.profileScope.search = {};
		userProfile.setProfile("search", $scope.newObject);
	  };

	  $scope.processSearchResult = function(type) {

		  /* save data for next search */
		  var data = {param:{}, timestamp:{}};

                  var transaction = userProfile.getProfile("transaction");
                  var limit = userProfile.getProfile("limit");
                  var timedate = userProfile.getProfile("timerange");
                  var value = userProfile.getProfile("search");
                  var node = userProfile.getProfile("node").dbnode;

                  /* make construct of query */
                  data.param.transaction = {};
                  data.param.limit = limit;
                  data.param.search = value;
                  data.param.node = node;
                  data.timestamp.from = timedate.from.getTime();
		  data.timestamp.to = timedate.to.getTime();

		  angular.forEach(transaction.transaction, function(v, k) {
			data.param.transaction[v.name] = true;
		  });

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

		  search.makePcapTextData(data, type).then( function (msg) {

		              if(type == 0) {
                                  var filename = "HOMER5_"+ts+".pcap";
                                  var content_type = "application/pcap";
                              }
                              else if(type == 1) {
                                    filename = "HOMER5_"+ts+".txt";
                                    content_type = "attachment/text;charset=utf-8";
                              }
                              else if(type == 2) {
                                  if(msg.data && msg.data.hasOwnProperty("url")) {
				      window.sweetAlert({   title: "Export Done!",   text: "Your PCAP can be accessed here",   html: true });
                                  }
                                  else {
                                     var error = "Please check your settings";
                                      if(msg.data && msg.data.hasOwnProperty("exceptions")) error = msg.data.exceptions;
                                      window.sweetAlert({   title: "Error", type: "error",  text: "Your PCAP couldn't be uploaded!
"+error,   html: true });
                                  }
                                  return;
                              }
                              var blob = new Blob([msg], {type: content_type});
                              saveAs(blob, filename);
        	  });
	  };

	  $scope.type_transaction = [
 		{ name:'call', value:'CALLS'},
    		{ name:'registration', value:'REGISTRATIONS'},
    		{ name:'rest', value:'OTHER'}
	  ];

	  $scope.type_result = [
 		{ name:'table', value:'TABLE'},
    		{ name:'pcap', value:'PCAP'},
    		{ name:'text', value:'TEXT'},
    		{ name:'cloud', value:'CLOUD'}
	  ];

          $scope.method_list = [ 'INVITE','REGISTER','BYE','CANCEL','OPTIONS','ACK','PRACK','SUBSCRIBE',
                                 'NOTIFY','PUBLISH','INFO','REFER','MESSAGE','UPDATE'
          ];

	  $scope.db_node_selected = [];
	  $scope.db_node = [
 		{ name:'localhost', id:'localhost'}
	  ];

	  search.loadNode().then( function (data) {
	           $scope.db_node = data;
          });

          $scope.filterStringList = function(userInput) {
            var filter = $q.defer();
            var normalisedInput = userInput.toLowerCase();
            var filteredArray = $scope.method_list.filter(function(method) {
              return method.toLowerCase().indexOf(normalisedInput) === 0;
            });
            $scope.newObject.method = userInput;
            filter.resolve(filteredArray);
            return filter.promise;
          };

	  $scope.itemMethodSelected = function(item) {
            console.log('Handle item string selected in controller:', item);
            //$scope.newObject.method = item;
            //self.stringMessage = 'String item selected: ' + item;
          };

	  //$scope.type_result_selected = $scope.type_result[0];
	  $scope.newResult['restype'] =  $scope.type_result[0];
	  $scope.newNode['node'] =  $scope.db_node[0];
 	//$scope.newTransaction = [$scope.type_transaction[0], $scope.type_transaction[1]];

	$scope.type_method_selected = [];
	$scope.type_method = [
 		{ id:1, value:'INVITE', checked: false },
    		{ id:2, value:'REGISTER', checked: false },
    		{ id:3, value:'BYE', checked: false },
    		{ id:4, value:'CANCEL', checked: false },
    		{ id:5, value:'OPTIONS', checked: false },
    		{ id:6, value:'ACK', checked: false },
    		{ id:7, value:'PRACK', checked: false },
    		{ id:8, value:'SUBSCRIBE', checked: false },
    		{ id:9, value:'NOTIFY', checked: false },
    		{ id:10, value:'PUBLISH', checked: false },
    		{ id:11, value:'INFO', checked: false },
    		{ id:12, value:'REFER', checked: false },
    		{ id:13, value:'MESSAGE', checked: false },
    		{ id:14, value:'UPDATE', checked: false },
    		{ id:15, value:'1xx', checked: false },
    		{ id:16, value:'2xx', checked: false },
    		{ id:17, value:'3xx', checked: false },
    		{ id:18, value:'4xx', checked: false },
    		{ id:19, value:'5xx', checked: false },
    		{ id:20, value:'6xx', checked: false },
    		{ id:21, value:'', checked: false }
	];

   }])
  .controller('quicksearchEditCtrl', function($scope){

	  var counter = 0;
	  function getFields(){
	      if (!$scope.config.fields){
	        $scope.config.fields = [];
	      }

	      return $scope.config.fields;
	   }

	   $scope.addField = function(){
		getFields().push({ name: "default"+counter} );
	   };

	   $scope.removeField = function(index){
		getFields().splice(index, 1);
	   };

	   $scope.headers = [

                   {name:'from_user', selection:'From User'},
                   {name:'from_domain', selection:'From Domain'},
                   {name:'to_user', selection:'To User'},
                   {name:'to_domain', selection:'To Domain'},
                   {name:'ruri_user', selection:'RURI User'},
                   {name:'ruri_domain', selection:'RURI Domain'},
                   {name:'callid', selection:'Call-ID'},
                   {name:'callid_aleg', selection:'B2B CID'},
                   {name:'custom_field1', selection:'Custom F1'},
                   {name:'custom_field2', selection:'Custom F2'},
                   {name:'custom_field3', selection:'Custom F3'},
                   {name:'contact_user', selection:'Contact User'},
                   {name:'pid_user', selection:'PID User'},
                   {name:'auth_user', selection:'Auth User'},
                   {name:'user_agent', selection:'User-Agent'},
                   {name:'method', selection:'Method'},
                   {name:'cseq', selection:'CSeq'},
                   {name:'reason', selection:'Reason'},
                   {name:'msg', selection:'Message'},
                   {name:'diversion', selection:'Diversion'},
                   {name:'via_1', selection:'VIA'},
                   {name:'source_ip', selection:'Source IP'},
                   {name:'destination_ip', selection:'Dest. IP'},
                   {name:'source_port', selection:'Source Port'},
                   {name:'destination_port', selection:'Dest. Port'},
                   {name:'node', selection:'Node'},
                   {name:'uniq', selection:'Unique'},
                   {name:'orand', selection:'Logic OR'},
                   {name:'proto', selection:'Protocol'},
                   {name:'family', selection:'Family'},
                   {name:'limit', selection:'Limit Query'},
                   {name:'transaction', selection:'Transaction'},
                   //{name:'methodtype', selection:'Methodtype'},
                   {name:'dbnode', selection:'DB Node'},
                   {name:'b2b', selection:'B2B ext'},
                   {name:'restype', selection:'Result Type'}
            ];
  })
  .directive('ngEnter', function() {
   return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if(event.which === 13) {
                scope.$apply(function (){
                    scope.$eval(attrs.ngEnter);
                });

                event.preventDefault();
            }
        });
    };
  })
  .directive('fieldDisplay', function($compile) {
  return {
    scope: {
      fieldDisplay: "=", //import referenced model to our directives scope
      fieldName: "=", //import referenced model to our directives scope
      fieldHeaders: "="
    },
    templateUrl: 'js/widgets/quicksearch/template.html',
    link: function(scope, elem, attr, ctrl) {

      scope.selectedItem = {name: scope.fieldName, selection: scope.fieldDisplay};

      scope.$watch('selectedItem', function(val) {
           scope.fieldDisplay = val.selection;
           scope.fieldName = val.name;
      }, true);

    }
  }

});

<|endoftext|>