<commit_before>// A very simple promise implementation without external dependencies.
// MIT license. (c) Ubimix (c) Mikhail Kotelnikov
var P = {
    defer : Deferred,
    then : function(onResolve, onReject) {
        var deferred = P.defer();
        deferred.resolve();
        return deferred.then(onResolve, onReject);
    },
    reject : function(value) {
        var deferred = P.defer();
        deferred.reject(value);
        return deferred;
    },
    resolve : function(value) {
        var deferred = P.defer();
        deferred.resolve(value);
        return deferred;
    }
};
function Deferred() {
    var slots = [];
    var done;
    var that = {};
    that.then = function(onResolve, onReject) {
        var next = new Deferred();
        slots.push({
            onResolve : onResolve,
            onReject : onReject,
            next : next
        });
        if (done) {
            done();
        }
        return next;
    };
    that.resolve = function(result) {
        finish(function(slot) {
            if (slot.onResolve) {
                return slot.onResolve(result);
            } else {
                return result;
            }
        });
    };
    that.reject = function(err) {
        finish(function(slot) {
            if (slot.onReject) {
                return slot.onReject(err);
            } else {
                throw err;
            }
        });
    };
    return that;
    function finish(action) {
        that.resolve = that.reject = function() {
            throw new Error('This promise is already resolved.');
        };
        var scheduled = false;
        done = function() {
            if (scheduled) {
                return;
            }
            scheduled = true;
            Deferred.nextTick(function() {
                scheduled = false;
                var prevSlots = slots;
                slots = [];
                for (var i = 0; i < prevSlots.length; i++) {
                    var slot = prevSlots[i];
                    var next = slot.next;
                    try {
                        result = action(slot);
                        if (result && typeof result.then === 'function') {
                            result.then(next.resolve, next.reject);
                        } else {
                            next.resolve(result);
                        }
                    } catch (err) {
                        next.reject(err);
                    }
                }
            });
        };
        done();
    }
}
// Deferred.nextTick = function(action) {
// action();
// }
Deferred.nextTick = function(action) {
    if (typeof process !== 'undefined' && process.nextTick) {
        Deferred.nextTick = process.nextTick;
    } else {
        Deferred.nextTick = function(action) {
            setTimeout(action, 0);
        };
    }
    Deferred.nextTick(action); // It is not an infinite recursion!
};
P.all = function(list) {
    var deferred = P.defer();
    var len = list ? list.length : 0;
    var results = [];
    function end(error, result) {
        results.push(result);
        if (error) {
            deferred.reject(error);
        } else {
            if (results.length === len) {
                deferred.resolve(results);
            }
        }
    }
    function onResolve(result) {
        end(null, result);
    }
    function onReject(err) {
        end(err, null);
    }
    for (var i = 0; i < len; i++) {
        list[i].then(onResolve, onReject);
    }
    if (len === 0) {
        deferred.resolve(results);
    }
    return deferred;
};
P.nresolver = function(deferred) {
    return function(error, value) {
        if (error) {
            deferred.reject(error);
        } else {
            deferred.resolve(value);
        }
    };
};
P.ninvoke = function(object, name /* ...args */) {
    var args = [];
    for (var i = 2; i < arguments.length; i++) {
        args.push(arguments[i]);
    }
    var deferred = P.defer();
    args.push(P.nresolver(deferred));
    try {
        var f = (typeof name) == 'function' ? name : object[name];
        f.apply(object, args);
    } catch (e) {
        deferred.reject(e);
    }
    return deferred.promise;
};
module.exports = P;
<commit_msg>P.isPromise method was added<commit_after>// A very simple promise implementation without external dependencies.
// MIT license. (c) Ubimix (c) Mikhail Kotelnikov
var P = {
    defer : Deferred,
    then : function(onResolve, onReject) {
        var deferred = P.defer();
        deferred.resolve();
        return deferred.then(onResolve, onReject);
    },
    reject : function(value) {
        var deferred = P.defer();
        deferred.reject(value);
        return deferred;
    },
    resolve : function(value) {
        var deferred = P.defer();
        deferred.resolve(value);
        return deferred;
    }
};
function Deferred() {
    var slots = [];
    var done;
    var that = {};
    that.then = function(onResolve, onReject) {
        var next = new Deferred();
        slots.push({
            onResolve : onResolve,
            onReject : onReject,
            next : next
        });
        if (done) {
            done();
        }
        return next;
    };
    that.resolve = function(result) {
        finish(function(slot) {
            if (slot.onResolve) {
                return slot.onResolve(result);
            } else {
                return result;
            }
        });
    };
    that.reject = function(err) {
        finish(function(slot) {
            if (slot.onReject) {
                return slot.onReject(err);
            } else {
                throw err;
            }
        });
    };
    return that;
    function finish(action) {
        that.resolve = that.reject = function() {
            throw new Error('This promise is already resolved.');
        };
        var scheduled = false;
        done = function() {
            if (scheduled) {
                return;
            }
            scheduled = true;
            Deferred.nextTick(function() {
                scheduled = false;
                var prevSlots = slots;
                slots = [];
                for (var i = 0; i < prevSlots.length; i++) {
                    var slot = prevSlots[i];
                    var next = slot.next;
                    try {
                        result = action(slot);
                        if (Deferred.isThennable(result)) {
                            result.then(next.resolve, next.reject);
                        } else {
                            next.resolve(result);
                        }
                    } catch (err) {
                        next.reject(err);
                    }
                }
            });
        };
        done();
    }
}
Deferred.isThennable = function(result) {
    return result && typeof result.then === 'function';
};
// Deferred.nextTick = function(action) {
// action();
// }
Deferred.nextTick = function(action) {
    if (typeof process !== 'undefined' && process.nextTick) {
        Deferred.nextTick = process.nextTick;
    } else {
        Deferred.nextTick = function(action) {
            setTimeout(action, 0);
        };
    }
    Deferred.nextTick(action); // It is not an infinite recursion!
};
P.isPromise = Deferred.isThennable;
P.all = function(list) {
    var deferred = P.defer();
    var len = list ? list.length : 0;
    var results = [];
    function end(error, result) {
        results.push(result);
        if (error) {
            deferred.reject(error);
        } else {
            if (results.length === len) {
                deferred.resolve(results);
            }
        }
    }
    function onResolve(result) {
        end(null, result);
    }
    function onReject(err) {
        end(err, null);
    }
    for (var i = 0; i < len; i++) {
        list[i].then(onResolve, onReject);
    }
    if (len === 0) {
        deferred.resolve(results);
    }
    return deferred;
};
P.nresolver = function(deferred) {
    return function(error, value) {
        if (error) {
            deferred.reject(error);
        } else {
            deferred.resolve(value);
        }
    };
};
P.ninvoke = function(object, name /* ...args */) {
    var args = [];
    for (var i = 2; i < arguments.length; i++) {
        args.push(arguments[i]);
    }
    var deferred = P.defer();
    args.push(P.nresolver(deferred));
    try {
        var f = (typeof name) == 'function' ? name : object[name];
        f.apply(object, args);
    } catch (e) {
        deferred.reject(e);
    }
    return deferred.promise;
};
module.exports = P;
<|endoftext|>


<commit_before>import adminUsers from './root/admin-users';
import adminContributions from './root/admin-contributions';
import flex from './root/flex';
import insights from './root/insights';
import posts from './root/posts';
import jobs from './root/jobs';
import liveStatistics from './root/live-statistics';
import projectsContributionReport from './root/projects-contribution-report';
import projectsDashboard from './root/projects-dashboard';
import projectsExplore from './root/projects-explore';
import projectsHome from './root/projects-home';
import projectsShow from './root/projects-show';
import projectsContribution from './root/projects-contribution';
import usersShow from './root/users-show';
import usersEdit from './root/users-edit';
import projectsPayment from './root/projects-payment';
import projectsReward from './root/projects-reward';
import publish from './root/publish';
import start from './root/start';
import team from './root/team';
import usersBalanceMain from './root/users-balance-main';
import menu from './root/menu';
import footer from './root/footer';
import FollowFoundFriends from './root/follow-found-friends';
import thankYou from './root/thank-you';
import CheckEmail from './root/check-email';
import projectEditUserAbout from './root/project-edit-user-about';
import projectEditReward from './root/project-edit-reward';
import projectEditUserSettings from './root/project-edit-user-settings';
import projectEditBasic from './root/project-edit-basic';
import projectEditDescription from './root/project-edit-description';
import projectEditBudget from './root/project-edit-budget';
import projectEditVideo from './root/project-edit-video';
import projectEditGoal from './root/project-edit-goal';
import projectEditCard from './root/project-edit-card';
import copyTextInput from './c/copy-text-input';

const c = {
    root: {
        AdminUsers: adminUsers,
        AdminContributions: adminContributions,
        ClipboardCopy: copyTextInput,
        Flex: flex,
        Insights: insights,
        Posts: posts,
        Jobs: jobs,
        LiveStatistics: liveStatistics,
        ProjectsContributionReport: projectsContributionReport,
        ProjectsDashboard: projectsDashboard,
        ProjectsExplore: projectsExplore,
        ProjectsHome: projectsHome,
        ProjectsShow: projectsShow,
        UsersShow: usersShow,
        UsersEdit: usersEdit,
        ProjectsContribution: projectsContribution,
        ProjectsPayment: projectsPayment,
        ProjectsReward: projectsReward,
        ThankYou: thankYou,
        Publish: publish,
        Start: start,
        Team: team,
        UsersBalance: usersBalanceMain,
        Menu: menu,
        Footer: footer,
        FollowFoundFriends,
        CheckEmail,
        projectEditUserAbout,
        projectEditUserSettings,
        projectEditReward,
        projectEditBasic,
        projectEditDescription,
        projectEditBudget,
        projectEditVideo,
        projectEditGoal,
        projectEditCard
    }
};

export default c;
<commit_msg>Remove userBalanceMain from root mapping<commit_after>import adminUsers from './root/admin-users';
import adminContributions from './root/admin-contributions';
import flex from './root/flex';
import insights from './root/insights';
import posts from './root/posts';
import jobs from './root/jobs';
import liveStatistics from './root/live-statistics';
import projectsContributionReport from './root/projects-contribution-report';
import projectsDashboard from './root/projects-dashboard';
import projectsExplore from './root/projects-explore';
import projectsHome from './root/projects-home';
import projectsShow from './root/projects-show';
import projectsContribution from './root/projects-contribution';
import usersShow from './root/users-show';
import usersEdit from './root/users-edit';
import projectsPayment from './root/projects-payment';
import projectsReward from './root/projects-reward';
import publish from './root/publish';
import start from './root/start';
import team from './root/team';
import menu from './root/menu';
import footer from './root/footer';
import FollowFoundFriends from './root/follow-found-friends';
import thankYou from './root/thank-you';
import CheckEmail from './root/check-email';
import projectEditUserAbout from './root/project-edit-user-about';
import projectEditReward from './root/project-edit-reward';
import projectEditUserSettings from './root/project-edit-user-settings';
import projectEditBasic from './root/project-edit-basic';
import projectEditDescription from './root/project-edit-description';
import projectEditBudget from './root/project-edit-budget';
import projectEditVideo from './root/project-edit-video';
import projectEditGoal from './root/project-edit-goal';
import projectEditCard from './root/project-edit-card';
import copyTextInput from './c/copy-text-input';

const c = {
    root: {
        AdminUsers: adminUsers,
        AdminContributions: adminContributions,
        ClipboardCopy: copyTextInput,
        Flex: flex,
        Insights: insights,
        Posts: posts,
        Jobs: jobs,
        LiveStatistics: liveStatistics,
        ProjectsContributionReport: projectsContributionReport,
        ProjectsDashboard: projectsDashboard,
        ProjectsExplore: projectsExplore,
        ProjectsHome: projectsHome,
        ProjectsShow: projectsShow,
        UsersShow: usersShow,
        UsersEdit: usersEdit,
        ProjectsContribution: projectsContribution,
        ProjectsPayment: projectsPayment,
        ProjectsReward: projectsReward,
        ThankYou: thankYou,
        Publish: publish,
        Start: start,
        Team: team,
        Menu: menu,
        Footer: footer,
        FollowFoundFriends,
        CheckEmail,
        projectEditUserAbout,
        projectEditUserSettings,
        projectEditReward,
        projectEditBasic,
        projectEditDescription,
        projectEditBudget,
        projectEditVideo,
        projectEditGoal,
        projectEditCard
    }
};

export default c;
<|endoftext|>


<commit_before>//
// Copyright (c) 2015-2015, John Mettraux, jmettraux@gmail.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

var H = (function() {

  var self = this;

  this.VERSION = '1.0.0';

  var toEltRefine = function(start, elt_or_sel) {

    if ( ! elt_or_sel) { elt_or_sel = start; start = document; }

    if ( ! start) { start = document; }
    if ((typeof start) === 'string') start = document.querySelector(start);

    return [ start, elt_or_sel ];
  };

  var toElt = function(start, elt_or_sel) {

    var se = toEltRefine(start, elt_or_sel); var sta = se[0], sel = se[1];

    return ((typeof sel) === 'string') ?  sta.querySelector(sel) : sel;
  };

  var toElts = function(start, elt_or_sel) {

    var se = toEltRefine(start, elt_or_sel); var sta = se[0], sel = se[1];
    var es = (typeof sel) === 'string' ?  sta.querySelectorAll(sel) : [ sel ];
    var r = []; for (var i = 0, l = es.length; i < l; i++) { r.push(es[i]); };

    return r;
  };

  this.elt = function(start, elt_or_selector) {

    return toElt(start, elt_or_selector);
  };

  this.elts = function(start, selector) {

    return toElts(start, selector);
  }

  this.forEach = function(start, selector, func) {

    if ((typeof selector) === 'function') { func = selector; selector = null; }

    var r = toElts(start, selector);
    r.forEach(func);

    return r;
  };

  this.dim = function(start, elt_or_selector) {

    var e = toElt(start, elt_or_selector);

    if ( ! e) return null;

    return {
      top: e.offsetTop,
      bottom: e.offsetTop + e.offsetHeight,
      left: e.offsetLeft,
      right: e.offsetLeft + e.offsetWidth,
      height: e.offsetHeight,
      width: e.offsetWidth,
    }
  }

  var onOrOff = function(dir, start, elt_or_selector, eventName, eventHandler) {

    if ( ! eventHandler) {
      eventHandler = eventName;
      eventName = elt_or_selector;
      elt_or_selector = start;
      start = document;
    }

    var es = toElts(start, elt_or_selector);
    for (var i = 0; ; i++) {
      var e = es[i]; if ( ! e) break;
      if (dir === 'on') e.addEventListener(eventName, eventHandler);
      else /* off */ e.removeEventListener(eventName, eventHandler);
    }
  };

  this.on = function(start, elt_or_selector, eventName, eventHandler) {
    onOrOff('on', start, elt_or_selector, eventName, eventHandler);
  };

  this.off = function(start, elt_or_selector, eventName, eventHandler) {
    onOrOff('off', start, elt_or_selector, eventName, eventHandler);
  };

  var indexNext = function(sel) {

    var d = sel.indexOf('.'); var s = sel.indexOf('#');
    if (d < 0) return s; if (s < 0) return d;
    return d < s ? d : s;
  };

  this.create = function(sel, atts, text) {

    sel = '%' + sel;
    if ((typeof atts) === 'string') { text = atts; atts = {}; }

    var e = document.createElement('div');

    for (var i = 0; i < sel.length; ) {
      var t = sel.substring(i, i + 1);
      var j = indexNext(sel.substring(i + 1));
      var s = j > -1 ? sel.substring(i + 1, i + 1 + j) : sel.substring(i + 1);
      //console.log([ t, j, s ]);
      if (t === '%') e = document.createElement(s);
      else if (t === '#') e.id = s;
      else if (t === '.') e.classList.add(s);
      if (j < 0) break;
      i = i + 1 + j;
    }

    for (var k in atts) e.setAttribute(k, atts[k]);

    if (text) e.appendChild(document.createTextNode(text));

    return e;
  };

  this.toNode = function(html) {

    var e = document.createElement('div');
    e.innerHTML = html; // :-(

    return e.children[0];
  };

  var defaultOn = function(type, method, uri) {

    return function(res) {
      if (type === 'load') console.log([ method + ' ' + uri, res ]);
      else console.log([ meth + ' ' + uri + ' connection problem', res ]);
    }
  };

  this.request = function(method, uri, data, callbacks) {

    if ( ! callbacks) { callbacks = data; data = null; }
    if ((typeof callbacks) === 'function') callbacks = { onok: callbacks };

    var r = new XMLHttpRequest();
    r.open(method, uri, true);

    if (data) {
      if (data.constructor.toString().match(/FormData/)) {
        //r.setRequestHeader('Content-Type', 'application/form-data');
      }
      else {
        r.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
        data = (typeof data) === 'string' ? data : JSON.stringify(data);
      }
    }

    r.onload = function() {
      var o = { status: r.status, request: r };
      o.data = null; try { o.data = JSON.parse(r.responseText); } catch (ex) {};
      if (callbacks.onok && r.status === 200)
        callbacks.onok(o);
      else
        (callbacks.onload || defaultOn('load', method, uri))(o);
    };
    r.onerror = callbacks.onerror || defaultOn('error', method, uri);

    r.send(data);
  };

  this.upload = function(uri, inputFileElt_s, data, callbacks) {

    //console.log('uploading to ' + uri + ' ...');

    if ( ! callbacks) { callbacks = data; data = {}; }

    var fd = new FormData();

    for (var k in data) fd.append(k, data[k]);

    var isMulti = Array.isArray(inputFileElt_s);
    var elts = isMulti ? inputFileElt_s : [ inputFileElt_s ];

    var fcount = 0;

    elts.forEach(function(elt) {

      var files = elt.files;

      for (var i = 0, l = files.length; i < l; i++) {

        fcount = fcount + 1;

        var f = files[i];

        var l = elt.getAttribute('data-sg-lang');
        var k = 'file-';
        if (l || isMulti) k = k + elt.name + '-';
        if (l) k = k + l + '-';
        k = k + i;

        fd.append(k, f, f.name);
      }
    });

    if (fcount < 1) return 0;

    var onok = callbacks.onok;
    callbacks.onok = function(res) {
      elts.forEach(function(elt) { elt.value = ''; });
      onok(res);
    };

    H.request('POST', uri, fd, callbacks);

    return fcount;
  };

  this.matches = function(elt, sel) {

    if (elt.matches) return elt.matches(sel);
    if (elt.matchesSelector) return elt.matchesSelector(sel);
    if (elt.msMatchesSelector) return elt.msMatchesSelector(sel);

    throw "browser doesn't support elt.matches() or elt.matchesSelector()";
  };

  this.closest = function(start, elt_or_selector, sel) {

    if ( ! sel) {
      sel = elt_or_selector; elt_or_selector = start; start = null;
    }
    var elt = toElt(start, elt_or_selector);

    if (H.matches(elt, sel)) return elt;

    return elt.parentElement ? H.closest(elt.parentElement, sel) : null;
  };

  // adapted from http://upshots.org/javascript/jquery-copy-style-copycss
  //
  this.style = function(start, elt_or_selector) {

    var elt = toElt(start, elt_or_selector);

    var r = {};
    var style = null;

    if (window.getComputedStyle) {

      style = window.getComputedStyle(elt, null);

      for (var i = 0, l = style.length; i < l; i++) {
        var p = style[i];
        var n = p.replace(
          /-([a-za])/g, function(a, b) { return b.toUpperCase(); })
        r[n] = style.getPropertyValue(p);
      }

      return r;
    }

    if (style = elt.currentStyle) {

      for (var p in style) r[p] = style[p];
      return r;
    }

    if (style = elt.style) {

      for (var p in style) {
        var s = style[p];
        if ((typeof s) !== 'function') r[p] = s;
      }

      //return r;
    }

    return r;
  };

  this.hasClass = function(start, elt_or_selector, className) {

    if ( ! className) {
      className = elt_or_selector; elt_or_selector = start; start = null;
    }

    var elt = toElt(start, elt_or_selector);
    if (className[0] === '.') className = className.substring(1);

    try {
      if (elt.classList) return elt.classList.contains(className);
      return (new RegExp('\\b' + className + '\\b')).test(elt.className);
    }
    catch (ex) {
      return false;
    }
  };

  this.removeClass = function(start, elt_or_selector, className) {

    if ( ! className) {
      className = elt_or_selector; elt_or_selector = start; start = null;
    }

    if (className[0] === '.') className = className.substring(1);

    toElts(start, elt_or_selector).forEach(function(e) {
      e.classList.remove(className);
    });
  }

  this.addClass = function(start, elt_or_selector, className) {

    if ( ! className) {
      className = elt_or_selector; elt_or_selector = start; start = null;
    }

    if (className[0] === '.') className = className.substring(1);

    toElts(start, elt_or_selector).forEach(function(e) {
      e.classList.add(className);
    });
  }

  var tog = function(start, elt_or_selector, bool, klass) {

    if (
      (typeof elt_or_selector) === 'boolean' || elt_or_selector === 'toggle'
    ) {
      bool = elt_or_selector; elt_or_selector = start; start = null;
    }

    if (bool === 'toggle') {
      bool = ! self.hasClass(start, elt_or_selector, klass);
    }

    toElts(start, elt_or_selector).forEach(function(e) {
      self[bool ? 'addClass' : 'removeClass'](e, klass);
      return bool;
    });
  };

  this.toggleClass = function(start, elt_or_selector, className) {

    if ( ! className) {
      className = elt_or_selector; elt_or_selector = start; start = null;
    }

    return tog(start, elt_or_selector, 'toggle', className);
  };
  this.toggle = this.toggleClass;

  this.show = function(start, elt_or_selector, bool) {

    tog(start, elt_or_selector, bool, '.show');
  };

  this.hide = function(start, elt_or_selector, bool) {

    tog(start, elt_or_selector, bool, '.hidden');
  };

  this.enable = function(start, elt_or_selector, bool) {

    if (bool === undefined) {
      bool = elt_or_selector; elt_or_selector = start; start = null;
    }

    toElts(start, elt_or_selector).forEach(function(e) {
      if (bool === false || bool === null)
        e.setAttribute('disabled', 'disabled');
      else
        e.removeAttribute('disabled');
    });
  }

  this.disable = function(start, elt_or_selector) {

    self.enable(start, elt_or_selector, false);
  };

  this.cdisable = function(start, elt_or_selector) {

    H.addClass(start, elt_or_selector, '.disabled');
  };

  this.cenable = function(start, elt_or_selector) {

    H.removeClass(start, elt_or_selector, '.disabled');
  };

  this.toCamelCase = function(s) {

    return s.replace(
      /([_-][a-z])/g, function(x) { return x.substring(1).toUpperCase(); });
  };

  this.prepend = function(start, elt_or_selector, child) {

    if ( ! child) {
      child = elt_or_selector; elt_or_selector = start; start = null;
    }

    var elt = toElt(start, elt_or_selector);

    elt.parentNode.insertBefore(child, elt);
  };

  this.trigger = function(start, elt_or_selector, eventName) {

    if ( ! eventName) {
      eventName = elt_or_selector; elt_or_selector = start; start = null;
    }

    var elt = toElt(start, elt_or_selector);

    var ev = document.createEvent('HTMLEvents');
    ev.initEvent(eventName, true, false);

    elt.dispatchEvent(ev);
  };

  this.clean = function(start, elt_or_selector, className) {

    var elt = toElt(start, elt_or_selector);
    if (className) H.forEach(elt, className, function(e) { e.remove(); });
    else while (elt.firstChild) elt.removeChild(elt.firstChild);

    return elt;
  };

  this.onDocumentReady = function(f) {

    if (document.readyState != 'loading') f();
    else document.addEventListener('DOMContentLoaded', f);
  };

  //
  // over.

  return this;

}).apply({});

<commit_msg>compact H.elt() and H.elts()<commit_after>//
// Copyright (c) 2015-2015, John Mettraux, jmettraux@gmail.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

var H = (function() {

  var self = this;

  this.VERSION = '1.0.0';

  var toEltRefine = function(start, sel) {

    if ( ! sel) { sel = start; start = document; }

    if ( ! start) { start = document; }
    if ((typeof start) === 'string') start = document.querySelector(start);

    return [ start, sel ];
  };

  var toElt = function(start, sel) {

    var se = toEltRefine(start, sel); var sta = se[0], sel = se[1];

    return ((typeof sel) === 'string') ?  sta.querySelector(sel) : sel;
  };

  var toElts = function(start, sel) {

    var se = toEltRefine(start, sel); var sta = se[0], sel = se[1];
    var es = (typeof sel) === 'string' ?  sta.querySelectorAll(sel) : [ sel ];
    var r = []; for (var i = 0, l = es.length; i < l; i++) { r.push(es[i]); };

    return r;
  };

  this.elt = function(start, selector) { return toElt(start, selector); };
  this.elts = function(start, selector) { return toElts(start, selector); };

  this.forEach = function(start, selector, func) {

    if ((typeof selector) === 'function') { func = selector; selector = null; }

    var r = toElts(start, selector);
    r.forEach(func);

    return r;
  };

  this.dim = function(start, selector) {

    var e = toElt(start, selector);

    if ( ! e) return null;

    return {
      top: e.offsetTop,
      bottom: e.offsetTop + e.offsetHeight,
      left: e.offsetLeft,
      right: e.offsetLeft + e.offsetWidth,
      height: e.offsetHeight,
      width: e.offsetWidth,
    }
  }

  var onOrOff = function(dir, start, elt_or_selector, eventName, eventHandler) {

    if ( ! eventHandler) {
      eventHandler = eventName;
      eventName = elt_or_selector;
      elt_or_selector = start;
      start = document;
    }

    var es = toElts(start, elt_or_selector);
    for (var i = 0; ; i++) {
      var e = es[i]; if ( ! e) break;
      if (dir === 'on') e.addEventListener(eventName, eventHandler);
      else /* off */ e.removeEventListener(eventName, eventHandler);
    }
  };

  this.on = function(start, elt_or_selector, eventName, eventHandler) {
    onOrOff('on', start, elt_or_selector, eventName, eventHandler);
  };

  this.off = function(start, elt_or_selector, eventName, eventHandler) {
    onOrOff('off', start, elt_or_selector, eventName, eventHandler);
  };

  var indexNext = function(sel) {

    var d = sel.indexOf('.'); var s = sel.indexOf('#');
    if (d < 0) return s; if (s < 0) return d;
    return d < s ? d : s;
  };

  this.create = function(sel, atts, text) {

    sel = '%' + sel;
    if ((typeof atts) === 'string') { text = atts; atts = {}; }

    var e = document.createElement('div');

    for (var i = 0; i < sel.length; ) {
      var t = sel.substring(i, i + 1);
      var j = indexNext(sel.substring(i + 1));
      var s = j > -1 ? sel.substring(i + 1, i + 1 + j) : sel.substring(i + 1);
      //console.log([ t, j, s ]);
      if (t === '%') e = document.createElement(s);
      else if (t === '#') e.id = s;
      else if (t === '.') e.classList.add(s);
      if (j < 0) break;
      i = i + 1 + j;
    }

    for (var k in atts) e.setAttribute(k, atts[k]);

    if (text) e.appendChild(document.createTextNode(text));

    return e;
  };

  this.toNode = function(html) {

    var e = document.createElement('div');
    e.innerHTML = html; // :-(

    return e.children[0];
  };

  var defaultOn = function(type, method, uri) {

    return function(res) {
      if (type === 'load') console.log([ method + ' ' + uri, res ]);
      else console.log([ meth + ' ' + uri + ' connection problem', res ]);
    }
  };

  this.request = function(method, uri, data, callbacks) {

    if ( ! callbacks) { callbacks = data; data = null; }
    if ((typeof callbacks) === 'function') callbacks = { onok: callbacks };

    var r = new XMLHttpRequest();
    r.open(method, uri, true);

    if (data) {
      if (data.constructor.toString().match(/FormData/)) {
        //r.setRequestHeader('Content-Type', 'application/form-data');
      }
      else {
        r.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
        data = (typeof data) === 'string' ? data : JSON.stringify(data);
      }
    }

    r.onload = function() {
      var o = { status: r.status, request: r };
      o.data = null; try { o.data = JSON.parse(r.responseText); } catch (ex) {};
      if (callbacks.onok && r.status === 200)
        callbacks.onok(o);
      else
        (callbacks.onload || defaultOn('load', method, uri))(o);
    };
    r.onerror = callbacks.onerror || defaultOn('error', method, uri);

    r.send(data);
  };

  this.upload = function(uri, inputFileElt_s, data, callbacks) {

    //console.log('uploading to ' + uri + ' ...');

    if ( ! callbacks) { callbacks = data; data = {}; }

    var fd = new FormData();

    for (var k in data) fd.append(k, data[k]);

    var isMulti = Array.isArray(inputFileElt_s);
    var elts = isMulti ? inputFileElt_s : [ inputFileElt_s ];

    var fcount = 0;

    elts.forEach(function(elt) {

      var files = elt.files;

      for (var i = 0, l = files.length; i < l; i++) {

        fcount = fcount + 1;

        var f = files[i];

        var l = elt.getAttribute('data-sg-lang');
        var k = 'file-';
        if (l || isMulti) k = k + elt.name + '-';
        if (l) k = k + l + '-';
        k = k + i;

        fd.append(k, f, f.name);
      }
    });

    if (fcount < 1) return 0;

    var onok = callbacks.onok;
    callbacks.onok = function(res) {
      elts.forEach(function(elt) { elt.value = ''; });
      onok(res);
    };

    H.request('POST', uri, fd, callbacks);

    return fcount;
  };

  this.matches = function(elt, sel) {

    if (elt.matches) return elt.matches(sel);
    if (elt.matchesSelector) return elt.matchesSelector(sel);
    if (elt.msMatchesSelector) return elt.msMatchesSelector(sel);

    throw "browser doesn't support elt.matches() or elt.matchesSelector()";
  };

  this.closest = function(start, elt_or_selector, sel) {

    if ( ! sel) {
      sel = elt_or_selector; elt_or_selector = start; start = null;
    }
    var elt = toElt(start, elt_or_selector);

    if (H.matches(elt, sel)) return elt;

    return elt.parentElement ? H.closest(elt.parentElement, sel) : null;
  };

  // adapted from http://upshots.org/javascript/jquery-copy-style-copycss
  //
  this.style = function(start, elt_or_selector) {

    var elt = toElt(start, elt_or_selector);

    var r = {};
    var style = null;

    if (window.getComputedStyle) {

      style = window.getComputedStyle(elt, null);

      for (var i = 0, l = style.length; i < l; i++) {
        var p = style[i];
        var n = p.replace(
          /-([a-za])/g, function(a, b) { return b.toUpperCase(); })
        r[n] = style.getPropertyValue(p);
      }

      return r;
    }

    if (style = elt.currentStyle) {

      for (var p in style) r[p] = style[p];
      return r;
    }

    if (style = elt.style) {

      for (var p in style) {
        var s = style[p];
        if ((typeof s) !== 'function') r[p] = s;
      }

      //return r;
    }

    return r;
  };

  this.hasClass = function(start, elt_or_selector, className) {

    if ( ! className) {
      className = elt_or_selector; elt_or_selector = start; start = null;
    }

    var elt = toElt(start, elt_or_selector);
    if (className[0] === '.') className = className.substring(1);

    try {
      if (elt.classList) return elt.classList.contains(className);
      return (new RegExp('\\b' + className + '\\b')).test(elt.className);
    }
    catch (ex) {
      return false;
    }
  };

  this.removeClass = function(start, elt_or_selector, className) {

    if ( ! className) {
      className = elt_or_selector; elt_or_selector = start; start = null;
    }

    if (className[0] === '.') className = className.substring(1);

    toElts(start, elt_or_selector).forEach(function(e) {
      e.classList.remove(className);
    });
  }

  this.addClass = function(start, elt_or_selector, className) {

    if ( ! className) {
      className = elt_or_selector; elt_or_selector = start; start = null;
    }

    if (className[0] === '.') className = className.substring(1);

    toElts(start, elt_or_selector).forEach(function(e) {
      e.classList.add(className);
    });
  }

  var tog = function(start, elt_or_selector, bool, klass) {

    if (
      (typeof elt_or_selector) === 'boolean' || elt_or_selector === 'toggle'
    ) {
      bool = elt_or_selector; elt_or_selector = start; start = null;
    }

    if (bool === 'toggle') {
      bool = ! self.hasClass(start, elt_or_selector, klass);
    }

    toElts(start, elt_or_selector).forEach(function(e) {
      self[bool ? 'addClass' : 'removeClass'](e, klass);
      return bool;
    });
  };

  this.toggleClass = function(start, elt_or_selector, className) {

    if ( ! className) {
      className = elt_or_selector; elt_or_selector = start; start = null;
    }

    return tog(start, elt_or_selector, 'toggle', className);
  };
  this.toggle = this.toggleClass;

  this.show = function(start, elt_or_selector, bool) {

    tog(start, elt_or_selector, bool, '.show');
  };

  this.hide = function(start, elt_or_selector, bool) {

    tog(start, elt_or_selector, bool, '.hidden');
  };

  this.enable = function(start, elt_or_selector, bool) {

    if (bool === undefined) {
      bool = elt_or_selector; elt_or_selector = start; start = null;
    }

    toElts(start, elt_or_selector).forEach(function(e) {
      if (bool === false || bool === null)
        e.setAttribute('disabled', 'disabled');
      else
        e.removeAttribute('disabled');
    });
  }

  this.disable = function(start, elt_or_selector) {

    self.enable(start, elt_or_selector, false);
  };

  this.cdisable = function(start, elt_or_selector) {

    H.addClass(start, elt_or_selector, '.disabled');
  };

  this.cenable = function(start, elt_or_selector) {

    H.removeClass(start, elt_or_selector, '.disabled');
  };

  this.toCamelCase = function(s) {

    return s.replace(
      /([_-][a-z])/g, function(x) { return x.substring(1).toUpperCase(); });
  };

  this.prepend = function(start, elt_or_selector, child) {

    if ( ! child) {
      child = elt_or_selector; elt_or_selector = start; start = null;
    }

    var elt = toElt(start, elt_or_selector);

    elt.parentNode.insertBefore(child, elt);
  };

  this.trigger = function(start, elt_or_selector, eventName) {

    if ( ! eventName) {
      eventName = elt_or_selector; elt_or_selector = start; start = null;
    }

    var elt = toElt(start, elt_or_selector);

    var ev = document.createEvent('HTMLEvents');
    ev.initEvent(eventName, true, false);

    elt.dispatchEvent(ev);
  };

  this.clean = function(start, elt_or_selector, className) {

    var elt = toElt(start, elt_or_selector);
    if (className) H.forEach(elt, className, function(e) { e.remove(); });
    else while (elt.firstChild) elt.removeChild(elt.firstChild);

    return elt;
  };

  this.onDocumentReady = function(f) {

    if (document.readyState != 'loading') f();
    else document.addEventListener('DOMContentLoaded', f);
  };

  //
  // over.

  return this;

}).apply({});

<|endoftext|>


<commit_before>const http = require('http');
const express = require('express');
const mongo = require('mongodb');
const fs = require('fs');
const bodyparser = require('body-parser');
var ascoltatori_mqtt = require('ascoltatori');
var mqtt = require('mqtt');
const BSON = require('bson').BSONPure;
var path = require('path');
var MongoClient = mongo.MongoClient;
var Server = mongo.Server;
var expressapp = express();
var mongoUrl;
var mongoPort;
var kafkaUrl;
var kafkaPort;
var timeoutLimit,
    roadMapIdTemp,
    db,
    latestOffset,
    mqttHost,
    mqttPort;
var MyDate = new Date();
var MyDateString;
var consumer;
var kafka = require('kafka-node'),
Producer = kafka.Producer,
Consumer = kafka.Consumer,
client = new kafka.Client(),
producer = new Producer(client),
payloads = [
    {
        // topic:'event',
        messages: '',
        partition: 0
    }
],
offset = new kafka.Offset(client);
//make server starts from latest logs
offset.fetchLatestOffsets(['log'], function (error, offsets) {
    if (error)
    return handleError(error);
    console.log('start from...\n\tkafka topic: log\n\toffset : '+offsets['log'][0]);
    latestOffset = offsets['log'][0];
    consumer = new Consumer(
        client,
        [
            {
                topic: 'log',
                partition: 0,
                offset: latestOffset
            }
        ],
        {
            autoCommit: false,
            fromOffset: true

        }
    );
    consumer.on('message', function (message) {
        MyDate = new Date();
        MyDate.setDate(MyDate.getDate() + 20);
        MyDateString = MyDate.getFullYear() + '/'
        +('0' + MyDate.getMonth()).slice(-2) + '/'
        +('0' + MyDate.getDate()).slice(-2) + '   '
        +('0' + MyDate.getHours()).slice(-2) + ':'
        +('0' + MyDate.getMinutes()).slice(-2) + ':'
        +('0' + MyDate.getSeconds()).slice(-2);
        console.log(MyDateString+"   "+JSON.stringify(message));
        fs.appendFile('.log', '['+MyDateString+']  '+ JSON.stringify(message)+'\r\n', 'utf8', function(err) {
        });
    });
});

expressapp.use(bodyparser.json());
expressapp.use(function(req,res,next){
    res.setTimeout(15000, function(){
        console.log('time out..');
        res.sendStatus(408);
    });
    next();
});
expressapp.use(express.static(path.join(__dirname+"/../", 'ENOW-console')));
const port = 1111;
expressapp.set('port', port);

expressapp.post('/post_db', function(req, res){
    connectDB(req.body, 'enow', 'recipes', 'save', res);
});

var sendKafka = function(req, topic, messages){
    payloads[0]['topic'] = topic
    payloads[0]['messages']= JSON.stringify(messages, null, '   ');
    setTimeout(function () {
        producer.send(payloads, function (err, data) {
            console.log(payloads);
        });
        producer.on('error', function (err) {
            console.log(err);
        });
    }, 1000);
}

var reserve = function(cb) {
    process.nextTick(function() {
        cb();
    });
}
var makeReserve = function(key, value, res) {
    reserve(function() {
        var obj = new Object();
        var aliveAsk = 0;
        obj['brokerId'] = key;
        console.log(obj);
        connectDB(obj, 'connectionData', 'brokerList', 'findBroker2', null);
        setTimeout(function(){
        console.log("-------------------------------------------");
        console.log("-------------------------------------------");
        console.log(mqttHost);
        console.log(mqttPort);
            var client = mqtt.connect('mqtt://'+mqttHost+':'+mqttPort);
            client.on('connect', function(){
                client.publish('enow/server0/'+key+'/'+value+'/alive/request', '{"topic":'+'enow/server0/'+key+'/'+value+'"}');
                client.subscribe('enow/server0/'+key+'/'+value+'/alive/response');
            })
            var waitAck = setInterval(function(){
                console.log(client.connected);
                if(++aliveAsk>3){
                    clearInterval(waitAck);
                    res.write('0');
                    client.end();
                }
            }, 2000);
            client.on('message', function(topic, message){
                console.log(topic);
                console.log(message.toString());
                client.end();
                res.write('1');
                clearInterval(waitAck);
            });
        }, 2000);
        console.log(key, value);
    });
}
expressapp.post('/alive_check', function(req, res){
    var obj = new Object();
    console.log('Running RoadMap!');

    setTimeout(function(){
        for(var i=1; i<= Object.keys(req.body['nodeIds']).length ; ++i){
            obj[req.body['nodeIds'][i]['brokerId']] = obj[req.body['nodeIds'][i]['brokerId']] || [];
            obj[req.body['nodeIds'][i]['brokerId']].push(req.body['nodeIds'][i]['deviceId']);
        }
        for(key in obj){
            for(val in obj[key]){
                makeReserve(key, obj[key][val], res);
            }
        }
        setTimeout(function(){
            res.end();
        },timeoutLimit || 12000)
    }, 3000);
});
expressapp.post('/run_db', function(req, res){
        connectDB(req.body, 'enow', 'execute', 'run', res);
        sendKafka(req, 'event', '{roadMapId:'+req.body['roadMapId']+'}');
});
expressapp.post('/kill_db', function(req, res){
    console.log('kill execute...');
    connectDB(req.body, 'enow', 'execute', 'kill', res)
});
expressapp.post('/add_broker', function(req, res){
    console.log('add broker...');
    console.log(req.body);
    connectDB(req.body, 'connectionData', 'brokerList', 'saveBroker', res);
    sendKafka(req, 'brokerAdd', req.body);
});
expressapp.post('/add_device', function(req, res){
    console.log('add device...');
    connectDB(req.body, 'connectionData', 'brokerList', 'saveDevice', res);
});
expressapp.post('/find_device', function(req, res){
    console.log('find device...');
    connectDB(req.body, 'connectionData', 'brokerList', 'findDevice', res);
});
expressapp.post('/find_broker', function(req, res){
    console.log('find broker...');
    connectDB(req.body, 'connectionData', 'brokerList', 'findBroker', res);
});
expressapp.post('/post_url_settings', function(req, res){
    console.log('setting url...');
    mongoUrl = req.body['mongoUrl'];
    mongoPort = req.body['mongoPort'];
    kafkaUrl = req.body['kafkaUrl'];
    kafkaPort = req.body['kafkaPort'];
    timeoutLimit = req.body['timeoutLimit']*1000;
    producer.client.connectionString = kafkaUrl+':'+kafkaPort;
    if(db){
        db.close();
    }
    MongoClient.connect('mongodb://'+ mongoUrl+'/'+mongoPort, function(err, database, callback) {
        if(err){
            console.log(err);
            res.send('no_connect');
            return;
        }
        db = database;
        console.log('connected to mongodb://'+ mongoUrl+'/'+mongoPort);
        res.send("done");
    });
});
expressapp.post('/load_roadmap', function(req, res){
    console.log('load roadmap...');
    console.log(req.body['db']);
    connectDB(req.body, req.body['db'], req.body['collection'], 'findTarget', res);
});
expressapp.post('/get_broker', function(req, res){
    console.log('get broker...');
    connectDB(req.body, 'connectionData', 'brokerList', 'findBroker', res);
});

expressapp.post('/add_secure', function(req, res){
    console.log('add secure...');
    console.log(req.body);
    connectDB(req.body, 'connectionData', 'brokerList', 'addSecure', res);
});

expressapp.get('/get_brokers', function(req, res){
    console.log('get brokers...');
    connectDB(null, 'connectionData', 'brokerList', 'find', res);
});
expressapp.get('/get_settings', function(req, res){
    console.log('get settings...');
    connectDB(null, 'connectionData', 'settings', 'find', res);
});
expressapp.get('/get_roadmaps', function(req, res){
    console.log('get roadmaps...');
    connectDB(null, 'enow', 'recipes', 'find', res);
});
expressapp.get('/get_running_roadmaps', function(req, res){
    console.log('get running roadmaps...');
    connectDB(null, 'enow', 'execute', 'find', res);
});
expressapp.get('/get_devices', function(req, res){
    console.log('get devices...');
    connectDB(null, 'connectionData', 'brokerList', 'find', res);
});

var server = expressapp.listen(expressapp.get('port'), function(){
    console.log(
        "\n\n\n  ███████╗███╗   ██╗ ██████╗ ██╗    ██╗\
        \n  ██╔════╝████╗  ██║██╔═══██╗██║    ██║  ENOW Started!\
        \n  █████╗  ██╔██╗ ██║██║   ██║██║ █╗ ██║  Connect to 127.0.0.1:1111\
        \n  ██╔══╝  ██║╚██╗██║██║   ██║██║███╗██║\
        \n  ███████╗██║ ╚████║╚██████╔╝╚███╔███╔╝  Version 0.0.1\
        \n  ╚══════╝╚═╝  ╚═══╝ ╚═════╝  ╚══╝╚══╝   Copyright © 2016 ENOW. All rights reserved.");
    });

    function connectDB(source, dbName, collectionName, command, response){
        console.log('connecting to '+mongoUrl+':'+mongoPort+'...'+dbName+'.'+collectionName);
        var findDocument = function(callback){
            db.db(dbName).collection(collectionName).find({}).toArray(function(err,result){
                response.send(result);
            });
        };
        var findBroker = function(callback){
            db.db(dbName).collection(collectionName).find({brokerId:source['brokerId']}).toArray(function(err,result){
                    response.send(result);
            });
        };
        var findBroker_2 = function(callback){
            console.log(source);
            db.db(dbName).collection(collectionName).find({brokerId:source['brokerId']}).toArray(function(err,result){
                    mqttHost = result[0]['ipAddress'];
                    mqttPort = result[0]['port'];

            });
        };
        var findTarget = function(callback){
            var o_id = BSON.ObjectID.createFromHexString(source['_id']);
            db.db(dbName).collection(collectionName).find({_id:o_id}).toArray(function(err,result){
                response.send(result);
                o_id = null;
            });
        }

        var findDevice = function(callback){
            db.db(dbName).collection(collectionName).find({deviceId:source['deviceId']}).toArray(function(err,result){
                response.send(result);
            });
        }

        var insertDocument = function(callback){
            var cursor = db.db(dbName).collection(collectionName).find({}).toArray(function(err,result){
                if(result.length!=0){
                    roadMapIdTemp = parseInt(result[result.length-1]['roadMapId'])+1;
                }
                else{
                    roadMapIdTemp = 1;
                }
                db.db(dbName).collection(collectionName).insertOne({
                    "roadMapId" : roadMapIdTemp.toString(),
                    "clientId" : source['clientId'],
                    "orderNode" : source['orderNode'],
                    "initNode" : source['initNode'],
                    "lastNode" : source['lastNode'],
                    "incomingNode" : source['incomingNode'],
                    "outingNode" : source['outingNode'],
                    "isInput" : source['isInput'],
                    "isOutput" : source['isOutput'],
                    "nodeIds" : source['nodeIds']
                },function(err, result){
                    response.send("done");
                });
            });

        };

        var insertDocumentDevice = function(callback){
            db.db(dbName).collection(collectionName).updateOne({'brokerId':source['brokerId']},{
                '$push' : { 'deviceId': source['deviceId']}
            }, function(err,result){
                response.send("done");
            });
        };

        var insertDocumentBroker = function(callback){
            db.db(dbName).collection(collectionName).count({}, function(err, cnt) {
                db.db(dbName).collection(collectionName).insertOne({
                    "brokerNum" : (cnt+1).toString(),
                    "brokerId" : source['brokerId'],
                    "ipAddress" : source['ipAddress'],
                    "port" : source['port'],
                    "deviceId" : source['deviceId'],
                },function(err, result){
                    response.send("done");
                });
            });
        };

        var updateBroker = function(callback){
            db.db(dbName).collection(collectionName).updateOne({'brokerId':source['brokerId']},{
                '$set' : { 'ca': source['ca'], 'hostCrt': source['hostCrt'], 'hostKey': source['hostKey']}
            }, function(err,result){
                response.send("done");
            });
        };

        var deleteDocument = function(callback){
            db.db(dbName).collection(collectionName).deleteOne({
            },function(err, result){
                response.send("done");
            });
        };

        if(command=="save" || command=="run"){
            insertDocument(db, function(){
            });
        }else if(command=="saveBroker"){
            insertDocumentBroker(db, function(){
            });
        }else if(command=="saveDevice"){
            insertDocumentDevice(db, function(){
            });
        }else if(command=="findDevice"){
            findDevice(db, function(){
            });
        }else if(command=="kill"){
            deleteDocument(db,function(){
            });
        }else if(command=="find"){
            findDocument(db, function(){
            });
        }else if(command=="findTarget"){
            findTarget(db, function(){
            });
        }else if(command=="findBroker"){
            findBroker(db, function(){
            });
        }else if(command=="findBroker2"){
            findBroker_2(db, function(){
            });
        }else if(command=="addSecure"){
            updateBroker(db, function(){
            });
        }
    };
<commit_msg>sorry. try again<commit_after>const http = require('http');
const express = require('express');
const mongo = require('mongodb');
const fs = require('fs');
const bodyparser = require('body-parser');
var ascoltatori_mqtt = require('ascoltatori');
var mqtt = require('mqtt');
const BSON = require('bson').BSONPure;
var path = require('path');
var MongoClient = mongo.MongoClient;
var Server = mongo.Server;
var expressapp = express();
var mongoUrl;
var mongoPort;
var kafkaUrl;
var kafkaPort;
var timeoutLimit,
    roadMapIdTemp,
    db,
    latestOffset,
    mqttHost,
    mqttPort;
var MyDate = new Date();
var MyDateString;
var consumer;
var kafka = require('kafka-node'),
Producer = kafka.Producer,
Consumer = kafka.Consumer,
client = new kafka.Client(),
producer = new Producer(client),
payloads = [
    {
        // topic:'event',
        messages: '',
        partition: 0
    }
],
offset = new kafka.Offset(client);
//make server starts from latest logs
offset.fetchLatestOffsets(['log'], function (error, offsets) {
    if (error)
    return handleError(error);
    console.log('start from...\n\tkafka topic: log\n\toffset : '+offsets['log'][0]);
    latestOffset = offsets['log'][0];
    consumer = new Consumer(
        client,
        [
            {
                topic: 'log',
                partition: 0,
                offset: latestOffset
            }
        ],
        {
            autoCommit: false,
            fromOffset: true

        }
    );
    consumer.on('message', function (message) {
        MyDate = new Date();
        MyDate.setDate(MyDate.getDate() + 20);
        MyDateString = MyDate.getFullYear() + '/'
        +('0' + MyDate.getMonth()).slice(-2) + '/'
        +('0' + MyDate.getDate()).slice(-2) + '   '
        +('0' + MyDate.getHours()).slice(-2) + ':'
        +('0' + MyDate.getMinutes()).slice(-2) + ':'
        +('0' + MyDate.getSeconds()).slice(-2);
        console.log(MyDateString+"   "+JSON.stringify(message));
        fs.appendFile('.log', '['+MyDateString+']  '+ JSON.stringify(message)+'\r\n', 'utf8', function(err) {
        });
    });
});

expressapp.use(bodyparser.json());
expressapp.use(function(req,res,next){
    res.setTimeout(15000, function(){
        console.log('time out..');
        res.sendStatus(408);
    });
    next();
});
expressapp.use(express.static(path.join(__dirname+"/../", 'ENOW-console')));
const port = 1111;
expressapp.set('port', port);

expressapp.post('/post_db', function(req, res){
    connectDB(req.body, 'enow', 'recipes', 'save', res);
});

var sendKafka = function(req, topic, messages){
    payloads[0]['topic'] = topic
    payloads[0]['messages']= JSON.stringify(messages, null, '   ');
    setTimeout(function () {
        producer.send(payloads, function (err, data) {
            console.log(payloads);
        });
        producer.on('error', function (err) {
            console.log(err);
        });
    }, 1000);
}

var reserve = function(cb) {
    process.nextTick(function() {
        cb();
    });
}
var makeReserve = function(key, value, res) {
    reserve(function() {
        var obj = new Object();
        var aliveAsk = 0;
        obj['brokerId'] = key;
        console.log(obj);
        connectDB(obj, 'connectionData', 'brokerList', 'findBroker2', null);
        setTimeout(function(){
        console.log("-------------------------------------------");
        console.log("-------------------------------------------");
        console.log(mqttHost);
        console.log(mqttPort);
            var client = mqtt.connect('mqtt://'+mqttHost+':'+mqttPort);
            client.on('connect', function(){
                client.publish('enow/server0/'+key+'/'+value+'/alive/request', '{"topic":'+'"enow/server0/'+key+'/'+value+'"}');
                client.subscribe('enow/server0/'+key+'/'+value+'/alive/response');
            })
            var waitAck = setInterval(function(){
                console.log(client.connected);
                if(++aliveAsk>3){
                    clearInterval(waitAck);
                    res.write('0');
                    client.end();
                }
            }, 2000);
            client.on('message', function(topic, message){
                console.log(topic);
                console.log(message.toString());
                client.end();
                res.write('1');
                clearInterval(waitAck);
            });
        }, 2000);
        console.log(key, value);
    });
}
expressapp.post('/alive_check', function(req, res){
    var obj = new Object();
    console.log('Running RoadMap!');

    setTimeout(function(){
        for(var i=1; i<= Object.keys(req.body['nodeIds']).length ; ++i){
            obj[req.body['nodeIds'][i]['brokerId']] = obj[req.body['nodeIds'][i]['brokerId']] || [];
            obj[req.body['nodeIds'][i]['brokerId']].push(req.body['nodeIds'][i]['deviceId']);
        }
        for(key in obj){
            for(val in obj[key]){
                makeReserve(key, obj[key][val], res);
            }
        }
        setTimeout(function(){
            res.end();
        },timeoutLimit || 12000)
    }, 3000);
});
expressapp.post('/run_db', function(req, res){
        connectDB(req.body, 'enow', 'execute', 'run', res);
        sendKafka(req, 'event', '{roadMapId:'+req.body['roadMapId']+'}');
});
expressapp.post('/kill_db', function(req, res){
    console.log('kill execute...');
    connectDB(req.body, 'enow', 'execute', 'kill', res)
});
expressapp.post('/add_broker', function(req, res){
    console.log('add broker...');
    console.log(req.body);
    connectDB(req.body, 'connectionData', 'brokerList', 'saveBroker', res);
    sendKafka(req, 'brokerAdd', req.body);
});
expressapp.post('/add_device', function(req, res){
    console.log('add device...');
    connectDB(req.body, 'connectionData', 'brokerList', 'saveDevice', res);
});
expressapp.post('/find_device', function(req, res){
    console.log('find device...');
    connectDB(req.body, 'connectionData', 'brokerList', 'findDevice', res);
});
expressapp.post('/find_broker', function(req, res){
    console.log('find broker...');
    connectDB(req.body, 'connectionData', 'brokerList', 'findBroker', res);
});
expressapp.post('/post_url_settings', function(req, res){
    console.log('setting url...');
    mongoUrl = req.body['mongoUrl'];
    mongoPort = req.body['mongoPort'];
    kafkaUrl = req.body['kafkaUrl'];
    kafkaPort = req.body['kafkaPort'];
    timeoutLimit = req.body['timeoutLimit']*1000;
    producer.client.connectionString = kafkaUrl+':'+kafkaPort;
    if(db){
        db.close();
    }
    MongoClient.connect('mongodb://'+ mongoUrl+'/'+mongoPort, function(err, database, callback) {
        if(err){
            console.log(err);
            res.send('no_connect');
            return;
        }
        db = database;
        console.log('connected to mongodb://'+ mongoUrl+'/'+mongoPort);
        res.send("done");
    });
});
expressapp.post('/load_roadmap', function(req, res){
    console.log('load roadmap...');
    console.log(req.body['db']);
    connectDB(req.body, req.body['db'], req.body['collection'], 'findTarget', res);
});
expressapp.post('/get_broker', function(req, res){
    console.log('get broker...');
    connectDB(req.body, 'connectionData', 'brokerList', 'findBroker', res);
});

expressapp.post('/add_secure', function(req, res){
    console.log('add secure...');
    console.log(req.body);
    connectDB(req.body, 'connectionData', 'brokerList', 'addSecure', res);
});

expressapp.get('/get_brokers', function(req, res){
    console.log('get brokers...');
    connectDB(null, 'connectionData', 'brokerList', 'find', res);
});
expressapp.get('/get_settings', function(req, res){
    console.log('get settings...');
    connectDB(null, 'connectionData', 'settings', 'find', res);
});
expressapp.get('/get_roadmaps', function(req, res){
    console.log('get roadmaps...');
    connectDB(null, 'enow', 'recipes', 'find', res);
});
expressapp.get('/get_running_roadmaps', function(req, res){
    console.log('get running roadmaps...');
    connectDB(null, 'enow', 'execute', 'find', res);
});
expressapp.get('/get_devices', function(req, res){
    console.log('get devices...');
    connectDB(null, 'connectionData', 'brokerList', 'find', res);
});

var server = expressapp.listen(expressapp.get('port'), function(){
    console.log(
        "\n\n\n  ███████╗███╗   ██╗ ██████╗ ██╗    ██╗\
        \n  ██╔════╝████╗  ██║██╔═══██╗██║    ██║  ENOW Started!\
        \n  █████╗  ██╔██╗ ██║██║   ██║██║ █╗ ██║  Connect to 127.0.0.1:1111\
        \n  ██╔══╝  ██║╚██╗██║██║   ██║██║███╗██║\
        \n  ███████╗██║ ╚████║╚██████╔╝╚███╔███╔╝  Version 0.0.1\
        \n  ╚══════╝╚═╝  ╚═══╝ ╚═════╝  ╚══╝╚══╝   Copyright © 2016 ENOW. All rights reserved.");
    });

    function connectDB(source, dbName, collectionName, command, response){
        console.log('connecting to '+mongoUrl+':'+mongoPort+'...'+dbName+'.'+collectionName);
        var findDocument = function(callback){
            db.db(dbName).collection(collectionName).find({}).toArray(function(err,result){
                response.send(result);
            });
        };
        var findBroker = function(callback){
            db.db(dbName).collection(collectionName).find({brokerId:source['brokerId']}).toArray(function(err,result){
                    response.send(result);
            });
        };
        var findBroker_2 = function(callback){
            console.log(source);
            db.db(dbName).collection(collectionName).find({brokerId:source['brokerId']}).toArray(function(err,result){
                    mqttHost = result[0]['ipAddress'];
                    mqttPort = result[0]['port'];

            });
        };
        var findTarget = function(callback){
            var o_id = BSON.ObjectID.createFromHexString(source['_id']);
            db.db(dbName).collection(collectionName).find({_id:o_id}).toArray(function(err,result){
                response.send(result);
                o_id = null;
            });
        }

        var findDevice = function(callback){
            db.db(dbName).collection(collectionName).find({deviceId:source['deviceId']}).toArray(function(err,result){
                response.send(result);
            });
        }

        var insertDocument = function(callback){
            var cursor = db.db(dbName).collection(collectionName).find({}).toArray(function(err,result){
                if(result.length!=0){
                    roadMapIdTemp = parseInt(result[result.length-1]['roadMapId'])+1;
                }
                else{
                    roadMapIdTemp = 1;
                }
                db.db(dbName).collection(collectionName).insertOne({
                    "roadMapId" : roadMapIdTemp.toString(),
                    "clientId" : source['clientId'],
                    "orderNode" : source['orderNode'],
                    "initNode" : source['initNode'],
                    "lastNode" : source['lastNode'],
                    "incomingNode" : source['incomingNode'],
                    "outingNode" : source['outingNode'],
                    "isInput" : source['isInput'],
                    "isOutput" : source['isOutput'],
                    "nodeIds" : source['nodeIds']
                },function(err, result){
                    response.send("done");
                });
            });

        };

        var insertDocumentDevice = function(callback){
            db.db(dbName).collection(collectionName).updateOne({'brokerId':source['brokerId']},{
                '$push' : { 'deviceId': source['deviceId']}
            }, function(err,result){
                response.send("done");
            });
        };

        var insertDocumentBroker = function(callback){
            db.db(dbName).collection(collectionName).count({}, function(err, cnt) {
                db.db(dbName).collection(collectionName).insertOne({
                    "brokerNum" : (cnt+1).toString(),
                    "brokerId" : source['brokerId'],
                    "ipAddress" : source['ipAddress'],
                    "port" : source['port'],
                    "deviceId" : source['deviceId'],
                },function(err, result){
                    response.send("done");
                });
            });
        };

        var updateBroker = function(callback){
            db.db(dbName).collection(collectionName).updateOne({'brokerId':source['brokerId']},{
                '$set' : { 'ca': source['ca'], 'hostCrt': source['hostCrt'], 'hostKey': source['hostKey']}
            }, function(err,result){
                response.send("done");
            });
        };

        var deleteDocument = function(callback){
            db.db(dbName).collection(collectionName).deleteOne({
            },function(err, result){
                response.send("done");
            });
        };

        if(command=="save" || command=="run"){
            insertDocument(db, function(){
            });
        }else if(command=="saveBroker"){
            insertDocumentBroker(db, function(){
            });
        }else if(command=="saveDevice"){
            insertDocumentDevice(db, function(){
            });
        }else if(command=="findDevice"){
            findDevice(db, function(){
            });
        }else if(command=="kill"){
            deleteDocument(db,function(){
            });
        }else if(command=="find"){
            findDocument(db, function(){
            });
        }else if(command=="findTarget"){
            findTarget(db, function(){
            });
        }else if(command=="findBroker"){
            findBroker(db, function(){
            });
        }else if(command=="findBroker2"){
            findBroker_2(db, function(){
            });
        }else if(command=="addSecure"){
            updateBroker(db, function(){
            });
        }
    };
<|endoftext|>


<commit_before>var dgram  = require('dgram')
  , sys    = require('sys')
  , net    = require('net')
  , config = require('./config')

var counters = {};
var timers = {};
var debugInt, flushInt, server;

config.configFile(process.argv[2], function (config, oldConfig) {
  if (! config.debug && debugInt) {
    clearInterval(debugInt);
    debugInt = false;
  }

  if (config.debug) {
    if (debugInt !== undefined) { clearInterval(debugInt); }
    debugInt = setInterval(function () {
      sys.log("Counters:\n" + sys.inspect(counters) + "\nTimers:\n" + sys.inspect(timers));
    }, config.debugInterval || 10000);
  }

  if (server === undefined) {
    server = dgram.createSocket('udp4', function (msg, rinfo) {
      if (config.dumpMessages) { sys.log(msg.toString()); }
      var bits = msg.toString().split(':');
      var key = bits.shift()
                    .replace(/\s+/g, '_')
                    .replace(/\//g, '-')
                    .replace(/[^a-zA-Z_\-0-9\.]/g, '');

      if (bits.length == 0) {
        bits.push("1");
      }

      for (var i = 0; i < bits.length; i++) {
        var sampleRate = 1;
        var fields = bits[i].split("|");
        if (fields[1] == "ms") {
          if (! timers[key]) {
            timers[key] = [];
          }
          timers[key].push(Number(fields[0] || 0));
        } else {
          if (fields[2] && fields[2].match(/^@([\d\.]+)/)) {
            sampleRate = Number(fields[2].match(/^@([\d\.]+)/)[1]);
          }
          if (! counters[key]) {
            counters[key] = 0;
          }
          counters[key] += Number(fields[0] || 1) * (1 / sampleRate);
        }
      }
    });

    server.bind(config.port || 8125);

    var flushInterval = Number(config.flushInterval || 10000);

    flushInt = setInterval(function () {
      var statString = '';
      var ts = Math.round(new Date().getTime() / 1000);
      var numStats = 0;
      var key;

      for (key in counters) {
        var value = counters[key] / (flushInterval / 1000);
        var message = 'stats.' + key + ' ' + value + ' ' + ts + "\n";
        statString += message;
        counters[key] = 0;

        numStats += 1;
      }

      for (key in timers) {
        if (timers[key].length > 0) {
          var pctThreshold = config.percentThreshold || 90;
          var values = timers[key].sort(function (a,b) { return a-b; });
          var count = values.length;
          var min = values[0];
          var max = values[count - 1];

          var mean = min;
          var maxAtThreshold = max;

          if (count > 1) {
            var thresholdIndex = Math.round(((100 - pctThreshold) / 100) * count);
            var numInThreshold = count - thresholdIndex;
            values = values.slice(0, numInThreshold);
            maxAtThreshold = values[numInThreshold - 1];

            // average the remaining timings
            var sum = 0;
            for (var i = 0; i < numInThreshold; i++) {
              sum += values[i];
            }

            mean = sum / numInThreshold;
          }

          timers[key] = [];

          var message = "";
          message += 'stats.timers.' + key + '.mean ' + mean + ' ' + ts + "\n";
          message += 'stats.timers.' + key + '.upper ' + max + ' ' + ts + "\n";
          message += 'stats.timers.' + key + '.upper_' + pctThreshold + ' ' + maxAtThreshold + ' ' + ts + "\n";
          message += 'stats.timers.' + key + '.lower ' + min + ' ' + ts + "\n";
          message += 'stats.timers.' + key + '.count ' + count + ' ' + ts + "\n";
          statString += message;

          numStats += 1;
        }
      }

      statString += 'statsd.numStats ' + numStats + ' ' + ts + "\n";

      var graphite = net.createConnection(config.graphitePort, config.graphiteHost);

      graphite.on('connect', function() {
        this.write(statString);
        this.end();
      });

    }, flushInterval);
  }

});

<commit_msg>trim whitespace before checking if the message type is "ms" (timer)<commit_after>var dgram  = require('dgram')
  , sys    = require('sys')
  , net    = require('net')
  , config = require('./config')

var counters = {};
var timers = {};
var debugInt, flushInt, server;

config.configFile(process.argv[2], function (config, oldConfig) {
  if (! config.debug && debugInt) {
    clearInterval(debugInt);
    debugInt = false;
  }

  if (config.debug) {
    if (debugInt !== undefined) { clearInterval(debugInt); }
    debugInt = setInterval(function () {
      sys.log("Counters:\n" + sys.inspect(counters) + "\nTimers:\n" + sys.inspect(timers));
    }, config.debugInterval || 10000);
  }

  if (server === undefined) {
    server = dgram.createSocket('udp4', function (msg, rinfo) {
      if (config.dumpMessages) { sys.log(msg.toString()); }
      var bits = msg.toString().split(':');
      var key = bits.shift()
                    .replace(/\s+/g, '_')
                    .replace(/\//g, '-')
                    .replace(/[^a-zA-Z_\-0-9\.]/g, '');

      if (bits.length == 0) {
        bits.push("1");
      }

      for (var i = 0; i < bits.length; i++) {
        var sampleRate = 1;
        var fields = bits[i].split("|");
        if (fields[1].trim() == "ms") {
          if (! timers[key]) {
            timers[key] = [];
          }
          timers[key].push(Number(fields[0] || 0));
        } else {
          if (fields[2] && fields[2].match(/^@([\d\.]+)/)) {
            sampleRate = Number(fields[2].match(/^@([\d\.]+)/)[1]);
          }
          if (! counters[key]) {
            counters[key] = 0;
          }
          counters[key] += Number(fields[0] || 1) * (1 / sampleRate);
        }
      }
    });

    server.bind(config.port || 8125);

    var flushInterval = Number(config.flushInterval || 10000);

    flushInt = setInterval(function () {
      var statString = '';
      var ts = Math.round(new Date().getTime() / 1000);
      var numStats = 0;
      var key;

      for (key in counters) {
        var value = counters[key] / (flushInterval / 1000);
        var message = 'stats.' + key + ' ' + value + ' ' + ts + "\n";
        statString += message;
        counters[key] = 0;

        numStats += 1;
      }

      for (key in timers) {
        if (timers[key].length > 0) {
          var pctThreshold = config.percentThreshold || 90;
          var values = timers[key].sort(function (a,b) { return a-b; });
          var count = values.length;
          var min = values[0];
          var max = values[count - 1];

          var mean = min;
          var maxAtThreshold = max;

          if (count > 1) {
            var thresholdIndex = Math.round(((100 - pctThreshold) / 100) * count);
            var numInThreshold = count - thresholdIndex;
            values = values.slice(0, numInThreshold);
            maxAtThreshold = values[numInThreshold - 1];

            // average the remaining timings
            var sum = 0;
            for (var i = 0; i < numInThreshold; i++) {
              sum += values[i];
            }

            mean = sum / numInThreshold;
          }

          timers[key] = [];

          var message = "";
          message += 'stats.timers.' + key + '.mean ' + mean + ' ' + ts + "\n";
          message += 'stats.timers.' + key + '.upper ' + max + ' ' + ts + "\n";
          message += 'stats.timers.' + key + '.upper_' + pctThreshold + ' ' + maxAtThreshold + ' ' + ts + "\n";
          message += 'stats.timers.' + key + '.lower ' + min + ' ' + ts + "\n";
          message += 'stats.timers.' + key + '.count ' + count + ' ' + ts + "\n";
          statString += message;

          numStats += 1;
        }
      }

      statString += 'statsd.numStats ' + numStats + ' ' + ts + "\n";

      var graphite = net.createConnection(config.graphitePort, config.graphiteHost);

      graphite.on('connect', function() {
        this.write(statString);
        this.end();
      });

    }, flushInterval);
  }

});

<|endoftext|>