<commit_before>(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['angular', 'pikaday'], factory);
  } else if (typeof exports === 'object') {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports, like Node.
    module.exports = factory(require('angular'), require('pikaday'));
  } else {
    // Browser globals (root is window)
    root.returnExports = factory(root.angular, root.Pikaday);
  }
}(this, function (angular, Pikaday) {

  angular.module('pikaday', [])
    .provider('pikadayConfig', function pikadayProviderFn() {

      // Create provider with getter and setter methods, allows setting of global configs

      var config = {};

      this.$get = function() {
        return config;
      };

      this.setConfig = function setConfig(configs) {
        config = configs;
      };
    })
    .directive('pikaday', ['pikadayConfig', pikadayDirectiveFn]);

  function pikadayDirectiveFn(pikadayConfig) {

    return {
      restrict: 'A',
      scope: {
        pikaday: '=',
        minDate: '=',
        maxDate: '=',
        onSelect: '&',
        onOpen: '&',
        onClose: '&',
        onDraw: '&',
        disableDayFn: '&'
      },
      require: '?ngModel',
      link: function (scope, elem, attrs, modelCtrl) {

        // Init config Object

        var config = { field: elem[0], onSelect: function () {
          setTimeout(function(){
            scope.$apply();
          });
        }};
        var hasMoment = typeof moment === 'function';
        // Decorate config with globals

        angular.forEach(pikadayConfig, function (value, key) {
          config[key] = value;
        });

        // Decorate/Overide config with inline attributes

        angular.forEach(attrs.$attr, function (dashAttr) {
          var attr = attrs.$normalize(dashAttr); // normalize = ToCamelCase()
          applyConfig(attr, attrs[attr]);
        });

        function applyConfig (attr, value) {
          switch (attr) {

            // Booleans, Integers & Arrays

            case "setDefaultDate":
            case "bound":
            case "reposition":
            case "disableWeekends":
            case "showWeekNumber":
            case "isRTL":
            case "showMonthAfterYear":
            case "firstDay":
            case "yearRange":
            case "numberOfMonths":
            case "mainCalendar":

              config[attr] = scope.$eval(value);
              break;

            // Functions

            case "onSelect":
            case "onOpen":
            case "onClose":
            case "onDraw":
            case "disableDayFn":

              config[attr] = function (date) {
                setTimeout(function(){
                  scope.$apply();
                });
                return scope[attr]({ pikaday: this, date: date });
              };
              break;

            // Strings

            case "format":
            case "position":
            case "theme":
            case "yearSuffix":

              config[attr] = value;
              break;

            // Dates

            case "minDate":
              scope.$watch('minDate', function (nValue) {
                if (!nValue) return;
                picker.setMinDate(nValue);
              });
              break;
            case "maxDate":
              scope.$watch('maxDate', function (nValue) {
                if (!nValue) return;
                picker.setMaxDate(nValue);
              });
              break;
            case "defaultDate":

              config[attr] = (value === 'now')? new Date(): new Date(value);
              break;

            // Elements

            case "trigger":
            case "container":

              config[attr] = document.getElementById(value);
              break;

            // Translations

            case "i18n":

              config[attr] = pikadayConfig.locales[value];

          }
        }
        // instantiate pikaday with config, bind to scope, add destroy event callback
        var picker = new Pikaday(config);
        scope.pikaday = picker;

        if (modelCtrl) {
          modelCtrl.$formatters.push(function (modelValue) {
            if (!modelValue) {
              return modelValue
            }
            var date = new Date(Date.parse(modelValue));
            if (date == "Invalid Date") {
              modelCtrl.$setValidity('date', false);
              return modelValue;
            }
            return hasMoment? moment(date).format(picker._o.format) : date.toDateString();
          });

          modelCtrl.$parsers.push(function (viewValue) {
            date = picker.getDate();
            return date;
          });
        }

        scope.$on('$destroy', function () {
          picker.destroy();
        });
      }
    };
  }

}));
<commit_msg>pikaday value is not required<commit_after>(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['angular', 'pikaday'], factory);
  } else if (typeof exports === 'object') {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports, like Node.
    module.exports = factory(require('angular'), require('pikaday'));
  } else {
    // Browser globals (root is window)
    root.returnExports = factory(root.angular, root.Pikaday);
  }
}(this, function (angular, Pikaday) {

  angular.module('pikaday', [])
    .provider('pikadayConfig', function pikadayProviderFn() {

      // Create provider with getter and setter methods, allows setting of global configs

      var config = {};

      this.$get = function() {
        return config;
      };

      this.setConfig = function setConfig(configs) {
        config = configs;
      };
    })
    .directive('pikaday', ['pikadayConfig', pikadayDirectiveFn]);

  function pikadayDirectiveFn(pikadayConfig) {

    return {
      restrict: 'A',
      scope: {
        pikaday: '=',
        minDate: '=',
        maxDate: '=',
        onSelect: '&',
        onOpen: '&',
        onClose: '&',
        onDraw: '&',
        disableDayFn: '&'
      },
      require: '?ngModel',
      link: function (scope, elem, attrs, modelCtrl) {

        // Init config Object

        var config = { field: elem[0], onSelect: function () {
          setTimeout(function(){
            scope.$apply();
          });
        }};
        var hasMoment = typeof moment === 'function';
        // Decorate config with globals

        angular.forEach(pikadayConfig, function (value, key) {
          config[key] = value;
        });

        // Decorate/Overide config with inline attributes

        angular.forEach(attrs.$attr, function (dashAttr) {
          var attr = attrs.$normalize(dashAttr); // normalize = ToCamelCase()
          applyConfig(attr, attrs[attr]);
        });

        function applyConfig (attr, value) {
          switch (attr) {

            // Booleans, Integers & Arrays

            case "setDefaultDate":
            case "bound":
            case "reposition":
            case "disableWeekends":
            case "showWeekNumber":
            case "isRTL":
            case "showMonthAfterYear":
            case "firstDay":
            case "yearRange":
            case "numberOfMonths":
            case "mainCalendar":

              config[attr] = scope.$eval(value);
              break;

            // Functions

            case "onSelect":
            case "onOpen":
            case "onClose":
            case "onDraw":
            case "disableDayFn":

              config[attr] = function (date) {
                setTimeout(function(){
                  scope.$apply();
                });
                return scope[attr]({ pikaday: this, date: date });
              };
              break;

            // Strings

            case "format":
            case "position":
            case "theme":
            case "yearSuffix":

              config[attr] = value;
              break;

            // Dates

            case "minDate":
              scope.$watch('minDate', function (nValue) {
                if (!nValue) return;
                picker.setMinDate(nValue);
              });
              break;
            case "maxDate":
              scope.$watch('maxDate', function (nValue) {
                if (!nValue) return;
                picker.setMaxDate(nValue);
              });
              break;
            case "defaultDate":

              config[attr] = (value === 'now')? new Date(): new Date(value);
              break;

            // Elements

            case "trigger":
            case "container":

              config[attr] = document.getElementById(value);
              break;

            // Translations

            case "i18n":

              config[attr] = pikadayConfig.locales[value];

          }
        }
        // instantiate pikaday with config, bind to scope, add destroy event callback
        var picker = new Pikaday(config);
        if (attrs.pikaday) {
          scope.pikaday = picker;
        }

        if (modelCtrl) {
          modelCtrl.$formatters.push(function (modelValue) {
            if (!modelValue) {
              return modelValue
            }
            var date = new Date(Date.parse(modelValue));
            if (date == "Invalid Date") {
              modelCtrl.$setValidity('date', false);
              return modelValue;
            }
            return hasMoment? moment(date).format(picker._o.format) : date.toDateString();
          });

          modelCtrl.$parsers.push(function (viewValue) {
            return picker.getDate();
          });
        }

        scope.$on('$destroy', function () {
          picker.destroy();
        });
      }
    };
  }

}));
<|endoftext|>


<commit_before>/**
    Usage:
    var update = new no.Update(pageinfo.layoutId, appView, pageinfo.params);

    @param {string} layoutId Current layout id. Initially it current page layout id.
    @param {no.View} pageRootView Start view for update. Currenty, it is app view.
    @param {Object} params Update params. Initially these are page params from URL.
*/
no.Update = function(layoutId, pageRootView, params) {
    this.id = no.Update.id++;

    // @type Object.<string, no.Request>
    this.queue = {};

    this.layout_id = layoutId;
    this.view = pageRootView;
    this.params = params;

    this.layout = no.layout.get(this.layout_id);
    this.createRequests();
};

no.extend(no.Update.prototype, no.Events);

/** @type {number} */
no.Update.id = 0;

no.Update.prototype.start = function() {
    this.requestMore();
};

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

no.Update.prototype.createRequests = function() {
    var that = this;
    var tree = this.tree = no.View.getLayoutTree(this.view.id, this);
    var main_models = []; // Main request models list.

    no.Update.walkLeafs(tree, function(view_id, type) {
        var view_info = no.View.info(view_id);
        var models = view_info.models;
        if (view_info.async) {
            that.createRequest4Async(view_id);
        } else {
            main_models = main_models.concat(models);
        }
    });

    this.createMainRequest(no.array.uniq(main_models));
};

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

/**
    Create request for async view.
*/
no.Update.prototype.createRequest4Async = function(viewId) {
    var that = this;

    var group = this._createGroup(viewId);
    if (!group) {
        return;
    }

    var request = new no.Request([ group ], false);

    request.on("gotData", function() { // После каждой очередной порции данных - пытаемся запросить ещё данных.
        that.requestMore();
    });

    this.queue[viewId] = request;

    request.promise.then(function() {
        // Remove request from queue when done.
        // "All done" check will be done in gotData handler.
        delete that.queue[viewId];

        that.page_ready.then(function() {
            var view = no.View.get(viewId, that.params);
            if (view) {
                view.invalidate();
            }
            that.updateView(viewId, request);
        });
    });
};

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

/**
    Creates a request for all !async blocks for main update view.
    @param {Array.<string>} models Model ids for !async blocks.
*/
no.Update.prototype.createMainRequest = function(models) {
    var that = this;
    var viewId = this.view.id;
    var page_redraw_promise = new no.Promise();
    var request = new no.Request([ { models: models, params: this.params } ], false);

    this.page_ready = no.Promise.wait([
        request.promise, // Got main page data.
        page_redraw_promise // Page main blocks were drawn (main page redraw promise).
    ]);

    request.on("gotData", function() { // После каждой очередной порции данных - пытаемся запросить ещё данных.
        that.requestMore();
    });

    this.queue[viewId] = request;

    request.promise.then(function() {
        // Remove request from queue when done.
        // "All done" check will be done in gotData handler.
        delete that.queue[viewId];

        that.updateView(that.view, request); // Update main page view.
        page_redraw_promise.resolve(); // Resolve main page redraw promise.
    });
};

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

/**
    @param {!Object} obj Target object to go through its properties.
    @param {function} callback A callback, called only on leaf properties (primitive types, !object).
*/
no.Update.walkLeafs = function(obj, callback) {
    no.object.forEach(obj, function(value, key) {
        if (typeof value !== 'object') {
            callback(key, value);
        } else {
            no.Update.walkLeafs(value, callback);
        }
    });
};

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

/**
    @param {no.View|no.Box|string} view View instance or view id, to find it.
*/
no.Update.prototype.updateView = function(view, request) {
    if (typeof view === "string") {
        view = no.View.get(view, this.params);
    }

    var viewsTree = [];
    view.getUpdateTrees(this, viewsTree);

    var tree = {
        models: {},
        params: this.params,
        views: viewsTree,
        location: document.location
    };

    var models = tree.models;

    var groups = request.groups;
    for (var i = 0, l = groups.length; i < l; i++) {
        var group = groups[i];
        for (var j = 0, m = group.models.length; j < m; j++) {
            var model_id = group.models[j];
            models[model_id] = no.Model.get(model_id, group.params).data;
        }
    }

    var html = Yater.run( tree ); // FIXME: Нужно проверять, что update не нужен и ничего не делать.
    var div = document.createElement('div');
    div.innerHTML = html;

    var node = div.firstChild;
    this.updateHtml(view, node);
};

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

/**
    @param {no.View|no.Box} view View / box, which html must be updated.
    @param {Element} node Generated html.
*/
no.Update.prototype.updateHtml = function(view, node) {
    var that = this;
    view.processTree(function(view) {
        if (view.needUpdate(that)) {
            view.update(node, that, true);
            return false;
        }
    });
};

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

no.Update.prototype.requestMore = function() {
    var all_done = true; // this update has nothing more to do.

    no.object.forEach(this.queue, function(request, view_id) {
        if (request.status === "active") { // this request is active, waiting for response.
            all_done = false;
        }

        if (request.send()) { // Could request more models.
            all_done = false;
        }
    });

    if (all_done) {
        no.object.forEach(this.queue, function(request, view_id) {
            // Waiting requests must be terminated.
            if (request.status === "waiting") {
                request.promise.resolve();
            }
        });

        this.trigger("done"); // XXX all rendered?
    }
};

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

no.Update.prototype._createGroup = function(viewId) {
    var info = no.View.info(viewId);
    if (info.models.length === 0) {
        return null;
    }

    return {
        models: info.models,
        params: this.params
    };
};
<commit_msg>Поток сознания про новый update<commit_after>/*
    Процесс апдейта:

      * Берем layout.
      * Проходим по текущему дереву блоков, выписываем все видимые сейчас.
      * Согласно layout выписываем все блоки, которые будут видны после апдейта.
      * Все несуществующие блоки создаются в соответствующих боксах со статусом loading. ???
      * Строим списки моделей, которые нужно запросить. Один список для основного (синхронного) апдейта,
        и по одному списку для всех асинхронных view.
      * Отправляем все запросы параллельно.
        Но! Первым отправляем запрос для синхронного апдейта.
      * При получении всех данных для синхро-апдейта строим дерево для шаблонизатор.
        В этом дереве должно быть под-дерево соответствующее иерархии блоков
        с дополнительной информацией, в частности, про статус блока.
        Для блоков, для которых еще нет данных нужно генерить блок-заглушку стандартным шаблоном.
      * Возможно, для асинхронные блоки верхнего уровня нужно создавать сразу и создавать отдельные апдейты для них.
      * Блок-заглушка показывает место этого "бокса" в ДОМе, все однотипные блоки создаются как сиблинги этой ноды.
      * После того, как отработал синхро-апдейт, можно апдейтить ДОМ для асинхронных апдейтов.
      * В дереве для шаблонизаторов лучше не линковать данные для каждого блока и использовать true/false для
        синхронных и асинхронных блоков.
      * Странная идея: есть проблема в том, что если не описывать подблоки в описании блока, а использовать
        только лейауты страниц, то неоткуда взять список параметров блока, чтобы строить ключ.
        Идея: пройтись по всем лейаутам и вытащить оттуда, какие блоки бывают внутри данного и составить список параметров.

*/

(function() {

no.Update = function(view, layout, params) {
    this.view = view;
    this.layout = layout;
    this.params = params;
};

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

no.Update.prototype.start = function() {
    var views = [];

    this.view.walk(function(view) {
        if ( !view.visible() ) {
            return false;
        }

        views.push(view);
    });
};

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

})();

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

/**
    Usage:
    var update = new no.Update(pageinfo.layoutId, appView, pageinfo.params);

    @param {string} layoutId Current layout id. Initially it current page layout id.
    @param {no.View} pageRootView Start view for update. Currenty, it is app view.
    @param {Object} params Update params. Initially these are page params from URL.
*/
no.Update = function(layoutId, pageRootView, params) {
    this.id = no.Update.id++;

    // @type Object.<string, no.Request>
    this.queue = {};

    this.layout_id = layoutId;
    this.view = pageRootView;
    this.params = params;

    this.layout = no.layout.get(this.layout_id);
    this.createRequests();
};

no.extend(no.Update.prototype, no.Events);

/** @type {number} */
no.Update.id = 0;

no.Update.prototype.start = function() {
    this.requestMore();
};

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

no.Update.prototype.createRequests = function() {
    var that = this;
    var tree = this.tree = no.View.getLayoutTree(this.view.id, this);
    var main_models = []; // Main request models list.

    no.Update.walkLeafs(tree, function(view_id, type) {
        var view_info = no.View.info(view_id);
        var models = view_info.models;
        if (view_info.async) {
            that.createRequest4Async(view_id);
        } else {
            main_models = main_models.concat(models);
        }
    });

    this.createMainRequest(no.array.uniq(main_models));
};

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

/**
    Create request for async view.
*/
no.Update.prototype.createRequest4Async = function(viewId) {
    var that = this;

    var group = this._createGroup(viewId);
    if (!group) {
        return;
    }

    var request = new no.Request([ group ], false);

    request.on("gotData", function() { // После каждой очередной порции данных - пытаемся запросить ещё данных.
        that.requestMore();
    });

    this.queue[viewId] = request;

    request.promise.then(function() {
        // Remove request from queue when done.
        // "All done" check will be done in gotData handler.
        delete that.queue[viewId];

        that.page_ready.then(function() {
            var view = no.View.get(viewId, that.params);
            if (view) {
                view.invalidate();
            }
            that.updateView(viewId, request);
        });
    });
};

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

/**
    Creates a request for all !async blocks for main update view.
    @param {Array.<string>} models Model ids for !async blocks.
*/
no.Update.prototype.createMainRequest = function(models) {
    var that = this;
    var viewId = this.view.id;
    var page_redraw_promise = new no.Promise();
    var request = new no.Request([ { models: models, params: this.params } ], false);

    this.page_ready = no.Promise.wait([
        request.promise, // Got main page data.
        page_redraw_promise // Page main blocks were drawn (main page redraw promise).
    ]);

    request.on("gotData", function() { // После каждой очередной порции данных - пытаемся запросить ещё данных.
        that.requestMore();
    });

    this.queue[viewId] = request;

    request.promise.then(function() {
        // Remove request from queue when done.
        // "All done" check will be done in gotData handler.
        delete that.queue[viewId];

        that.updateView(that.view, request); // Update main page view.
        page_redraw_promise.resolve(); // Resolve main page redraw promise.
    });
};

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

/**
    @param {!Object} obj Target object to go through its properties.
    @param {function} callback A callback, called only on leaf properties (primitive types, !object).
*/
no.Update.walkLeafs = function(obj, callback) {
    no.object.forEach(obj, function(value, key) {
        if (typeof value !== 'object') {
            callback(key, value);
        } else {
            no.Update.walkLeafs(value, callback);
        }
    });
};

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

/**
    @param {no.View|no.Box|string} view View instance or view id, to find it.
*/
no.Update.prototype.updateView = function(view, request) {
    if (typeof view === "string") {
        view = no.View.get(view, this.params);
    }

    var viewsTree = [];
    view.getUpdateTrees(this, viewsTree);

    var tree = {
        models: {},
        params: this.params,
        views: viewsTree,
        location: document.location
    };

    var models = tree.models;

    var groups = request.groups;
    for (var i = 0, l = groups.length; i < l; i++) {
        var group = groups[i];
        for (var j = 0, m = group.models.length; j < m; j++) {
            var model_id = group.models[j];
            models[model_id] = no.Model.get(model_id, group.params).data;
        }
    }

    var html = Yater.run( tree ); // FIXME: Нужно проверять, что update не нужен и ничего не делать.
    var div = document.createElement('div');
    div.innerHTML = html;

    var node = div.firstChild;
    this.updateHtml(view, node);
};

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

/**
    @param {no.View|no.Box} view View / box, which html must be updated.
    @param {Element} node Generated html.
*/
no.Update.prototype.updateHtml = function(view, node) {
    var that = this;
    view.processTree(function(view) {
        if (view.needUpdate(that)) {
            view.update(node, that, true);
            return false;
        }
    });
};

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

no.Update.prototype.requestMore = function() {
    var all_done = true; // this update has nothing more to do.

    no.object.forEach(this.queue, function(request, view_id) {
        if (request.status === "active") { // this request is active, waiting for response.
            all_done = false;
        }

        if (request.send()) { // Could request more models.
            all_done = false;
        }
    });

    if (all_done) {
        no.object.forEach(this.queue, function(request, view_id) {
            // Waiting requests must be terminated.
            if (request.status === "waiting") {
                request.promise.resolve();
            }
        });

        this.trigger("done"); // XXX all rendered?
    }
};

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

no.Update.prototype._createGroup = function(viewId) {
    var info = no.View.info(viewId);
    if (info.models.length === 0) {
        return null;
    }

    return {
        models: info.models,
        params: this.params
    };
};
<|endoftext|>


<commit_before>(function() {
    var childProcess = require("child_process");
    var oldSpawn = childProcess.spawn;
    function mySpawn() {
        console.log('spawn called');
        console.log(arguments);
        var result = oldSpawn.apply(this, arguments);
        return result;
    }
    childProcess.spawn = mySpawn;
})();

var User = require('./models/user');

var express = require('express');
var session = require('express-session');
var vhost = require('vhost');
var app = express();
var router = express.Router();
var qt = require('quickthumb');

var favicon = require('serve-favicon');

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/labeli-api');

var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

app.use(session({
    secret: 'labeliSessionPwordAss',
    resave: true,
    saveUninitialized: true
}));

app.use(function (req, res, next) {
    res.header("Cache-Control", "no-cache");
    res.header("Access-Control-Allow-Origin", "http://localhost:9020");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Credentials", "true");
    res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
    next();
});

app.use(function (req, res, next) {
    console.log("request by " + req.session.userId);

    if (req.session.userId == undefined) {
        req.session.userId = null;
        req.session.level = -1;
    }

    next();
});

app.use(require('./routes/users'));
app.use(require('./routes/projects'));
app.use(require('./routes/auth'));
app.use(require('./routes/messages'));
app.use(require('./routes/votes'));
app.use(require('./routes/projectUsers'));
app.use(require('./routes/surveys'));
app.use(require('./routes/surveyItems'));
app.use(require('./routes/surveyVotes'));
app.use(require('./routes/upload'));

// Use quickthumb
app.use(qt.static(__dirname + '/', { type : 'resize' }));
// Show the upload form
app.get('/uploadAFile', function (req, res) {
    res.writeHead(200, {
        'Content-Type': 'text/html'
    });
    var form = '<form action="/upload" enctype="multipart/form-data" method="post">Add a title: <input name="name" type="text" />

<input multiple="multiple" name="upload" type="file" />

<input type="submit" value="Upload" /></form>';
    res.end(form);
});
app.listen(8080);

// Add doc
app.use("/", express.static("./doc/"));

// Add favicon
app.use(favicon(__dirname + "/styles/favicon.ico"));

app.use(router);
app.listen(9010);
<commit_msg>Last try to rotate pictures from qt<commit_after>(function() {
    var childProcess = require("child_process");
    var oldSpawn = childProcess.spawn;
    function mySpawn() {
        console.log('spawn called');
        console.log(arguments);
        var result = oldSpawn.apply(this, arguments);
        return result;
    }
    childProcess.spawn = mySpawn;
})();

var User = require('./models/user');

var express = require('express');
var session = require('express-session');
var vhost = require('vhost');
var app = express();
var router = express.Router();
var qt = require('quickthumb');

var favicon = require('serve-favicon');

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/labeli-api');

var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

app.use(session({
    secret: 'labeliSessionPwordAss',
    resave: true,
    saveUninitialized: true
}));

app.use(function (req, res, next) {
    res.header("Cache-Control", "no-cache");
    res.header("Access-Control-Allow-Origin", "http://localhost:9020");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Credentials", "true");
    res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
    next();
});

app.use(function (req, res, next) {
    console.log("request by " + req.session.userId);

    if (req.session.userId == undefined) {
        req.session.userId = null;
        req.session.level = -1;
    }

    next();
});

app.use(require('./routes/users'));
app.use(require('./routes/projects'));
app.use(require('./routes/auth'));
app.use(require('./routes/messages'));
app.use(require('./routes/votes'));
app.use(require('./routes/projectUsers'));
app.use(require('./routes/surveys'));
app.use(require('./routes/surveyItems'));
app.use(require('./routes/surveyVotes'));
app.use(require('./routes/upload'));

// Use quickthumb
app.use(qt.static(__dirname + '/', { type : 'resize' ,}));
// Show the upload form
app.get('/uploadAFile', function (req, res) {
    res.writeHead(200, {
        'Content-Type': 'text/html'
    });
    var form = '<form action="/upload" enctype="multipart/form-data" method="post">Add a title: <input name="name" type="text" />

<input multiple="multiple" name="upload" type="file" />

<input type="submit" value="Upload" /></form>';
    res.end(form);
});
app.listen(8080);

// Add doc
app.use("/", express.static("./doc/"));

// Add favicon
app.use(favicon(__dirname + "/styles/favicon.ico"));

app.use(router);
app.listen(9010);
<|endoftext|>


<commit_before><commit_msg>empty file?<commit_after><|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc filter
 * @name orderBy
 * @kind function
 *
 * @description
 * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
 * for strings and numerically for numbers. Note: if you notice numbers are not being sorted
 * correctly, make sure they are actually being saved as numbers and not strings.
 *
 * @param {Array} array The array to sort.
 * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
 *    used by the comparator to determine the order of elements.
 *
 *    Can be one of:
 *
 *    - `function`: Getter function. The result of this function will be sorted using the
 *      `<`, `=`, `>` operator.
 *    - `string`: An Angular expression. The result of this expression is used to compare elements
 *      (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
 *      3 first characters of a property called `name`). The result of a constant expression
 *      is interpreted as a property name to be used in comparisons (for example `"special name"`
 *      to sort object by the value of their `special name` property). An expression can be
 *      optionally prefixed with `+` or `-` to control ascending or descending sort order
 *      (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
 *      element itself is used to compare where sorting.
 *    - `Array`: An array of function or string predicates. The first predicate in the array
 *      is used for sorting, but when two items are equivalent, the next predicate is used.
 *
 *    If the predicate is missing or empty then it defaults to `'+'`.
 *
 * @param {boolean=} reverse Reverse the order of the array.
 * @returns {Array} Sorted copy of the source array.
 *
 * @example
   <example module="orderByExample">
     <file name="index.html">

Sorting predicate = {{predicate}}; reverse = {{reverse}}

         [ unsorted ]

             Name
                 (^)
             Phone Number
             Age

             {{friend.name}}
             {{friend.phone}}
             {{friend.age}}

     </file>
   </example>
 *
 * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
 * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
 * desired parameters.
 *
 * Example:
 *
 * @example
  <example module="orderByExample">
    <file name="index.html">

            Name
              (^)
            Phone Number
            Age

            {{friend.name}}
            {{friend.phone}}
            {{friend.age}}

    </file>

    <file name="script.js">
      angular.module('orderByExample', [])
        .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
          var orderBy = $filter('orderBy');
          $scope.friends = [
            { name: 'John',    phone: '555-1212',    age: 10 },
            { name: 'Mary',    phone: '555-9876',    age: 19 },
            { name: 'Mike',    phone: '555-4321',    age: 21 },
            { name: 'Adam',    phone: '555-5678',    age: 35 },
            { name: 'Julie',   phone: '555-8765',    age: 29 }
          ];
          $scope.order = function(predicate, reverse) {
            $scope.friends = orderBy($scope.friends, predicate, reverse);
          };
          $scope.order('-age',false);
        }]);
    </file>
</example>
 */
orderByFilter.$inject = ['$parse'];
function orderByFilter($parse) {
  return function(array, sortPredicate, reverseOrder) {
    if (!(isArrayLike(array))) return array;
    sortPredicate = isArray(sortPredicate) ? sortPredicate : [sortPredicate];
    if (sortPredicate.length === 0) { sortPredicate = ['+']; }
    sortPredicate = sortPredicate.map(function(predicate) {
      var descending = false, get = predicate || identity;
      if (isString(predicate)) {
        if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
          descending = predicate.charAt(0) == '-';
          predicate = predicate.substring(1);
        }
        if (predicate === '') {
          // Effectively no predicate was passed so we compare identity
          return reverseComparator(function(a, b) {
            return compare(a, b);
          }, descending);
        }
        get = $parse(predicate);
        if (get.constant) {
          var key = get();
          return reverseComparator(function(a, b) {
            return compare(a[key], b[key]);
          }, descending);
        }
      }
      return reverseComparator(function(a, b) {
        return compare(get(a),get(b));
      }, descending);
    });
    return slice.call(array).sort(reverseComparator(comparator, reverseOrder));

    function comparator(o1, o2) {
      for (var i = 0; i < sortPredicate.length; i++) {
        var comp = sortPredicate[i](o1, o2);
        if (comp !== 0) return comp;
      }
      return 0;
    }
    function reverseComparator(comp, descending) {
      return descending
          ? function(a, b) {return comp(b,a);}
          : comp;
    }

    function isPrimitive(value) {
      switch (typeof value) {
        case 'number': /* falls through */
        case 'boolean': /* falls through */
        case 'string':
          return true;
        default:
          return false;
      }
    }

    function objectToString(value) {
      if (value === null) return 'null';
      if (typeof value.toString === 'function') {
        value = value.toString();
        if (isPrimitive(value)) return value;
      }
      if (typeof value.valueOf === 'function') {
        value = value.valueOf();
        if (isPrimitive(value)) return value;
      }
      return '';
    }

    function compare(v1, v2) {
      var t1 = typeof v1;
      var t2 = typeof v2;
      if (t1 === t2 && t1 === "object") {
        v1 = objectToString(v1);
        v2 = objectToString(v2);
      }
      if (t1 === t2) {
        if (t1 === "string") {
           v1 = v1.toLowerCase();
           v2 = v2.toLowerCase();
        }
        if (v1 === v2) return 0;
        return v1 < v2 ? -1 : 1;
      } else {
        return t1 < t2 ? -1 : 1;
      }
    }
  };
}
<commit_msg>refactor(orderBy): remove unneeded function wrapping<commit_after>'use strict';

/**
 * @ngdoc filter
 * @name orderBy
 * @kind function
 *
 * @description
 * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
 * for strings and numerically for numbers. Note: if you notice numbers are not being sorted
 * correctly, make sure they are actually being saved as numbers and not strings.
 *
 * @param {Array} array The array to sort.
 * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
 *    used by the comparator to determine the order of elements.
 *
 *    Can be one of:
 *
 *    - `function`: Getter function. The result of this function will be sorted using the
 *      `<`, `=`, `>` operator.
 *    - `string`: An Angular expression. The result of this expression is used to compare elements
 *      (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
 *      3 first characters of a property called `name`). The result of a constant expression
 *      is interpreted as a property name to be used in comparisons (for example `"special name"`
 *      to sort object by the value of their `special name` property). An expression can be
 *      optionally prefixed with `+` or `-` to control ascending or descending sort order
 *      (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
 *      element itself is used to compare where sorting.
 *    - `Array`: An array of function or string predicates. The first predicate in the array
 *      is used for sorting, but when two items are equivalent, the next predicate is used.
 *
 *    If the predicate is missing or empty then it defaults to `'+'`.
 *
 * @param {boolean=} reverse Reverse the order of the array.
 * @returns {Array} Sorted copy of the source array.
 *
 * @example
   <example module="orderByExample">
     <file name="index.html">

Sorting predicate = {{predicate}}; reverse = {{reverse}}

         [ unsorted ]

             Name
                 (^)
             Phone Number
             Age

             {{friend.name}}
             {{friend.phone}}
             {{friend.age}}

     </file>
   </example>
 *
 * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
 * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
 * desired parameters.
 *
 * Example:
 *
 * @example
  <example module="orderByExample">
    <file name="index.html">

            Name
              (^)
            Phone Number
            Age

            {{friend.name}}
            {{friend.phone}}
            {{friend.age}}

    </file>

    <file name="script.js">
      angular.module('orderByExample', [])
        .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
          var orderBy = $filter('orderBy');
          $scope.friends = [
            { name: 'John',    phone: '555-1212',    age: 10 },
            { name: 'Mary',    phone: '555-9876',    age: 19 },
            { name: 'Mike',    phone: '555-4321',    age: 21 },
            { name: 'Adam',    phone: '555-5678',    age: 35 },
            { name: 'Julie',   phone: '555-8765',    age: 29 }
          ];
          $scope.order = function(predicate, reverse) {
            $scope.friends = orderBy($scope.friends, predicate, reverse);
          };
          $scope.order('-age',false);
        }]);
    </file>
</example>
 */
orderByFilter.$inject = ['$parse'];
function orderByFilter($parse) {
  return function(array, sortPredicate, reverseOrder) {
    if (!(isArrayLike(array))) return array;
    sortPredicate = isArray(sortPredicate) ? sortPredicate : [sortPredicate];
    if (sortPredicate.length === 0) { sortPredicate = ['+']; }
    sortPredicate = sortPredicate.map(function(predicate) {
      var descending = false, get = predicate || identity;
      if (isString(predicate)) {
        if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
          descending = predicate.charAt(0) == '-';
          predicate = predicate.substring(1);
        }
        if (predicate === '') {
          // Effectively no predicate was passed so we compare identity
          return reverseComparator(compare, descending);
        }
        get = $parse(predicate);
        if (get.constant) {
          var key = get();
          return reverseComparator(function(a, b) {
            return compare(a[key], b[key]);
          }, descending);
        }
      }
      return reverseComparator(function(a, b) {
        return compare(get(a),get(b));
      }, descending);
    });
    return slice.call(array).sort(reverseComparator(comparator, reverseOrder));

    function comparator(o1, o2) {
      for (var i = 0; i < sortPredicate.length; i++) {
        var comp = sortPredicate[i](o1, o2);
        if (comp !== 0) return comp;
      }
      return 0;
    }
    function reverseComparator(comp, descending) {
      return descending
          ? function(a, b) {return comp(b,a);}
          : comp;
    }

    function isPrimitive(value) {
      switch (typeof value) {
        case 'number': /* falls through */
        case 'boolean': /* falls through */
        case 'string':
          return true;
        default:
          return false;
      }
    }

    function objectToString(value) {
      if (value === null) return 'null';
      if (typeof value.toString === 'function') {
        value = value.toString();
        if (isPrimitive(value)) return value;
      }
      if (typeof value.valueOf === 'function') {
        value = value.valueOf();
        if (isPrimitive(value)) return value;
      }
      return '';
    }

    function compare(v1, v2) {
      var t1 = typeof v1;
      var t2 = typeof v2;
      if (t1 === t2 && t1 === "object") {
        v1 = objectToString(v1);
        v2 = objectToString(v2);
      }
      if (t1 === t2) {
        if (t1 === "string") {
           v1 = v1.toLowerCase();
           v2 = v2.toLowerCase();
        }
        if (v1 === v2) return 0;
        return v1 < v2 ? -1 : 1;
      } else {
        return t1 < t2 ? -1 : 1;
      }
    }
  };
}
<|endoftext|>


<commit_before>import * as types from './usersActionTypes';

export const users = (state = {}, action) => {
  switch(action.type) {
    case types.USER_LOGGED_IN:
      const { uid, email, photoURL, displayName, lastTimeLoggedIn } = action;

      return {
        ...state,
        [uid]: {
          email,
          photoURL ,
          displayName,
          lastTimeLoggedIn
        }
      };
    default:
      return state;
  }
};
<commit_msg>store all the user payload instead of individual fields<commit_after>import * as types from './usersActionTypes';

export const users = (state = {}, action) => {
  switch(action.type) {
    case types.USER_LOGGED_IN:
      const { uid, userPayload } = action;

      return {
        ...state,
        [uid]: {
          ...userPayload
        }
      };
    default:
      return state;
  }
};
<|endoftext|>


<commit_before>var http = require('http');
var https = require('https');
var net = require('net');
var sys = require('sys');
var fs = require('fs');
var logger = require('util');
var _ = require('underscore')._;
var settings = require('./settings').create();
var EventEmitter = require('events').EventEmitter;
var controller = new EventEmitter();
module.exports = controller;

var status = {};
status.last = new Date().toGMTString();
status.services = [];

updatingServices = function() {
  status.lastupdate = new Date().toUTCString();
  logger.log('Refreshing status board...');
  for (var i = 0; i < settings.services.length; i++) {
    status.services[i] = {};
    status.services[i].name = settings.services[i].name;
    status.services[i].label = settings.services[i].label;
    status.services[i].status = 'unknown';
    status.services[i].statusCode = 0;
    status.services[i].message = '';
    commands[settings.services[i].check].call(null, settings.services[i], status.services[i]);
  }
  setTimeout(function() {
    var statusTab = _.map(status.services, function(value, key) { return value; });
    status.summarize = {};
    status.summarize.lastupdate = status.lastupdate;
    status.summarize.up = _.reduce(_.select(status.services, function(data){ return data.status == 'up'; }), function(memo, num){ return memo + 1; }, 0);
    status.summarize.critical = _.reduce(_.select(status.services, function(data){ return data.status == 'critical'; }), function(memo, num){ return memo + 1; }, 0);
    status.summarize.down = _.reduce(_.select(status.services, function(data){ return data.status == 'down'; }), function(memo, num){ return memo + 1; }, 0);
    status.summarize.unknown = _.reduce(_.select(status.services, function(data){ return data.status == 'unknown'; }), function(memo, num){ return memo + 1; }, 0);

    controller.emit("refresh", status);
  }, settings.serviceDelay);
};

var commands = {
  http : function(serviceDefinition, service) {
    var options = {
      host: serviceDefinition.host,
      port: serviceDefinition.port,
      path: serviceDefinition.path,
      headers: serviceDefinition.headers
    };

    http.get(options, function(response) {
      service.message = '';
      if (response.statusCode == 200) {
        service.status = "up";
      } else if (response.statusCode == 301 || response.statusCode == 302) {
        service.status = "unknown";
        service.message = "Redirected to " + response.headers.location;
      } else if (response.statusCode == 503 || response.statusCode == 404) {
        service.status = "down";
      } else {
        service.status = "critical";
      }
      service.statusCode = response.statusCode;
    })
    .on('error', function(e) {
      service.status = "down";
      service.statusCode = 0;
      service.message = e.message;
    });
  },
  https : function(serviceDefinition, service) {
    var options = {
      host: serviceDefinition.host,
      port: serviceDefinition.port,
      path: serviceDefinition.path,
    };

    https.get(options, function(response) {
      service.message = '';
        if (response.statusCode == 200) {
          service.status = "up";
        } else if (response.statusCode == 301 || response.statusCode == 302) {
          service.status = "unknown";
          service.message = "Redirected to " + response.headers.location;
        } else if (response.statusCode == 503 || response.statusCode == 404) {
          service.status = "down";
        } else {
          service.status = "critical";
        }
      service.statusCode = response.statusCode;
    })
    .on('error', function(e) {
      service.status = "down";
      service.statusCode = 0;
      service.message = e.message;
    });
  },
  tcp : function(serviceDefinition, service) {
    var stream = net.createConnection(serviceDefinition.port, serviceDefinition.host);
    stream.addListener('data', function (buffer) {
      service.status = "up";
      service.statusCode = 0;
      service.message = "";
      stream.end();
    });
    stream.addListener('connect', function () {
      stream.write(serviceDefinition.cmd);
    });
    stream.addListener('end', function () {
      stream.end();
    });
    stream.addListener('error', function (e) {
      service.status = "down";
      service.statusCode = e.errno;
      service.message = e.message;
    });
  },
  ftp : function(serviceDefinition, service) {
    service.status = "unknown";
    service.statusCode = 0;
    service.message = 'FTP check in progress...';

    var stream = net.createConnection(serviceDefinition.port, serviceDefinition.host);

    stream.addListener('connect', function () {
      var ftpCommand = function(command, callback) {
        stream.write(command + '\r\n');
        var dataCallback = function(data) {
          stream.removeListener('data', dataCallback);
          var status = data.toString().match(/^\d\d\d/);
          if (parseInt(status[0]) > 399) {
            ftpError(status[0], data.toString());
          } else {
            return callback(data);
          }
        };
        stream.addListener('data', dataCallback);
      };

      ftpCommand('USER ' + service.username, function(data) {
        ftpCommand('PASS ' + service.password, function(data) {
          service.status = "up";
          service.statusCode = 0;
          service.message = "";
        });
      });
    });

    var ftpError = function(status, message) {
      service.status = "down";
      service.statusCode = status;
      service.message = message;
    };

    stream.addListener('error', function (e) {
      service.status = "down";
      service.statusCode = 0;
      service.message = e.message;
    });

  },
  pidfile : function(serviceDefinition, service) {
    service.status = "unknown";
    service.statusCode = 0;
    service.message = '';
    try {
      var pid = fs.readFileSync(serviceDefinition.pidfile);
    } catch (e) {
      service.status = "unknown";
      service.statusCode = e.errno;
      service.message = e.message;
      return;
    }
    try {
      process.kill(pid, 0);
      service.status = "up";
      service.statusCode = 0;
      service.message = '';
    } catch (e) {
      service.status = "down";
      service.statusCode = e.errno;
      service.message = e.message;
      return;
    }
  }
};

setInterval(updatingServices, settings.serviceInterval);
updatingServices();

module.exports.services = function(req, res) {
  res.send(200, {}, JSON.stringify(status));
};

module.exports.servicesElement = function(req, res, value) {
  res.send(200, {}, JSON.stringify(_.first(_.select(status.services, function(data){ return data.name == value; }))));
};

module.exports.summarize = function(req, res) {
  res.send(200, {}, { up: status.summarize.up, critical: status.summarize.critical, down: status.summarize.down, unknown: status.summarize.unknown });
};

exports.getServicesElement = function(value) {
  return status.services[value];
};

module.exports.getStatus = function() {
  return status;
};

<commit_msg>Cleaning last update<commit_after>var http = require('http');
var https = require('https');
var net = require('net');
var sys = require('sys');
var fs = require('fs');
var logger = require('util');
var _ = require('underscore')._;
var settings = require('./settings').create();
var EventEmitter = require('events').EventEmitter;
var controller = new EventEmitter();
module.exports = controller;

var status = {};
status.lastupdate = new Date().toGMTString();
status.services = [];

updatingServices = function() {
  status.lastupdate = new Date().toUTCString();
  logger.log('Refreshing status board...');
  for (var i = 0; i < settings.services.length; i++) {
    status.services[i] = {};
    status.services[i].name = settings.services[i].name;
    status.services[i].label = settings.services[i].label;
    status.services[i].status = 'unknown';
    status.services[i].statusCode = 0;
    status.services[i].message = '';
    commands[settings.services[i].check].call(null, settings.services[i], status.services[i]);
  }
  setTimeout(function() {
    var statusTab = _.map(status.services, function(value, key) { return value; });
    status.summarize = {};
    status.summarize.lastupdate = status.lastupdate;
    status.summarize.up = _.reduce(_.select(status.services, function(data){ return data.status == 'up'; }), function(memo, num){ return memo + 1; }, 0);
    status.summarize.critical = _.reduce(_.select(status.services, function(data){ return data.status == 'critical'; }), function(memo, num){ return memo + 1; }, 0);
    status.summarize.down = _.reduce(_.select(status.services, function(data){ return data.status == 'down'; }), function(memo, num){ return memo + 1; }, 0);
    status.summarize.unknown = _.reduce(_.select(status.services, function(data){ return data.status == 'unknown'; }), function(memo, num){ return memo + 1; }, 0);

    controller.emit("refresh", status);
  }, settings.serviceDelay);
};

var commands = {
  http : function(serviceDefinition, service) {
    var options = {
      host: serviceDefinition.host,
      port: serviceDefinition.port,
      path: serviceDefinition.path,
      headers: serviceDefinition.headers
    };

    http.get(options, function(response) {
      service.message = '';
      if (response.statusCode == 200) {
        service.status = "up";
      } else if (response.statusCode == 301 || response.statusCode == 302) {
        service.status = "unknown";
        service.message = "Redirected to " + response.headers.location;
      } else if (response.statusCode == 503 || response.statusCode == 404) {
        service.status = "down";
      } else {
        service.status = "critical";
      }
      service.statusCode = response.statusCode;
    })
    .on('error', function(e) {
      service.status = "down";
      service.statusCode = 0;
      service.message = e.message;
    });
  },
  https : function(serviceDefinition, service) {
    var options = {
      host: serviceDefinition.host,
      port: serviceDefinition.port,
      path: serviceDefinition.path,
    };

    https.get(options, function(response) {
      service.message = '';
        if (response.statusCode == 200) {
          service.status = "up";
        } else if (response.statusCode == 301 || response.statusCode == 302) {
          service.status = "unknown";
          service.message = "Redirected to " + response.headers.location;
        } else if (response.statusCode == 503 || response.statusCode == 404) {
          service.status = "down";
        } else {
          service.status = "critical";
        }
      service.statusCode = response.statusCode;
    })
    .on('error', function(e) {
      service.status = "down";
      service.statusCode = 0;
      service.message = e.message;
    });
  },
  tcp : function(serviceDefinition, service) {
    var stream = net.createConnection(serviceDefinition.port, serviceDefinition.host);
    stream.addListener('data', function (buffer) {
      service.status = "up";
      service.statusCode = 0;
      service.message = "";
      stream.end();
    });
    stream.addListener('connect', function () {
      stream.write(serviceDefinition.cmd);
    });
    stream.addListener('end', function () {
      stream.end();
    });
    stream.addListener('error', function (e) {
      service.status = "down";
      service.statusCode = e.errno;
      service.message = e.message;
    });
  },
  ftp : function(serviceDefinition, service) {
    service.status = "unknown";
    service.statusCode = 0;
    service.message = 'FTP check in progress...';

    var stream = net.createConnection(serviceDefinition.port, serviceDefinition.host);

    stream.addListener('connect', function () {
      var ftpCommand = function(command, callback) {
        stream.write(command + '\r\n');
        var dataCallback = function(data) {
          stream.removeListener('data', dataCallback);
          var status = data.toString().match(/^\d\d\d/);
          if (parseInt(status[0]) > 399) {
            ftpError(status[0], data.toString());
          } else {
            return callback(data);
          }
        };
        stream.addListener('data', dataCallback);
      };

      ftpCommand('USER ' + service.username, function(data) {
        ftpCommand('PASS ' + service.password, function(data) {
          service.status = "up";
          service.statusCode = 0;
          service.message = "";
        });
      });
    });

    var ftpError = function(status, message) {
      service.status = "down";
      service.statusCode = status;
      service.message = message;
    };

    stream.addListener('error', function (e) {
      service.status = "down";
      service.statusCode = 0;
      service.message = e.message;
    });

  },
  pidfile : function(serviceDefinition, service) {
    service.status = "unknown";
    service.statusCode = 0;
    service.message = '';
    try {
      var pid = fs.readFileSync(serviceDefinition.pidfile);
    } catch (e) {
      service.status = "unknown";
      service.statusCode = e.errno;
      service.message = e.message;
      return;
    }
    try {
      process.kill(pid, 0);
      service.status = "up";
      service.statusCode = 0;
      service.message = '';
    } catch (e) {
      service.status = "down";
      service.statusCode = e.errno;
      service.message = e.message;
      return;
    }
  }
};

setInterval(updatingServices, settings.serviceInterval);
updatingServices();

module.exports.services = function(req, res) {
  res.send(200, {}, JSON.stringify(status));
};

module.exports.servicesElement = function(req, res, value) {
  res.send(200, {}, JSON.stringify(_.first(_.select(status.services, function(data){ return data.name == value; }))));
};

module.exports.summarize = function(req, res) {
  res.send(200, {}, { up: status.summarize.up, critical: status.summarize.critical, down: status.summarize.down, unknown: status.summarize.unknown });
};

exports.getServicesElement = function(value) {
  return status.services[value];
};

module.exports.getStatus = function() {
  return status;
};

<|endoftext|>


<commit_before>importScripts('workbox-sw.prod.js')

const workboxSW = new WorkboxSW({ clientsClaim: true })

workboxSW.precache([])

workboxSW.router.registerRoute(
  'https://minnerwa.github.io/reddit-vuetifyjs/(.*)',
  workboxSW.strategies.networkFirst({networkTimeoutSeconds: 3})
)

importScripts('https://unpkg.com/workbox-routing@0.0.2/build/importScripts/workbox-routing.dev.v0.0.2.js');

const router = new workbox.routing.Router()
const crossOriginExpressRoute = new workbox.routing.ExpressRoute({
  path: 'https://www.reddit.com/r/(.*)',
  handler: ({ event }) => {
    return fetch(event.request)
  }
})
<commit_msg>:bug: fix ajax sw<commit_after>importScripts('workbox-sw.prod.js')

const workboxSW = new WorkboxSW({ clientsClaim: true })

workboxSW.precache([])

workboxSW.router.registerRoute(
  'https://minnerwa.github.io/reddit-vuetifyjs/(.*)',
  workboxSW.strategies.networkFirst({networkTimeoutSeconds: 3})
)

importScripts('https://unpkg.com/workbox-routing@0.0.2/build/importScripts/workbox-routing.dev.v0.0.2.js');

const router = new workbox.routing.Router()
const crossOriginExpressRoute = new workbox.routing.ExpressRoute({
  path: 'https://www.reddit.com/r/(.*)',
  handler: ({ event }) => {
    return fetch(event.request)
  }
})

router.registerRoutes({
  routes: [crossOriginExpressRoute],
})

self.addEventListener('install', () => self.skipWaiting())
self.addEventListener('activate', () => self.clients.claim())
<|endoftext|>


<commit_before>var Emitter = require('component-emitter')
var wpi = require('wiring-pi')
var brickpi = require('brickpi-raspberry-watch')

var robot = new brickpi.BrickPi({pollingInterval: 100})
var touchSensors = [1, 2, 3, 4].map(function (num) {
  return { port: brickpi.PORTS['S' + num], type: brickpi.SENSOR_TYPE.NXT.TOUCH }
})
touchSensors.forEach(function (sensor) { robot.addSensor(sensor) })
robot.setup()
robot.run()

var messages = exports.messages = new Emitter()

exports.light_toggle = light_toggle
exports.sensor_subscribe = sensor_subscribe
exports.sensor_unsubscribe = sensor_unsubscribe

function sensor_subscribe (data, cb) {
  var port = data.port
  touchSensors[port].on('change', function (value) {
    messages.emit(data.socketId, value)
    lightToggle({port: port})
  })
  cb(null)
}

function sensor_unsubscribe (data, cb) {
  var port = data.port
  touchSensors[port].off('change')
  cb(null)
}

function lightToggle (data, cb) {
  cb = cb || function () {}
  var port = data.port
  wpi.pinMode(port, wpi.OUTPUT)
  wpi.digitalRead(port) ? wpi.digitalWrite(port, wpi.LOW) : wpi.digitalWrite(port, wpi.HIGH)
  cb(null)
}
<commit_msg>robot on ready<commit_after>var Emitter = require('component-emitter')
var wpi = require('wiring-pi')
var brickpi = require('brickpi-raspberry-watch')

var robot = new brickpi.BrickPi({pollingInterval: 100})
var touchSensors = [1, 2, 3, 4].map(function (num) {
  return { port: brickpi.PORTS['S' + num], type: brickpi.SENSOR_TYPE.NXT.TOUCH }
})
touchSensors.forEach(function (sensor) { robot.addSensor(sensor) })
robot.setup()
robot.on('ready', function () {
  robot.run()
})

var messages = exports.messages = new Emitter()

exports.light_toggle = light_toggle
exports.sensor_subscribe = sensor_subscribe
exports.sensor_unsubscribe = sensor_unsubscribe

function sensor_subscribe (data, cb) {
  var port = data.port
  touchSensors[port].on('change', function (value) {
    messages.emit(data.socketId, value)
    lightToggle({port: port})
  })
  cb(null)
}

function sensor_unsubscribe (data, cb) {
  var port = data.port
  touchSensors[port].off('change')
  cb(null)
}

function lightToggle (data, cb) {
  cb = cb || function () {}
  var port = data.port
  wpi.pinMode(port, wpi.OUTPUT)
  wpi.digitalRead(port) ? wpi.digitalWrite(port, wpi.LOW) : wpi.digitalWrite(port, wpi.HIGH)
  cb(null)
}
<|endoftext|>


<commit_before>/**
 * Helper module with useful methods used throughout newman
 */

var jsface = require('jsface');

var Helpers = jsface.Class({
    $singleton: true,
    isValidUrl: function(url) {
        return false;
    }
});

module.exports = Helpers;
<commit_msg>Filled the isValidURL stub with simple regex"<commit_after>/**
 * Helper module with useful methods used throughout Newman
 */

var jsface = require('jsface');

var Helpers = jsface.Class({
    $singleton: true,
    isValidUrl: function(url) {
        // basic sanity check to validate url structure
        var result = url.match(/(https|http):\/\/([_a-z\d\-]+(\.[_a-z\d\-]+)+)(([_a-z\d\-\\\.\/]+[_a-z\d\-\\\/])+)*/);
        return result !== null;
    }
});

module.exports = Helpers;
<|endoftext|>


<commit_before>'use strict';

//# Initialization Wizard

//** Setup dependencies
var inquirer = require('inquirer'),
     install = require('./install'),
           _ = require('lodash');

//* Callback must be in the form `function(results)`
module.exports = function(options, indexCb) {

  function required(value) {
    return !!value.trim() || 'Required';
  }

  var questions = [{
    type: 'input',
    name: 'name',
    message: 'What would you have your MEAN app be called?',
    default: options.name,
    validate: required
  }];

  inquirer.prompt(questions, function(results) {
    console.log('');
    _.assign(options, results);
    install.init(options, indexCb);
  })
}
<commit_msg>docs(wizard): add lodash reference<commit_after>'use strict';

//# Initialization Wizard

//** Setup dependencies
var inquirer = require('inquirer'),
     install = require('./install'),
           _ = require('lodash');

//* Callback must be in the form `function(results)`
module.exports = function(options, indexCb) {

  function required(value) {
    return !!value.trim() || 'Required';
  }

  var questions = [{
    type: 'input',
    name: 'name',
    message: 'What would you have your MEAN app be called?',
    default: options.name,
    validate: required
  }];

  inquirer.prompt(questions, function(results) {
    console.log('');
    // Reference: https://lodash.com/docs#assign
    _.assign(options, results);
    install.init(options, indexCb);
  })
}
<|endoftext|>


<commit_before>var form_str = document.getElementById('search_str');
var sform = document.getElementById('search_form');
var sresults = document.getElementById('search_results');

function highlight(type) {
	str = '';

	var lex = {
		start: [
			[/^(\s+)(.*)/, ['whitespace']],
			[/^(.+)(::.*)/, ['funcname'], 'type']
		],
		type: [
			[/^(\s+)(.*)/, ['whitespace']],
			[/^([a-z]+)(.*)/, ['typevar']],
			[/^([A-Z]\w*)(.*)/, ['type']],
			[/^(\/\/.*)(.*?)/, ['comment']],
			[/^(\|)(.*)/, ['punctuation'], 'context'],
			[/^(\W)(.*)/, ['punctuation']]
		],
		context: [
			[/^(\s+)(.*)/, ['whitespace']],
			[/^(\/\/.*)(.*?)/, ['comment']],
			[/^(\S+)(.*)/, ['classname'], 'contextType']
		],
		contextType: [
			[/^(\s+)(.*)/, ['whitespace']],
			[/^(\/\/.*)(.*?)/, ['comment']],
			[/^([,&])(.*)/, ['punctuation'], 'context'],
			[/^([^\s,]+)(.*)/, ['typevar']]
		]
	};

	state = 'start';
	while (true) {
		var found = false;
		for (i in lex[state]) {
			patt = lex[state][i][0];
			clss = lex[state][i][1];
			if (type.match(patt)) {
				parts = patt.exec(type);
				var j = 0;
				for (k in clss) {
					j = parseInt(k)+1;
					str += '' + parts[j] + '';
				}
				type = parts[j+1];

				found = true;
				if (lex[state][i].length > 2)
					state = lex[state][i][2];

				break;
			}
		}
		if (!found || type == '')
			return str;
	}
}

function formsubmit(){
	if(form_str.value === ''){
		sresults.innerHTML = 'Can\'t search for the empty string';
	} else {
		sresults.innerHTML = 'Proccessing...';
		var str = encodeURIComponent(form_str.value);
		var url = 'api.php?str=' + str;
		console.log('Apicall: ' + url);
		var xmlHttp = new XMLHttpRequest();
		xmlHttp.onreadystatechange = function() {
			if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
				console.log('Response: ' + xmlHttp.responseText);
				var responsedata = JSON.parse(xmlHttp.responseText);
				sresults.innerHTML =
					'
Return code: ' + responsedata['return'] + '
' +
					'
Message: ' + responsedata['msg'] + '
';
				if(responsedata['return'] === 0){
					for(var i = 0; i<responsedata['data'].length; i++){
						var c = responsedata['data'][i];
						sresults.innerHTML += '

' +
							'
Library: 	' + c['library'] + '
' +
							'
Filename: 	' + c['filename'] + '
' +
							'
Module: 	' + c['module'] + '	' +
							'' + c['distance'] + '
' +
							'
' +
							'' + highlight(c['func']) + '';
					}
				}
			}
		};
		xmlHttp.open('GET', url, true); // true for asynchronous
		xmlHttp.send(null);
		document.location.hash = "#" + str;
	}
	return false;
};

window.onload = function(){
	sform.onsubmit = formsubmit;
	var str = document.location.hash;
	if(str !== ''){
		str = str.substring(1);
		console.log('Detected hash, setting searchstring to ' + str);
		form_str.value = str;
		formsubmit();
	}
}
<commit_msg>Removed console.log calls, focus input on load<commit_after>var form_str = document.getElementById('search_str');
var sform = document.getElementById('search_form');
var sresults = document.getElementById('search_results');

function highlight(type) {
	str = '';

	var lex = {
		start: [
			[/^(\s+)(.*)/, ['whitespace']],
			[/^(.+)(::.*)/, ['funcname'], 'type']
		],
		type: [
			[/^(\s+)(.*)/, ['whitespace']],
			[/^([a-z]+)(.*)/, ['typevar']],
			[/^([A-Z]\w*)(.*)/, ['type']],
			[/^(\/\/.*)(.*?)/, ['comment']],
			[/^(\|)(.*)/, ['punctuation'], 'context'],
			[/^(\W)(.*)/, ['punctuation']]
		],
		context: [
			[/^(\s+)(.*)/, ['whitespace']],
			[/^(\/\/.*)(.*?)/, ['comment']],
			[/^(\S+)(.*)/, ['classname'], 'contextType']
		],
		contextType: [
			[/^(\s+)(.*)/, ['whitespace']],
			[/^(\/\/.*)(.*?)/, ['comment']],
			[/^([,&])(.*)/, ['punctuation'], 'context'],
			[/^([^\s,]+)(.*)/, ['typevar']]
		]
	};

	state = 'start';
	while (true) {
		var found = false;
		for (i in lex[state]) {
			patt = lex[state][i][0];
			clss = lex[state][i][1];
			if (type.match(patt)) {
				parts = patt.exec(type);
				var j = 0;
				for (k in clss) {
					j = parseInt(k)+1;
					str += '' + parts[j] + '';
				}
				type = parts[j+1];

				found = true;
				if (lex[state][i].length > 2)
					state = lex[state][i][2];

				break;
			}
		}
		if (!found || type == '')
			return str;
	}
}

function formsubmit(){
	if(form_str.value === ''){
		sresults.innerHTML = 'Can\'t search for the empty string';
	} else {
		sresults.innerHTML = 'Proccessing...';
		var str = encodeURIComponent(form_str.value);
		var url = 'api.php?str=' + str;
		var xmlHttp = new XMLHttpRequest();
		xmlHttp.onreadystatechange = function() {
			if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
				var responsedata = JSON.parse(xmlHttp.responseText);
				sresults.innerHTML =
					'
Return code: ' + responsedata['return'] + '
' +
					'
Message: ' + responsedata['msg'] + '
';
				if(responsedata['return'] === 0){
					for(var i = 0; i<responsedata['data'].length; i++){
						var c = responsedata['data'][i];
						sresults.innerHTML += '

' +
							'
Library: 	' + c['library'] + '
' +
							'
Filename: 	' + c['filename'] + '
' +
							'
Module: 	' + c['module'] + '	' +
							'' + c['distance'] + '
' +
							'
' +
							'' + highlight(c['func']) + '';
					}
				}
			}
		};
		xmlHttp.open('GET', url, true); // true for asynchronous
		xmlHttp.send(null);
		document.location.hash = "#" + str;
	}
	return false;
};

window.onload = function(){
	sform.onsubmit = formsubmit;
	var str = document.location.hash;
	if(str !== ''){
		str = str.substring(1);
		form_str.value = str;
		formsubmit();
	}

	document.getElementById('search_str').focus();
}
<|endoftext|>


<commit_before>var paths = require('../paths');

var Scheduler = require(paths.lib + 'scheduler');
var Task = require(paths.lib + 'task');
var jobs = require(paths.jobs);
var Logger = require('./logger');
var moment = require('moment');
/**
	@class Worker
	@extends Scheduler
	@extends Db
*/
var Worker = function(name){
	Scheduler.apply(this,arguments);

	/** @private **/
	var _self = this;
	var logger = '';

	/** @public **/
	this.name = name;

	/** @public **/
	this.createTask = function(hash){

		if(!hash) return false;

		var _worker = this;

		// Instance of tasks to be configured
		var task  = new Task(hash);

		// Add method to execute job
		task.execute = jobs[task.job.name];

		// Listening Task events

		task.once("start", logger.start);
		task.once("schedule", logger.schedule);
		task.once("unschedule", logger.unschedule);
		task.once("error", logger.error);

		task.once("end", function(id, date){
			var id = id || task.id;
			var date = date || task.date;
			logger.end(id, function(){
				if( task.repeat ){
					logger.repeat(id, date, task.repeat);
				}
			});
		});
		console.log('listeners count', task.listeners('schedule').length);
		return task;
	};

	/** @public **/
	this.switcher = function(doc){
		// convert document to real task

		var task = _self.createTask(doc);
		console.log(task);
		/**
		// Decide what to do with a task
		if( task.isWaiting() ){
			if ( task.isDelayed() ){
				_self.executeTask(task);
			} else _self.schedule(task);

		} else if( task.isReschedule() ){
			_self.reschedule(task);

		} else if( doc.deleted || doc.status === 'done' || task.isCancel()){
			_self.unschedule(task);
		}
		**/
	};

	/** @private **/
	var __construct = function(_self){
		logger = new Logger();
		logger.init(_self.name, _self.switcher);

		// Start timer extented from scheduler
		_self.startClock();

		function exit(){
			logger.resetAll(_self.name, function(err, res){
				if (err) console.log(err);
				else console.log('All tasks reseted');
				process.exit();
			});
		}

		// When was to exit, change all scheduled docs to waiting again
		process.on('SIGINT', function () {
			console.log('SIGINT');
			exit();
		});
		process.on('SIGTERM', function () {
			console.log('SIGTERM');
			exit();
		});
	}(this);
};

/**
** @static
*/
Worker.getWorker = function(name){
	return new Worker(name);
};
module.exports = Worker;<commit_msg>contextual self<commit_after>var paths = require('../paths');

var Scheduler = require(paths.lib + 'scheduler');
var Task = require(paths.lib + 'task');
var jobs = require(paths.jobs);
var Logger = require('./logger');
var moment = require('moment');
/**
	@class Worker
	@extends Scheduler
	@extends Db
*/
var Worker = function(name){
	Scheduler.apply(this,arguments);

	/** @private **/
	var _self = this;
	var logger = '';

	/** @public **/
	this.name = name;

	/** @public **/
	this.createTask = function(hash){

		if(!hash) return false;

		var _worker = this;

		// Instance of tasks to be configured
		var task  = new Task(hash);

		// Add method to execute job
		task.execute = jobs[task.job.name];

		// Listening Task events

		task.once("start", logger.start);
		task.once("schedule", logger.schedule);
		task.once("unschedule", logger.unschedule);
		task.once("error", logger.error);

		task.once("end", function(id, date){
			var id = id || task.id;
			var date = date || task.date;
			logger.end(id, function(){
				if( task.repeat ){
					logger.repeat(id, date, task.repeat);
				}
			});
		});
		console.log('listeners count', task.listeners('schedule').length);
		return task;
	};

	/** @public **/
	this.switcher = function(doc){
		var _self = this;
		// convert document to real task
		var task = _self.createTask(doc);

		// Decide what to do with a task
		if( task.isWaiting() ){
			if ( task.isDelayed() ){
				_self.executeTask(task);
			} else _self.schedule(task);

		} else if( task.isReschedule() ){
			_self.reschedule(task);

		} else if( doc.deleted || doc.status === 'done' || task.isCancel()){
			_self.unschedule(task);
		}
	};

	/** @private **/
	var __construct = function(_self){
		logger = new Logger();
		logger.init(_self.name, _self.switcher);

		// Start timer extented from scheduler
		_self.startClock();

		function exit(){
			logger.resetAll(_self.name, function(err, res){
				if (err) console.log(err);
				else console.log('All tasks reseted');
				process.exit();
			});
		}

		// When was to exit, change all scheduled docs to waiting again
		process.on('SIGINT', function () {
			console.log('SIGINT');
			exit();
		});
		process.on('SIGTERM', function () {
			console.log('SIGTERM');
			exit();
		});
	}(this);
};

/**
** @static
*/
Worker.getWorker = function(name){
	return new Worker(name);
};
module.exports = Worker;<|endoftext|>


<commit_before>/*
Copyright 2017 BlocLedger

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/* jshint node: true */
'use strict';

process.env.NODE_ENV = 'production';
process.env.UV_THREADPOOL_SIZE = 64;

var app = require('express')();
var morgan = require('morgan');
var bodyparser = require('body-parser');
var atob = require('atob');
var path = require('path');
var fs = require('fs');
var util = require('./util.js');
var Q = require('q');
var debug = require('debug')('poe');
var rest = require('rest');
var mime = require('rest/interceptor/mime');
var errorCode = require('rest/interceptor/errorCode');
var restClient = rest.wrap(mime).wrap(errorCode, {code: 400});
var config = require('./configuration.js');
var GlobalAppUser = {};
var request = require('request');
var rp = require('request-promise-native');
var sa = require('superagent');
var init = require('./initialize.js');
var sdkInterface = require('./sdkInterface');
var poeRouter = require('./poeRouter.js'); // POE middleware to handle all of the POE REST endpoints
var sha = require('js-sha256');
var credentials = require('./credentials.js');

var newUser = util.newUser;
var PwStr = 'Pw!';

app.set('port', (process.env.PORT || 3000));

var chainHeight = 1;
var blockList = [];

// Path to the local directory containing the chaincode project under $GOPATH
process.env.GOPATH = path.join(__dirname, 'chaincode');
debug(process.env.GOPATH);

// Confidentiality setting
var confidentialSetting = config.confidentialSetting;

// Store the exports from initialize.js in global variables
var chain = init.chain;
var GlobalAppUser = init.GlobalAppUser;

var cred = config.cred;

// setup the sdk interface
var retrySdkInvoke = sdkInterface.retrySdkInvoke;
var retrySdkQuery = sdkInterface.retrySdkQuery;

app.use(morgan('dev'));
app.use(require('express').static(__dirname + '/public'));
app.use(require('cookie-parser')());
app.use(bodyparser.json());
app.use(require('cookie-session')({
  name: 'session',
  keys: [credentials.cookieSecret],
  maxAge: 24 * 60 * 60 * 1000,
}));
bodyparser.urlencoded({extended: true});
app.use(require('express-session')({
  secret: credentials.cookieSecret,
}));

app.use('/', poeRouter);  // handle the POE REST endpoint routes

app.get('/', function(req, res) {
  debug('Display basic home page.');
  res.sendfile('./public/' + 'index.html');
});

// provide an endpoint that will deploy the chaincode
app.get('/deploy', function(req, res) {
  // check to see if the user is enrolled
  var appUser = GlobalAppUser[req.session.appUser];
  if (!appUser) {
    console.log('Deploy failed. No user present.');
    return res.status(500).send('Deploy failed. No user present.');
  }

  sdkInterface.deploy(req, res);
});

app.get('/activeUser', function(req, res) {
  console.log('active user: ' + req.session.appUser);
  if (req.session.appUser) {
    return res.send('Log out ' + req.session.appUser.split('@')[0]);
  }
  res.send('Click to log in');
});

app.put('/resetUser', function(req, res) {
  res.send('Click to log in');
});

app.get('/chain/transactions/:id', function(req, res) {
  console.log('Get a transaction by ID: ' + req.params.id);
  var appUser = GlobalAppUser[req.session.appUser];
  init.client.setUserContext(appUser.hfcUser, true)
  .then(function(user) {
    console.log('user is ', user.getName());
    return init.chain.queryTransaction(req.params.id);
  })
  .then(function(result) {
    debug(result);
    res.json(result);
  })
  .catch(function(err) {
    console.log(err);
    res.status(500).send(err.msg);
  });
});

app.get('/adminPriv', function(req, res) {
  var adminSet = true; var anAdmin = false;
  if (GlobalAppUser) {
    Object.keys(GlobalAppUser).forEach(function(userName) {
      let usr = GlobalAppUser[userName];
      if (usr.userType == 'admin') {
        anAdmin = true;
      }
    });
  }
  if (req.session.appUser && anAdmin) {
    adminSet = GlobalAppUser[req.session.appUser].userType == 'admin';
  }
  if (!req.session.appUser && anAdmin) {
    adminSet = false;
  }
  var adminObj = {'adminPriv': adminSet};
  res.json(adminObj);
});

app.get('/loggedIn', function(req, res) {
  var loggedIn = false;
  if (req.session.appUser) {
    loggedIn = true;
  }
  var loginObj = {'loggedIn': loggedIn};
  res.json(loginObj);
});

app.get('/login', function(req, res) {
  console.log('Login/out: ' + req.user);
  if (req.user) {
    req.logout();
  }
  if (req.session.appUser) {
    req.session.appUser = null;
  }
  if (req.session.rememberUserName && !GlobalAppUser[req.session.rememberUserName]) {
    req.session.rememberUserName = null;
  }
  var userName = {'userName': req.session.rememberUserName};
  res.json(userName);
});

app.post('/login', function(req, res) {
  var params = req.body;
  var pwHash = sha.sha256(PwStr + params.userName + params.userPw);
  var retVal = true;

  console.log('Login post: ' + params.userName);

  var appUser = GlobalAppUser[params.userName];
  if (appUser) {
    console.log('app user:'); console.log(appUser);
    if (pwHash !== appUser.pwHash) {
      retVal = false;
    } else {
      if (params.remember) {
        console.log('remember ' + appUser.userName);
        req.session.rememberUserName = appUser.userName;
      }
      console.log('Set appUser: ' + appUser.userName);
      req.session.appUser = appUser.userName;
      res.redirect('/');
      return;
    }
  } else {
    retVal = false;
  }

  if (!retVal) {
    res.status(500).send('Login failed');
    return false;
  }
  res.status(200).send('success');
  return true;
});

function writeUsers() {
  var users = [];
  var appUserStr;
  let store = init.client.getStateStore();
  Object.keys(GlobalAppUser).forEach(function(userName) {
    let usr = GlobalAppUser[userName];
    let newUsr = {userName: usr.userName, pwHash: usr.pwHash,
      userType: usr.userType};
    users.push(newUsr);
  });
  try {
    appUserStr = JSON.stringify(users) + '\n';
  } catch (e) {
    console.log('stringify error: ' + e);
  }
  return store.setValue('appUsers', appUserStr);
}

app.post('/addUser', function(req, res) {
  var params = req.body;
  var appUser = null;
  var userName = params.userName.toLowerCase();

  console.log('Add user post: ' + userName);
  appUser = GlobalAppUser[userName];
  if (appUser) {
    res.status(500).send('User name is already in use');
    return;
  }

  if (!params.userPw) {
    res.status(500).send('Missing password');
    return;
  }
  if (params.userPw != params.userPwRepeat) {
    res.status(500).send('Passwords do not match');
    return;
  }
  var pwHash = sha.sha256(PwStr + userName + params.userPw);
  var userType = params.userType;
  if (userType === undefined || !userType) {
    userType = 'user';
  }

  var user = {userName: userName, pwHash: pwHash, userType: userType};
  GlobalAppUser[userName] = user;
  newUser(user);

  writeUsers();

  res.status(200).send('User added');
  return;
});

app.post('/editUser', function(req, res) {
  var params = req.body;
  var appUser = null;
  var userName = params.userName.toLowerCase();

  console.log('Edit user post: ' + userName);
  appUser = GlobalAppUser[userName];
  if (!appUser) {
    res.status(500).send('User name not found');
    return;
  }

  if (params.userPw) {
    if (params.userPw != params.userPwRepeat) {
      res.status(500).send('Passwords do not match');
      return;
    }
    var pwHash = sha.sha256(PwStr + userName + params.userPw);
    appUser.pwHash = pwHash;
  }
  var userType = params.userType;
  if (userType) {
    appUser.userType = userType;
  }

  writeUsers();

  res.status(200).send('User edited');
  return;
});

app.post('/delUser', function(req, res) {
  var params = req.body;
  var retVal = true;
  var userName = params.delUserName.toLowerCase();

  console.log('Delete user post: ' + userName);

  var appUser = GlobalAppUser[userName];
  if (appUser) {
    delete GlobalAppUser[userName];

    if (userName == req.session.appUser) {
      if (req.user) {
        req.logout();
      }
      req.session.appUser = null;
    }
    if (userName == req.session.rememberUserName) {
      req.session.rememberUserName = null;
    }
  } else {
    return res.status(500).send('User name not found');
  }

  writeUsers()
    .then(function() {
      if (!req.session.appUser) {
        console.log('Removed appUser');
        // Send status 201 to indicate that we removed the current logged-in user.
        // Tried using res.redirect() here, without success.
        res.status(201).send('success');
      }
      res.status(200).send('success');
    })
    .catch(function(err) {
      console.log(err);
    });
});

app.use(function(err, req, res, next) {
  console.log('unhandled error detected: ' + err.message + '\nurl: ' + req.url);
  res.type('text/plain');
  res.status(500);
  res.send('500 - server error');
});

app.use(function(req, res) {
  console.log('route not handled: ' + req.url);
  res.type('text/plain');
  res.status(404);
  res.send('404 - not found');
});

app.listen(app.get('port'), function() {
  console.log('listening on port', app.get('port'));
});
<commit_msg>Remove the credentials file.<commit_after>/*
Copyright 2017 BlocLedger

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/* jshint node: true */
'use strict';

process.env.NODE_ENV = 'production';
process.env.UV_THREADPOOL_SIZE = 64;

var app = require('express')();
var morgan = require('morgan');
var bodyparser = require('body-parser');
var atob = require('atob');
var path = require('path');
var fs = require('fs');
var util = require('./util.js');
var Q = require('q');
var debug = require('debug')('poe');
var rest = require('rest');
var mime = require('rest/interceptor/mime');
var errorCode = require('rest/interceptor/errorCode');
var restClient = rest.wrap(mime).wrap(errorCode, {code: 400});
var config = require('./configuration.js');
var GlobalAppUser = {};
var request = require('request');
var rp = require('request-promise-native');
var sa = require('superagent');
var init = require('./initialize.js');
var sdkInterface = require('./sdkInterface');
var poeRouter = require('./poeRouter.js'); // POE middleware to handle all of the POE REST endpoints
var sha = require('js-sha256');

var newUser = util.newUser;
var PwStr = 'Pw!';

app.set('port', (process.env.PORT || 3000));

var chainHeight = 1;
var blockList = [];

// Path to the local directory containing the chaincode project under $GOPATH
process.env.GOPATH = path.join(__dirname, 'chaincode');
debug(process.env.GOPATH);

// Confidentiality setting
var confidentialSetting = config.confidentialSetting;

// Store the exports from initialize.js in global variables
var chain = init.chain;
var GlobalAppUser = init.GlobalAppUser;

var cred = config.cred;

// setup the sdk interface
var retrySdkInvoke = sdkInterface.retrySdkInvoke;
var retrySdkQuery = sdkInterface.retrySdkQuery;

app.use(morgan('dev'));
app.use(require('express').static(__dirname + '/public'));
app.use(require('cookie-parser')());
app.use(bodyparser.json());
app.use(require('cookie-session')({
  name: 'session',
  keys: ["A cookie secret"],
  maxAge: 24 * 60 * 60 * 1000,
}));
bodyparser.urlencoded({extended: true});

app.use('/', poeRouter);  // handle the POE REST endpoint routes

app.get('/', function(req, res) {
  debug('Display basic home page.');
  res.sendfile('./public/' + 'index.html');
});

// provide an endpoint that will deploy the chaincode
app.get('/deploy', function(req, res) {
  // check to see if the user is enrolled
  var appUser = GlobalAppUser[req.session.appUser];
  if (!appUser) {
    console.log('Deploy failed. No user present.');
    return res.status(500).send('Deploy failed. No user present.');
  }

  sdkInterface.deploy(req, res);
});

app.get('/activeUser', function(req, res) {
  console.log('active user: ' + req.session.appUser);
  if (req.session.appUser) {
    return res.send('Log out ' + req.session.appUser.split('@')[0]);
  }
  res.send('Click to log in');
});

app.put('/resetUser', function(req, res) {
  res.send('Click to log in');
});

app.get('/chain/transactions/:id', function(req, res) {
  console.log('Get a transaction by ID: ' + req.params.id);
  var appUser = GlobalAppUser[req.session.appUser];
  init.client.setUserContext(appUser.hfcUser, true)
  .then(function(user) {
    console.log('user is ', user.getName());
    return init.chain.queryTransaction(req.params.id);
  })
  .then(function(result) {
    debug(result);
    res.json(result);
  })
  .catch(function(err) {
    console.log(err);
    res.status(500).send(err.msg);
  });
});

app.get('/adminPriv', function(req, res) {
  var adminSet = true; var anAdmin = false;
  if (GlobalAppUser) {
    Object.keys(GlobalAppUser).forEach(function(userName) {
      let usr = GlobalAppUser[userName];
      if (usr.userType == 'admin') {
        anAdmin = true;
      }
    });
  }
  if (req.session.appUser && anAdmin) {
    adminSet = GlobalAppUser[req.session.appUser].userType == 'admin';
  }
  if (!req.session.appUser && anAdmin) {
    adminSet = false;
  }
  var adminObj = {'adminPriv': adminSet};
  res.json(adminObj);
});

app.get('/loggedIn', function(req, res) {
  var loggedIn = false;
  if (req.session.appUser) {
    loggedIn = true;
  }
  var loginObj = {'loggedIn': loggedIn};
  res.json(loginObj);
});

app.get('/login', function(req, res) {
  console.log('Login/out: ' + req.user);
  if (req.user) {
    req.logout();
  }
  if (req.session.appUser) {
    req.session.appUser = null;
  }
  if (req.session.rememberUserName && !GlobalAppUser[req.session.rememberUserName]) {
    req.session.rememberUserName = null;
  }
  var userName = {'userName': req.session.rememberUserName};
  res.json(userName);
});

app.post('/login', function(req, res) {
  var params = req.body;
  var pwHash = sha.sha256(PwStr + params.userName + params.userPw);
  var retVal = true;

  console.log('Login post: ' + params.userName);

  var appUser = GlobalAppUser[params.userName];
  if (appUser) {
    console.log('app user:'); console.log(appUser);
    if (pwHash !== appUser.pwHash) {
      retVal = false;
    } else {
      if (params.remember) {
        console.log('remember ' + appUser.userName);
        req.session.rememberUserName = appUser.userName;
      }
      console.log('Set appUser: ' + appUser.userName);
      req.session.appUser = appUser.userName;
      res.redirect('/');
      return;
    }
  } else {
    retVal = false;
  }

  if (!retVal) {
    res.status(500).send('Login failed');
    return false;
  }
  res.status(200).send('success');
  return true;
});

function writeUsers() {
  var users = [];
  var appUserStr;
  let store = init.client.getStateStore();
  Object.keys(GlobalAppUser).forEach(function(userName) {
    let usr = GlobalAppUser[userName];
    let newUsr = {userName: usr.userName, pwHash: usr.pwHash,
      userType: usr.userType};
    users.push(newUsr);
  });
  try {
    appUserStr = JSON.stringify(users) + '\n';
  } catch (e) {
    console.log('stringify error: ' + e);
  }
  return store.setValue('appUsers', appUserStr);
}

app.post('/addUser', function(req, res) {
  var params = req.body;
  var appUser = null;
  var userName = params.userName.toLowerCase();

  console.log('Add user post: ' + userName);
  appUser = GlobalAppUser[userName];
  if (appUser) {
    res.status(500).send('User name is already in use');
    return;
  }

  if (!params.userPw) {
    res.status(500).send('Missing password');
    return;
  }
  if (params.userPw != params.userPwRepeat) {
    res.status(500).send('Passwords do not match');
    return;
  }
  var pwHash = sha.sha256(PwStr + userName + params.userPw);
  var userType = params.userType;
  if (userType === undefined || !userType) {
    userType = 'user';
  }

  var user = {userName: userName, pwHash: pwHash, userType: userType};
  GlobalAppUser[userName] = user;
  newUser(user);

  writeUsers();

  res.status(200).send('User added');
  return;
});

app.post('/editUser', function(req, res) {
  var params = req.body;
  var appUser = null;
  var userName = params.userName.toLowerCase();

  console.log('Edit user post: ' + userName);
  appUser = GlobalAppUser[userName];
  if (!appUser) {
    res.status(500).send('User name not found');
    return;
  }

  if (params.userPw) {
    if (params.userPw != params.userPwRepeat) {
      res.status(500).send('Passwords do not match');
      return;
    }
    var pwHash = sha.sha256(PwStr + userName + params.userPw);
    appUser.pwHash = pwHash;
  }
  var userType = params.userType;
  if (userType) {
    appUser.userType = userType;
  }

  writeUsers();

  res.status(200).send('User edited');
  return;
});

app.post('/delUser', function(req, res) {
  var params = req.body;
  var retVal = true;
  var userName = params.delUserName.toLowerCase();

  console.log('Delete user post: ' + userName);

  var appUser = GlobalAppUser[userName];
  if (appUser) {
    delete GlobalAppUser[userName];

    if (userName == req.session.appUser) {
      if (req.user) {
        req.logout();
      }
      req.session.appUser = null;
    }
    if (userName == req.session.rememberUserName) {
      req.session.rememberUserName = null;
    }
  } else {
    return res.status(500).send('User name not found');
  }

  writeUsers()
    .then(function() {
      if (!req.session.appUser) {
        console.log('Removed appUser');
        // Send status 201 to indicate that we removed the current logged-in user.
        // Tried using res.redirect() here, without success.
        res.status(201).send('success');
      }
      res.status(200).send('success');
    })
    .catch(function(err) {
      console.log(err);
    });
});

app.use(function(err, req, res, next) {
  console.log('unhandled error detected: ' + err.message + '\nurl: ' + req.url);
  res.type('text/plain');
  res.status(500);
  res.send('500 - server error');
});

app.use(function(req, res) {
  console.log('route not handled: ' + req.url);
  res.type('text/plain');
  res.status(404);
  res.send('404 - not found');
});

app.listen(app.get('port'), function() {
  console.log('listening on port', app.get('port'));
});
<|endoftext|>