<commit_before>require("internal").flushModuleCache();

var jsunity = require("jsunity"),
  console = require("console"),
  arangodb = require("org/arangodb"),
  FoxxApplication = require("org/arangodb/foxx").Application,
  db = arangodb.db;

function CreateFoxxApplicationSpec () {
  return {
    testCreationWithoutParameters: function () {
      var app = new FoxxApplication({prefix: "", foxxes: []}),
        routingInfo = app.routingInfo;

      assertEqual(routingInfo.routes.length, 0);
      assertEqual(routingInfo.urlPrefix, "");
    },

    testCreationWithURLPrefix: function () {
      var app = new FoxxApplication({prefix: "", foxxes: []}, {urlPrefix: "/wiese"}),
        routingInfo = app.routingInfo;

      assertEqual(routingInfo.routes.length, 0);
      assertEqual(routingInfo.urlPrefix, "/wiese");
    },

    testAdditionOfBaseMiddlewareInRoutingInfo: function () {
      var app = new FoxxApplication({prefix: "", foxxes: []}),
        routingInfo = app.routingInfo,
        hopefully_base = routingInfo.middleware[0];

      assertEqual(routingInfo.middleware.length, 1);
      assertEqual(hopefully_base.url.match, "/*");
    }
  };
}

function SetRoutesFoxxApplicationSpec () {
  var app;

  return {
    setUp: function () {
      app = new FoxxApplication({prefix: "", foxxes: []});
    },

    testSettingRoutes: function () {
      var myFunc = function () {},
        routes = app.routingInfo.routes;

      app.get('/simple/route', myFunc);
      assertEqual(routes.length, 1);
      assertEqual(routes[0].url.match, '/simple/route');
      assertUndefined(routes[0].url.constraint);
    },

    testSetMethodToHead: function () {
      var myFunc = function () {},
        routes = app.routingInfo.routes;

      app.head('/simple/route', myFunc);
      assertEqual(routes[0].docs.httpMethod, 'HEAD');
      assertEqual(routes[0].url.methods, ["head"]);
    },

    testSetMethodToGet: function () {
      var myFunc = function () {},
        routes = app.routingInfo.routes;

      app.get('/simple/route', myFunc);
      assertEqual(routes[0].docs.httpMethod, 'GET');
      assertEqual(routes[0].url.methods, ["get"]);
    },

    testSetMethodToPost: function () {
      var myFunc = function () {},
        routes = app.routingInfo.routes;

      app.post('/simple/route', myFunc);
      assertEqual(routes[0].docs.httpMethod, 'POST');
      assertEqual(routes[0].url.methods, ["post"]);
    },

    testSetMethodToPut: function () {
      var myFunc = function () {},
        routes = app.routingInfo.routes;

      app.put('/simple/route', myFunc);
      assertEqual(routes[0].docs.httpMethod, 'PUT');
      assertEqual(routes[0].url.methods, ["put"]);
    },

    testSetMethodToPatch: function () {
      var myFunc = function () {},
        routes = app.routingInfo.routes;

      app.patch('/simple/route', myFunc);
      assertEqual(routes[0].docs.httpMethod, 'PATCH');
      assertEqual(routes[0].url.methods, ["patch"]);
    },

    testSetMethodToDelete: function () {
      var myFunc = function () {},
        routes = app.routingInfo.routes;

      app['delete']('/simple/route', myFunc);
      assertEqual(routes[0].docs.httpMethod, 'DELETE');
      assertEqual(routes[0].url.methods, ["delete"]);
    },

    testSetMethodToDeleteViaAlias: function () {
      var myFunc = function () {},
        routes = app.routingInfo.routes;

      app.del('/simple/route', myFunc);
      assertEqual(routes[0].docs.httpMethod, 'DELETE');
      assertEqual(routes[0].url.methods, ["delete"]);
    },

    testRefuseRoutesWithRoutesThatAreNumbers: function () {
      var myFunc = function () {},
        routes = app.routingInfo.routes,
        error;

      try {
        app.get(2, myFunc);
      } catch(e) {
        error = e;
      }
      assertEqual(error, new Error("URL has to be a String"));
      assertEqual(routes.length, 0);
    },

    testRefuseRoutesWithRoutesThatAreRegularExpressions: function () {
      var myFunc = function () {},
        routes = app.routingInfo.routes,
        error;

      try {
        app.get(/[a-z]*/, myFunc);
      } catch(e) {
        error = e;
      }
      assertEqual(error, new Error("URL has to be a String"));
      assertEqual(routes.length, 0);
    },

    testRefuseRoutesWithRoutesThatAreArrays: function () {
      var myFunc = function () {},
        routes = app.routingInfo.routes,
        error;

      try {
        app.get(["/a", "/b"], myFunc);
      } catch(e) {
        error = e;
      }
      assertEqual(error, new Error("URL has to be a String"));
      assertEqual(routes.length, 0);
    }
  };
}

function DocumentationAndConstraintsSpec () {
  var app, routes;

  return {
    setUp: function () {
      app = new FoxxApplication({prefix: "", foxxes: []});
      routes = app.routingInfo.routes;
    },

    testDefinePathParam: function () {
      app.get('/foxx/:id', function () {
        //nothing
      }).pathParam("id", {
        description: "Id of the Foxx",
        dataType: "int"
      });

      assertEqual(routes.length, 1);
      assertEqual(routes[0].url.constraint.id, "/[0-9]+/");
      assertEqual(routes[0].docs.parameters[0].paramType, "path");
      assertEqual(routes[0].docs.parameters[0].name, "id");
      assertEqual(routes[0].docs.parameters[0].description, "Id of the Foxx");
      assertEqual(routes[0].docs.parameters[0].dataType, "int");
      assertEqual(routes[0].docs.parameters[0].required, true);
    },

    testDefinePathCaseParam: function () {
      app.get('/foxx/:idParam', function () {
        //nothing
      }).pathParam("idParam", {
        description: "Id of the Foxx",
        dataType: "int"
      });

      assertEqual(routes.length, 1);
      assertEqual(routes[0].url.constraint.idParam, "/[0-9]+/");
      assertEqual(routes[0].docs.parameters[0].paramType, "path");
      assertEqual(routes[0].docs.parameters[0].name, "idParam");
      assertEqual(routes[0].docs.parameters[0].description, "Id of the Foxx");
      assertEqual(routes[0].docs.parameters[0].dataType, "int");
      assertEqual(routes[0].docs.parameters[0].required, true);
    },

    testDefineMultiplePathParams: function () {
      app.get('/:foxx/:id', function () {
        //nothing
      }).pathParam("foxx", {
        description: "Kind of Foxx",
        dataType: "string"
      }).pathParam("id", {
        description: "Id of the Foxx",
        dataType: "int"
      });

      assertEqual(routes.length, 1);

      assertEqual(routes[0].url.constraint.foxx, "/.+/");
      assertEqual(routes[0].docs.parameters[0].paramType, "path");
      assertEqual(routes[0].docs.parameters[0].name, "foxx");
      assertEqual(routes[0].docs.parameters[0].description, "Kind of Foxx");
      assertEqual(routes[0].docs.parameters[0].dataType, "string");
      assertEqual(routes[0].docs.parameters[0].required, true);

      assertEqual(routes[0].url.constraint.id, "/[0-9]+/");
      assertEqual(routes[0].docs.parameters[1].paramType, "path");
      assertEqual(routes[0].docs.parameters[1].name, "id");
      assertEqual(routes[0].docs.parameters[1].description, "Id of the Foxx");
      assertEqual(routes[0].docs.parameters[1].dataType, "int");
      assertEqual(routes[0].docs.parameters[1].required, true);
    },

    testDefineMultiplePathCaseParams: function () {
      app.get('/:foxxParam/:idParam', function () {
        //nothing
      }).pathParam("foxxParam", {
        description: "Kind of Foxx",
        dataType: "string"
      }).pathParam("idParam", {
        description: "Id of the Foxx",
        dataType: "int"
      });

      assertEqual(routes.length, 1);

      assertEqual(routes[0].url.constraint.foxxParam, "/.+/");
      assertEqual(routes[0].docs.parameters[0].paramType, "path");
      assertEqual(routes[0].docs.parameters[0].name, "foxxParam");
      assertEqual(routes[0].docs.parameters[0].description, "Kind of Foxx");
      assertEqual(routes[0].docs.parameters[0].dataType, "string");
      assertEqual(routes[0].docs.parameters[0].required, true);

      assertEqual(routes[0].url.constraint.idParam, "/[0-9]+/");
      assertEqual(routes[0].docs.parameters[1].paramType, "path");
      assertEqual(routes[0].docs.parameters[1].name, "idParam");
      assertEqual(routes[0].docs.parameters[1].description, "Id of the Foxx");
      assertEqual(routes[0].docs.parameters[1].dataType, "int");
      assertEqual(routes[0].docs.parameters[1].required, true);
    },

    testDefineQueryParam: function () {
      app.get('/foxx', function () {
        //nothing
      }).queryParam("a", {
        description: "The value of an a",
        dataType: "int",
        required: false,
        allowMultiple: true
      });

      assertEqual(routes.length, 1);
      assertEqual(routes[0].docs.parameters[0].paramType, "query");
      assertEqual(routes[0].docs.parameters[0].name, "a");
      assertEqual(routes[0].docs.parameters[0].description, "The value of an a");
      assertEqual(routes[0].docs.parameters[0].dataType, "int");
      assertEqual(routes[0].docs.parameters[0].required, false);
      assertEqual(routes[0].docs.parameters[0].allowMultiple, true);
    },

    testDefineMetaData: function () {
      app.get('/foxx', function () {
        //nothing
      }).summary("b").notes("c");

      assertEqual(routes.length, 1);
      assertEqual(routes[0].docs.nickname, "get_foxx");
      assertEqual(routes[0].docs.summary, "b");
      assertEqual(routes[0].docs.notes, "c");
    },

    testSummaryRestrictedTo60Characters: function () {
      var error;

      try {
        app.get('/foxx', function () {
          //nothing
        }).summary("ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc");
      } catch(e) {
        error = e;
      }

      assertEqual(error, new Error("Summary can't be longer than 60 characters"));
    },

    testDefineErrorResponse: function () {
      app.get('/foxx', function () {
        //nothing
      }).errorResponse(400, "I don't understand a word you're saying");

      assertEqual(routes.length, 1);
      assertEqual(routes[0].docs.errorResponses.length, 1);
      assertEqual(routes[0].docs.errorResponses[0].code, 400);
      assertEqual(routes[0].docs.errorResponses[0].reason, "I don't understand a word you're saying");
    }
  };
}

function AddMiddlewareFoxxApplicationSpec () {
  var app;

  return {
    setUp: function () {
      app = new FoxxApplication({prefix: "", foxxes: []});
    },

    testAddABeforeMiddlewareForAllRoutes: function () {
      var myFunc = function (req, res) { a = (req > res); },
        middleware = app.routingInfo.middleware,
        callback;

      app.before(myFunc);

      assertEqual(middleware.length, 2);
      assertEqual(middleware[1].url.match, '/*');
      callback = String(middleware[1].action.callback);
      assertTrue(callback.indexOf((String(myFunc) + "(req, res)") > 0));
      assertTrue(callback.indexOf("next()" > 0));
      assertTrue(callback.indexOf(String(myFunc)) < callback.indexOf("next()"));
    },

    testAddABeforeMiddlewareForCertainRoutes: function () {
      var myFunc = function (req, res) { a = (req > res); },
        middleware = app.routingInfo.middleware,
        callback;

      app.before('/fancy/path', myFunc);

      assertEqual(middleware.length, 2);
      assertEqual(middleware[1].url.match, '/fancy/path');
      callback = String(middleware[1].action.callback);
      assertTrue(callback.indexOf((String(myFunc) + "(req, res)") > 0));
      assertTrue(callback.indexOf("next()" > 0));
      assertTrue(callback.indexOf(String(myFunc)) < callback.indexOf("next()"));
    },

    testAddAnAfterMiddlewareForAllRoutes: function () {
      var myFunc = function (req, res) { a = (req > res); },
        middleware = app.routingInfo.middleware,
        callback;

      app.after(myFunc);

      assertEqual(middleware.length, 2);
      assertEqual(middleware[1].url.match, '/*');
      callback = String(middleware[1].action.callback);
      assertTrue(callback.indexOf((String(myFunc) + "(req, res)") > 0));
      assertTrue(callback.indexOf("next()" > 0));
      assertTrue(callback.indexOf("func(req") > callback.indexOf("next()"));
    },

    testAddAnAfterMiddlewareForCertainRoutes: function () {
      var myFunc = function (req, res) { a = (req > res); },
        middleware = app.routingInfo.middleware,
        callback;

      app.after('/fancy/path', myFunc);

      assertEqual(middleware.length, 2);
      assertEqual(middleware[1].url.match, '/fancy/path');
      callback = String(middleware[1].action.callback);
      assertTrue(callback.indexOf((String(myFunc) + "(req, res)") > 0));
      assertTrue(callback.indexOf("next()" > 0));
      assertTrue(callback.indexOf("func(req") > callback.indexOf("next()"));
    }
  };
}

jsunity.run(CreateFoxxApplicationSpec);
jsunity.run(SetRoutesFoxxApplicationSpec);
jsunity.run(DocumentationAndConstraintsSpec);
jsunity.run(AddMiddlewareFoxxApplicationSpec);

return jsunity.done();
<commit_msg>Foxx: Preparing existing Tests for new context methods<commit_after>require("internal").flushModuleCache();

var jsunity = require("jsunity"),
  FoxxApplication = require("org/arangodb/foxx").Application,
  db = require("org/arangodb").db,
  fakeContext;

fakeContext = {
  prefix: "",
  foxxes: [],
  comments: [],
  clearComments: function () {},
  comment: function () {}
};

function CreateFoxxApplicationSpec () {
  return {
    testCreationWithoutParameters: function () {
      var app = new FoxxApplication(fakeContext),
        routingInfo = app.routingInfo;

      assertEqual(routingInfo.routes.length, 0);
      assertEqual(routingInfo.urlPrefix, "");
    },

    testCreationWithURLPrefix: function () {
      var app = new FoxxApplication(fakeContext, {urlPrefix: "/wiese"}),
        routingInfo = app.routingInfo;

      assertEqual(routingInfo.routes.length, 0);
      assertEqual(routingInfo.urlPrefix, "/wiese");
    },

    testAdditionOfBaseMiddlewareInRoutingInfo: function () {
      var app = new FoxxApplication(fakeContext),
        routingInfo = app.routingInfo,
        hopefully_base = routingInfo.middleware[0];

      assertEqual(routingInfo.middleware.length, 1);
      assertEqual(hopefully_base.url.match, "/*");
    }
  };
}

function SetRoutesFoxxApplicationSpec () {
  var app;

  return {
    setUp: function () {
      app = new FoxxApplication(fakeContext);
    },

    testSettingRoutes: function () {
      var myFunc = function () {},
        routes = app.routingInfo.routes;

      app.get('/simple/route', myFunc);
      assertEqual(routes.length, 1);
      assertEqual(routes[0].url.match, '/simple/route');
      assertUndefined(routes[0].url.constraint);
    },

    testSetMethodToHead: function () {
      var myFunc = function () {},
        routes = app.routingInfo.routes;

      app.head('/simple/route', myFunc);
      assertEqual(routes[0].docs.httpMethod, 'HEAD');
      assertEqual(routes[0].url.methods, ["head"]);
    },

    testSetMethodToGet: function () {
      var myFunc = function () {},
        routes = app.routingInfo.routes;

      app.get('/simple/route', myFunc);
      assertEqual(routes[0].docs.httpMethod, 'GET');
      assertEqual(routes[0].url.methods, ["get"]);
    },

    testSetMethodToPost: function () {
      var myFunc = function () {},
        routes = app.routingInfo.routes;

      app.post('/simple/route', myFunc);
      assertEqual(routes[0].docs.httpMethod, 'POST');
      assertEqual(routes[0].url.methods, ["post"]);
    },

    testSetMethodToPut: function () {
      var myFunc = function () {},
        routes = app.routingInfo.routes;

      app.put('/simple/route', myFunc);
      assertEqual(routes[0].docs.httpMethod, 'PUT');
      assertEqual(routes[0].url.methods, ["put"]);
    },

    testSetMethodToPatch: function () {
      var myFunc = function () {},
        routes = app.routingInfo.routes;

      app.patch('/simple/route', myFunc);
      assertEqual(routes[0].docs.httpMethod, 'PATCH');
      assertEqual(routes[0].url.methods, ["patch"]);
    },

    testSetMethodToDelete: function () {
      var myFunc = function () {},
        routes = app.routingInfo.routes;

      app['delete']('/simple/route', myFunc);
      assertEqual(routes[0].docs.httpMethod, 'DELETE');
      assertEqual(routes[0].url.methods, ["delete"]);
    },

    testSetMethodToDeleteViaAlias: function () {
      var myFunc = function () {},
        routes = app.routingInfo.routes;

      app.del('/simple/route', myFunc);
      assertEqual(routes[0].docs.httpMethod, 'DELETE');
      assertEqual(routes[0].url.methods, ["delete"]);
    },

    testRefuseRoutesWithRoutesThatAreNumbers: function () {
      var myFunc = function () {},
        routes = app.routingInfo.routes,
        error;

      try {
        app.get(2, myFunc);
      } catch(e) {
        error = e;
      }
      assertEqual(error, new Error("URL has to be a String"));
      assertEqual(routes.length, 0);
    },

    testRefuseRoutesWithRoutesThatAreRegularExpressions: function () {
      var myFunc = function () {},
        routes = app.routingInfo.routes,
        error;

      try {
        app.get(/[a-z]*/, myFunc);
      } catch(e) {
        error = e;
      }
      assertEqual(error, new Error("URL has to be a String"));
      assertEqual(routes.length, 0);
    },

    testRefuseRoutesWithRoutesThatAreArrays: function () {
      var myFunc = function () {},
        routes = app.routingInfo.routes,
        error;

      try {
        app.get(["/a", "/b"], myFunc);
      } catch(e) {
        error = e;
      }
      assertEqual(error, new Error("URL has to be a String"));
      assertEqual(routes.length, 0);
    }
  };
}

function DocumentationAndConstraintsSpec () {
  var app, routes;

  return {
    setUp: function () {
      app = new FoxxApplication(fakeContext);
      routes = app.routingInfo.routes;
    },

    testDefinePathParam: function () {
      app.get('/foxx/:id', function () {
        //nothing
      }).pathParam("id", {
        description: "Id of the Foxx",
        dataType: "int"
      });

      assertEqual(routes.length, 1);
      assertEqual(routes[0].url.constraint.id, "/[0-9]+/");
      assertEqual(routes[0].docs.parameters[0].paramType, "path");
      assertEqual(routes[0].docs.parameters[0].name, "id");
      assertEqual(routes[0].docs.parameters[0].description, "Id of the Foxx");
      assertEqual(routes[0].docs.parameters[0].dataType, "int");
      assertEqual(routes[0].docs.parameters[0].required, true);
    },

    testDefinePathCaseParam: function () {
      app.get('/foxx/:idParam', function () {
        //nothing
      }).pathParam("idParam", {
        description: "Id of the Foxx",
        dataType: "int"
      });

      assertEqual(routes.length, 1);
      assertEqual(routes[0].url.constraint.idParam, "/[0-9]+/");
      assertEqual(routes[0].docs.parameters[0].paramType, "path");
      assertEqual(routes[0].docs.parameters[0].name, "idParam");
      assertEqual(routes[0].docs.parameters[0].description, "Id of the Foxx");
      assertEqual(routes[0].docs.parameters[0].dataType, "int");
      assertEqual(routes[0].docs.parameters[0].required, true);
    },

    testDefineMultiplePathParams: function () {
      app.get('/:foxx/:id', function () {
        //nothing
      }).pathParam("foxx", {
        description: "Kind of Foxx",
        dataType: "string"
      }).pathParam("id", {
        description: "Id of the Foxx",
        dataType: "int"
      });

      assertEqual(routes.length, 1);

      assertEqual(routes[0].url.constraint.foxx, "/.+/");
      assertEqual(routes[0].docs.parameters[0].paramType, "path");
      assertEqual(routes[0].docs.parameters[0].name, "foxx");
      assertEqual(routes[0].docs.parameters[0].description, "Kind of Foxx");
      assertEqual(routes[0].docs.parameters[0].dataType, "string");
      assertEqual(routes[0].docs.parameters[0].required, true);

      assertEqual(routes[0].url.constraint.id, "/[0-9]+/");
      assertEqual(routes[0].docs.parameters[1].paramType, "path");
      assertEqual(routes[0].docs.parameters[1].name, "id");
      assertEqual(routes[0].docs.parameters[1].description, "Id of the Foxx");
      assertEqual(routes[0].docs.parameters[1].dataType, "int");
      assertEqual(routes[0].docs.parameters[1].required, true);
    },

    testDefineMultiplePathCaseParams: function () {
      app.get('/:foxxParam/:idParam', function () {
        //nothing
      }).pathParam("foxxParam", {
        description: "Kind of Foxx",
        dataType: "string"
      }).pathParam("idParam", {
        description: "Id of the Foxx",
        dataType: "int"
      });

      assertEqual(routes.length, 1);

      assertEqual(routes[0].url.constraint.foxxParam, "/.+/");
      assertEqual(routes[0].docs.parameters[0].paramType, "path");
      assertEqual(routes[0].docs.parameters[0].name, "foxxParam");
      assertEqual(routes[0].docs.parameters[0].description, "Kind of Foxx");
      assertEqual(routes[0].docs.parameters[0].dataType, "string");
      assertEqual(routes[0].docs.parameters[0].required, true);

      assertEqual(routes[0].url.constraint.idParam, "/[0-9]+/");
      assertEqual(routes[0].docs.parameters[1].paramType, "path");
      assertEqual(routes[0].docs.parameters[1].name, "idParam");
      assertEqual(routes[0].docs.parameters[1].description, "Id of the Foxx");
      assertEqual(routes[0].docs.parameters[1].dataType, "int");
      assertEqual(routes[0].docs.parameters[1].required, true);
    },

    testDefineQueryParam: function () {
      app.get('/foxx', function () {
        //nothing
      }).queryParam("a", {
        description: "The value of an a",
        dataType: "int",
        required: false,
        allowMultiple: true
      });

      assertEqual(routes.length, 1);
      assertEqual(routes[0].docs.parameters[0].paramType, "query");
      assertEqual(routes[0].docs.parameters[0].name, "a");
      assertEqual(routes[0].docs.parameters[0].description, "The value of an a");
      assertEqual(routes[0].docs.parameters[0].dataType, "int");
      assertEqual(routes[0].docs.parameters[0].required, false);
      assertEqual(routes[0].docs.parameters[0].allowMultiple, true);
    },

    testDefineMetaData: function () {
      app.get('/foxx', function () {
        //nothing
      }).summary("b").notes("c");

      assertEqual(routes.length, 1);
      assertEqual(routes[0].docs.nickname, "get_foxx");
      assertEqual(routes[0].docs.summary, "b");
      assertEqual(routes[0].docs.notes, "c");
    },

    testSummaryRestrictedTo60Characters: function () {
      var error;

      try {
        app.get('/foxx', function () {
          //nothing
        }).summary("ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc");
      } catch(e) {
        error = e;
      }

      assertEqual(error, new Error("Summary can't be longer than 60 characters"));
    },

    testDefineErrorResponse: function () {
      app.get('/foxx', function () {
        //nothing
      }).errorResponse(400, "I don't understand a word you're saying");

      assertEqual(routes.length, 1);
      assertEqual(routes[0].docs.errorResponses.length, 1);
      assertEqual(routes[0].docs.errorResponses[0].code, 400);
      assertEqual(routes[0].docs.errorResponses[0].reason, "I don't understand a word you're saying");
    }
  };
}

function AddMiddlewareFoxxApplicationSpec () {
  var app;

  return {
    setUp: function () {
      app = new FoxxApplication(fakeContext);
    },

    testAddABeforeMiddlewareForAllRoutes: function () {
      var myFunc = function (req, res) { a = (req > res); },
        middleware = app.routingInfo.middleware,
        callback;

      app.before(myFunc);

      assertEqual(middleware.length, 2);
      assertEqual(middleware[1].url.match, '/*');
      callback = String(middleware[1].action.callback);
      assertTrue(callback.indexOf((String(myFunc) + "(req, res)") > 0));
      assertTrue(callback.indexOf("next()" > 0));
      assertTrue(callback.indexOf(String(myFunc)) < callback.indexOf("next()"));
    },

    testAddABeforeMiddlewareForCertainRoutes: function () {
      var myFunc = function (req, res) { a = (req > res); },
        middleware = app.routingInfo.middleware,
        callback;

      app.before('/fancy/path', myFunc);

      assertEqual(middleware.length, 2);
      assertEqual(middleware[1].url.match, '/fancy/path');
      callback = String(middleware[1].action.callback);
      assertTrue(callback.indexOf((String(myFunc) + "(req, res)") > 0));
      assertTrue(callback.indexOf("next()" > 0));
      assertTrue(callback.indexOf(String(myFunc)) < callback.indexOf("next()"));
    },

    testAddAnAfterMiddlewareForAllRoutes: function () {
      var myFunc = function (req, res) { a = (req > res); },
        middleware = app.routingInfo.middleware,
        callback;

      app.after(myFunc);

      assertEqual(middleware.length, 2);
      assertEqual(middleware[1].url.match, '/*');
      callback = String(middleware[1].action.callback);
      assertTrue(callback.indexOf((String(myFunc) + "(req, res)") > 0));
      assertTrue(callback.indexOf("next()" > 0));
      assertTrue(callback.indexOf("func(req") > callback.indexOf("next()"));
    },

    testAddAnAfterMiddlewareForCertainRoutes: function () {
      var myFunc = function (req, res) { a = (req > res); },
        middleware = app.routingInfo.middleware,
        callback;

      app.after('/fancy/path', myFunc);

      assertEqual(middleware.length, 2);
      assertEqual(middleware[1].url.match, '/fancy/path');
      callback = String(middleware[1].action.callback);
      assertTrue(callback.indexOf((String(myFunc) + "(req, res)") > 0));
      assertTrue(callback.indexOf("next()" > 0));
      assertTrue(callback.indexOf("func(req") > callback.indexOf("next()"));
    }
  };
}

jsunity.run(CreateFoxxApplicationSpec);
jsunity.run(SetRoutesFoxxApplicationSpec);
jsunity.run(DocumentationAndConstraintsSpec);
jsunity.run(AddMiddlewareFoxxApplicationSpec);

return jsunity.done();
<|endoftext|>


<commit_before>var Vue = require('vue')
var VueRouter = require('vue-router')
Vue.use(VueRouter)

var Main = require('./app/main.vue')
var Login = require('./app/login.vue')
var Node = require('./app/node.vue')
var Console = require('./app/console.vue')

import {getCookie} from "./utils"

var routes = [
  {path: '/', component: Main, redirect: '/node'},
  {path: '/login', component: Login},
  {path: '/node', component: Node},
  {path: '/console', component: Console}
]

var router = new VueRouter({routes, linkActiveClass: "active"})

router.beforeEach((to, from, next) => {
  if (to.path === "/login") {
    next()
  } else if (getCookie("bitmark-webgui") === "") {
    next({path: "/login", query: {redirect: to.fullPath}})
  } else {
    next()
  }
})

var app = new Vue({
  router,
  el: '#main',
  render: h => h(Main)
})
<commit_msg>Prevent duplicated login<commit_after>var Vue = require('vue')
var VueRouter = require('vue-router')
Vue.use(VueRouter)

var Main = require('./app/main.vue')
var Login = require('./app/login.vue')
var Node = require('./app/node.vue')
var Console = require('./app/console.vue')

import {getCookie} from "./utils"

var routes = [
  {path: '/', component: Main, redirect: '/node'},
  {path: '/login', component: Login},
  {path: '/node', component: Node},
  {path: '/console', component: Console}
]

var router = new VueRouter({routes, linkActiveClass: "active"})

router.beforeEach((to, from, next) => {
  if (to.path === "/login") {
    if (getCookie("bitmark-webgui") !== "") {
      next({path: "/"})
    } else {
      next()
    }
  } else if (getCookie("bitmark-webgui") === "") {
    next({path: "/login", query: {redirect: to.fullPath}})
  } else {
    next()
  }
})

var app = new Vue({
  router,
  el: '#main',
  render: h => h(Main)
})
<|endoftext|>


<commit_before>'use strict';

const path = require("path");
const fs = require("fs");

const mkdirp = require("mkdirp");
const async = require("async");
const npm = require("npm");
const rimraf = require("rimraf");

const installerConfig = require(path.normalize(process.env.PWD + "/../etc/config.js"));
const serviceModule = require("./service");
const mongoModule = require("./mongo");

//set the logger
const logger = require("../utils/utils.js").getLogger();

const SOAJS_RMS = {
	'urac': 'soajs.urac',
	'oauth': 'soajs.oauth',
	'dashboard': 'soajs.dashboard',
	'gateway': "soajs.controller",
	'ui': 'soajs.dashboard.ui'
};

function updateConfigFile(workingDirectory, cb) {
	installerConfig.workingDirectory = workingDirectory;
	let newData = "'use strict';\n\n";
	newData += "module.exports = " + JSON.stringify(installerConfig, null, 2) + ";\n";
	fs.writeFile(path.normalize(process.env.PWD + "/../etc/config.js"), newData, cb);
}

function installConsoleComponents(cb) {
	let myPath = installerConfig.workingDirectory + "/node_modules/";
	fs.stat(myPath, (error, stats) => {
		if (error) {
			if (error.code === 'ENOENT' && !stats) {
				//if not found create the directories needed recursively
				mkdirp(myPath, runNPM);
			}
			else {
				return cb(error);
			}
		}
		else {
			runNPM();
		}
	});

	//install repos in component
	function runNPM() {
		logger.debug("\nInstalling SOAJS Console Components ...");
		process.argv = [installerConfig.workingDirectory];
		npm.load({prefix: installerConfig.workingDirectory}, (err) => {
			if (err) {
				return cb(err);
			}

			async.eachOfSeries(SOAJS_RMS, (oneRepo, oneService, mCb) => {

				logger.info(`Installing ${oneService} from NPM ${oneRepo} in ${installerConfig.workingDirectory} ...`);
				npm.commands.install([oneRepo], (error) => {
					if (error) {
						return mCb(error);
					}

					logger.debug(`${oneService} installed!`);
					setTimeout(() => {
						return mCb(null, true);
					}, 500);
				});
			}, (error) => {
				if (error) {
					return cb(error);
				}

				return cb(null, true);
			});
		});
	}
}

const consoleModule = {

	/**
	 * This function configures and starts mongodb server stand alone
	 * then it patches the provisioned data in mongdb server
	 * then it installs all of SOAJS Console components
	 * then it starts all the SOAJS Console components
	 * @param args
	 * @param callback
	 */
	'install': (args, callback) => {
		if (args.length === 0) {
			return callback("Please provide where you want to install the SOAJS Console. Ex: soajs console install %folder_path%");
		}

		//clean up the path ...
		if (args[0].includes("node_modules")) {
			let myPath = args[0].split(path.sep);
			if (myPath[myPath.length - 1] === 'node_modules') {
				myPath.pop();
				myPath = myPath.join(path.sep);
				args[0] = myPath;
			}
		}

		logger.debug(`Checking provided path: ${args[0]} ...`);
		fs.stat(args[0], (error, stats) => {
			if (error) {
				if (error.code === 'ENOENT' && !stats) {
					//create the working directory
					mkdirp(path.normalize(args[0] + "/node_modules/"), (error) => {
						if (error) {
							return callback("Unable to work in provided folder path (might be permissions): " + args[0]);
						}
						updateConfiguration();
					});
				}
				else {
					return callback(error);
				}
			}
			else {
				updateConfiguration();
			}
		});

		function updateConfiguration() {
			logger.debug(`Configuring installer ...`);

			//update the configuration file
			installerConfig.workingDirectory = args[0];
			updateConfigFile(args[0], (error) => {
				if (error) {
					return callback("Unable to update Installer configuration file, please try again!");
				}

				//install and start mongo
				launchMongo();
			});
		}

		function launchMongo() {
			logger.debug(`Configuring MongoDB Server ...`);
			mongoModule.install([], (error, response) => {
				if (error) {
					return callback(error);
				}

				logger.debug(response);
				setTimeout(() => {
					logger.debug(`Starting MongoDB Server ...`);
					mongoModule.start([], (error, response) => {
						if (error) {
							return callback(error);
						}

						logger.debug(response);
						setTimeout(() => {

							logger.debug(`Importing Data in MongoDB Server ...`);
							mongoModule.patch([], (error, response) => {
								if (error) {
									return callback(error);
								}

								logger.debug(response);
								installSOAJSConsole();
							});
						}, 1000);
					});
				}, 100);
			});
		}

		function installSOAJSConsole() {
			logger.debug(`Installing SOAJS Console ...`);
			//install all repository content
			installConsoleComponents((error) => {
				if (error) {
					return callback("Error while isntalling the SOAJS Console files!")
				}

				//start microservices
				consoleModule.start(args, (error) => {
					if (error) {
						return callback("Unable to Start the SOAJS Console!");
					}

					return callback(null, "SOAJS Console Started!");
				});
			});
		}
	},

	/**
	 * This function will stop all the services of SOAJS Console
	 * it will then run npm install in the working directory to update all the microservices repos related
	 * then it will start the services of SOAJS Console again
	 * @param args
	 * @param callback
	 */
	'update': (args, callback) => {
		logger.info("Updating SOAJS Console ...\n\n");
		setTimeout(() => {
			//stop microservices
			consoleModule.stop(args, (error) => {
				if (error) {
					return callback("Unable to Stop the SOAJS Console!");
				}

				//update all repository content
				installConsoleComponents((error) => {
					if (error) {
						return callback("Error while updating the SOAJS Console files!")
					}

					//start microservices
					consoleModule.start(args, (error) => {
						if (error) {
							return callback("Unable to Restart the SOAJS Console!");
						}

						return callback(null, "SOAJS Console Updated!");
					});
				});
			});
		}, 2000);
	},

	/**
	 * This function will stop all services of SOAJS Console
	 * it will also stop mongodb and clean up all SOAJS data from the database
	 * Then it will remove all the installed files and folders of SOAJS Console (PURGE Everything)
	 * @param args
	 * @param callback
	 */
	'remove': (args, callback) => {
		logger.info("Removing SOAJS Console ...\n\n");
		setTimeout(() => {
			//stop microservices
			consoleModule.stop(args, (error) => {
				if (error) {
					return callback("Unable to Stop the SOAJS Console!");
				}

				const mongoModule = require("./mongo.js");
				logger.info("Cleaning up Mongo and stopping it ...");
				setTimeout(() => {
					//remove data from mongodb
					mongoModule.clean([], (error) => {
						if (error && !error.message.includes("failed to connect to server")) {
							return callback("Error while Cleaning provisioned data from mongo!");
						}
						//stop mongodb
						mongoModule.stop([], (error) => {
							if (error) {
								return callback("Error while Stopping MongoDB Server!");
							}

							logger.info("Cleaning up downloaded SOAJS Console ...");
							setTimeout(() => {
								//remove folders of microservices
								async.eachOfSeries(SOAJS_RMS, (oneRepo, oneService, mCb) => {
									logger.debug(`Removing ${oneService} files ...`);
									logger.debug(path.normalize(installerConfig.workingDirectory + "/node_modules/" + SOAJS_RMS[oneService]) + "\n");
									rimraf(path.normalize(installerConfig.workingDirectory + "/node_modules/" + SOAJS_RMS[oneService]), (error) => {
										if (error) {
											return mCb(error);
										}
										logger.debug(`${oneService} --> ${oneRepo}: Removed!`);
										return mCb();
									});
								}, (error) => {
									if (error) {
										return callback("Error Cleaning up SOAJS Console ...");
									}

									//remove working directory
									rimraf(path.normalize(installerConfig.workingDirectory), () => {

										//clean up the configuration file
										updateConfigFile('', (error) => {
											logger.info("=========================\nSOAJS Console Removed!\n=========================\n\n");
											setTimeout(() => {
												return callback();
											}, 1000);
										});
									});
								});

							}, 2000);
						});
					});
				}, 2000);
			});

		}, 2000);
	},

	/**
	 * This function restarts all the services of the SOAJS Console
	 * @param args
	 * @param callback
	 */
	'restart': (args, callback) => {
		logger.info("Restarting SOAJS Console ...\n\n");
		setTimeout(() => {
			consoleModule.stop(args, (error) => {
				if (error) {
					return callback("Unable to Stop the SOAJS Console!");
				}

				consoleModule.start(args, (error) => {
					if (error) {
						return callback("Unable to Restart the SOAJS Console!");
					}

					return callback(null, "SOAJS Console Restarted!");
				});
			});
		}, 2000);
	},

	/**
	 * This command will calculate the needed env variables and
	 * start all the microservices in dashboard environment that the soajs console requires
	 * @param args {Array}
	 * @param callback {Function}
	 */
	'start': (args, callback) => {
		let requestedEnvironment = 'dashboard';

		//check if service is installed and downloaded
		if (!installerConfig.workingDirectory || installerConfig.workingDirectory === '') {
			return callback(`SOAJS Console is not installed!`);
		}

		logger.debug("Checking MongoDB Server ....");
		mongoModule.start([], (error, response) => {
			if (error) {
				return callback(error);
			}

			logger.info("Starting Microservices for SOAJS Console in Dashboard Environment ... \n");
			setTimeout(() => {
				async.eachOfSeries(SOAJS_RMS, (oneRepo, oneService, mCb) => {
					launchMyService(oneService, (error, response) => {
						if (error) {
							return mCb(error);
						}

						if (response && response !== '') {
							logger.debug(response + "\n");
						}
						return mCb(null, true);
					});
				}, (error) => {
					if (error) {
						return callback("Error starting the SOAJS Console");
					}

					logger.info("=========================\nSOAJS Console started!\n=========================\n\n");
					setTimeout(() => {
						return callback();
					}, 1000);
				});
			}, 1000);
		});

		function launchMyService(oneService, mCb) {
			serviceModule.start([oneService, "--env=" + requestedEnvironment], mCb)
		}
	},

	/**
	 * This command will find the process id of all microservices that the soajs console is using and kill them
	 * @param args
	 * @param callback
	 * @returns {*}
	 */
	'stop': (args, callback) => {
		let requestedEnvironment = 'dashboard';

		//check if service is installed and downloaded
		if (!installerConfig.workingDirectory || installerConfig.workingDirectory === '') {
			return callback(`SOAJS Console is not installed!`);
		}

		logger.info("Stopping Microservices for SOAJS Console in Dashboard Environment ... \n");
		setTimeout(() => {
			async.eachOfSeries(SOAJS_RMS, (oneRepo, oneService, mCb) => {
				launchMyService(oneService, (error, response) => {
					if (error) {
						return mCb(error);
					}

					if (response && response !== '') {
						logger.debug(response + "\n");
					}

					return mCb(null, true);
				});
			}, (error) => {
				if (error) {
					return callback("Error stop the SOAJS Console");
				}

				logger.info("=========================\nSOAJS Console Stopped!\n=========================\n\n");
				setTimeout(() => {
					return callback();
				}, 1000);
			});

		}, 1000);

		function launchMyService(oneService, mCb) {
			serviceModule.stop([oneService, "--env=" + requestedEnvironment], mCb)
		}
	}
};

module.exports = consoleModule;<commit_msg>fixed issue detected on linux with npm install dependencies from git<commit_after>'use strict';

const path = require("path");
const fs = require("fs");

const mkdirp = require("mkdirp");
const async = require("async");
const rimraf = require("rimraf");
const exec = require("child_process").exec;

const installerConfig = require(path.normalize(process.env.PWD + "/../etc/config.js"));
const serviceModule = require("./service");
const mongoModule = require("./mongo");

//set the logger
const logger = require("../utils/utils.js").getLogger();

const SOAJS_RMS = {
	'urac': 'soajs.urac',
	'oauth': 'soajs.oauth',
	'dashboard': 'soajs.dashboard',
	'gateway': "soajs.controller",
	'ui': 'soajs.dashboard.ui'
};

function updateConfigFile(workingDirectory, cb) {
	installerConfig.workingDirectory = workingDirectory;
	let newData = "'use strict';\n\n";
	newData += "module.exports = " + JSON.stringify(installerConfig, null, 2) + ";\n";
	fs.writeFile(path.normalize(process.env.PWD + "/../etc/config.js"), newData, cb);
}

function installConsoleComponents(cb) {
	let myPath = installerConfig.workingDirectory + "/node_modules/";
	fs.stat(myPath, (error, stats) => {
		if (error) {
			if (error.code === 'ENOENT' && !stats) {
				//if not found create the directories needed recursively
				mkdirp(myPath, runNPM);
			}
			else {
				return cb(error);
			}
		}
		else {
			runNPM();
		}
	});

	//install repos in component
	function runNPM() {
		logger.debug("\nInstalling SOAJS Console Components ...");

		async.eachOfSeries(SOAJS_RMS, (oneRepo, oneService, mCb) => {

			logger.info(`Installing ${oneService} from NPM ${oneRepo} in ${installerConfig.workingDirectory} ...`);
			logger.debug(`sudo ${process.env.NPM_BIN} install ${oneRepo}`);
			let modInstall = exec(`sudo ${process.env.NPM_BIN} install ${oneRepo}`, {
				cwd: path.normalize(installerConfig.workingDirectory + "/node_modules")
			});

			modInstall.stdout.on('data', (data) => {
				if (data) {
					process.stdout.write(data);
				}
			});

			modInstall.stderr.on('data', (error) => {
				if (error) {
					process.stdout.write(error);
				}
			});

			modInstall.on('close', (code) => {
				if (code === 0) {
					logger.debug(`${oneService} installed!`);
					setTimeout(() => {
						return mCb(null, true);
					}, 500);
				}
				else {
					return mCb("Error installing " + oneService);
				}
			});
		}, (error) => {
			if (error) {
				return cb(error);
			}

			return cb(null, true);
		});
	}
}

const consoleModule = {

	/**
	 * This function configures and starts mongodb server stand alone
	 * then it patches the provisioned data in mongdb server
	 * then it installs all of SOAJS Console components
	 * then it starts all the SOAJS Console components
	 * @param args
	 * @param callback
	 */
	'install': (args, callback) => {
		if (args.length === 0) {
			return callback("Please provide where you want to install the SOAJS Console. Ex: soajs console install %folder_path%");
		}

		//clean up the path ...
		if (args[0].includes("node_modules")) {
			let myPath = args[0].split(path.sep);
			if (myPath[myPath.length - 1] === 'node_modules') {
				myPath.pop();
				myPath = myPath.join(path.sep);
				args[0] = myPath;
			}
		}

		logger.debug(`Checking provided path: ${args[0]} ...`);
		fs.stat(args[0], (error, stats) => {
			if (error) {
				if (error.code === 'ENOENT' && !stats) {
					//create the working directory
					mkdirp(path.normalize(args[0] + "/node_modules/"), (error) => {
						if (error) {
							return callback("Unable to work in provided folder path (might be permissions): " + args[0]);
						}
						updateConfiguration();
					});
				}
				else {
					return callback(error);
				}
			}
			else {
				updateConfiguration();
			}
		});

		function updateConfiguration() {
			logger.debug(`Configuring installer ...`);

			//update the configuration file
			installerConfig.workingDirectory = args[0];
			updateConfigFile(args[0], (error) => {
				if (error) {
					return callback("Unable to update Installer configuration file, please try again!");
				}

				//install and start mongo
				launchMongo();
			});
		}

		function launchMongo() {
			logger.debug(`Configuring MongoDB Server ...`);
			mongoModule.install([], (error, response) => {
				if (error) {
					return callback(error);
				}

				logger.debug(response);
				setTimeout(() => {
					logger.debug(`Starting MongoDB Server ...`);
					mongoModule.start([], (error, response) => {
						if (error) {
							return callback(error);
						}

						logger.debug(response);
						setTimeout(() => {

							logger.debug(`Importing Data in MongoDB Server ...`);
							mongoModule.patch([], (error, response) => {
								if (error) {
									return callback(error);
								}

								logger.debug(response);
								installSOAJSConsole();
							});
						}, 1000);
					});
				}, 100);
			});
		}

		function installSOAJSConsole() {
			logger.debug(`Installing SOAJS Console ...`);
			//install all repository content
			installConsoleComponents((error) => {
				if (error) {
					return callback("Error while isntalling the SOAJS Console files!")
				}

				//start microservices
				consoleModule.start(args, (error) => {
					if (error) {
						return callback("Unable to Start the SOAJS Console!");
					}

					return callback(null, "SOAJS Console Started!");
				});
			});
		}
	},

	/**
	 * This function will stop all the services of SOAJS Console
	 * it will then run npm install in the working directory to update all the microservices repos related
	 * then it will start the services of SOAJS Console again
	 * @param args
	 * @param callback
	 */
	'update': (args, callback) => {
		logger.info("Updating SOAJS Console ...\n\n");
		setTimeout(() => {
			//stop microservices
			consoleModule.stop(args, (error) => {
				if (error) {
					return callback("Unable to Stop the SOAJS Console!");
				}

				//update all repository content
				installConsoleComponents((error) => {
					if (error) {
						return callback("Error while updating the SOAJS Console files!")
					}

					//start microservices
					consoleModule.start(args, (error) => {
						if (error) {
							return callback("Unable to Restart the SOAJS Console!");
						}

						return callback(null, "SOAJS Console Updated!");
					});
				});
			});
		}, 2000);
	},

	/**
	 * This function will stop all services of SOAJS Console
	 * it will also stop mongodb and clean up all SOAJS data from the database
	 * Then it will remove all the installed files and folders of SOAJS Console (PURGE Everything)
	 * @param args
	 * @param callback
	 */
	'remove': (args, callback) => {
		logger.info("Removing SOAJS Console ...\n\n");
		setTimeout(() => {
			//stop microservices
			consoleModule.stop(args, (error) => {
				if (error) {
					return callback("Unable to Stop the SOAJS Console!");
				}

				const mongoModule = require("./mongo.js");
				logger.info("Cleaning up Mongo and stopping it ...");
				setTimeout(() => {
					//remove data from mongodb
					mongoModule.clean([], (error) => {
						if (error && !error.message.includes("failed to connect to server")) {
							return callback("Error while Cleaning provisioned data from mongo!");
						}
						//stop mongodb
						mongoModule.stop([], (error) => {
							if (error) {
								return callback("Error while Stopping MongoDB Server!");
							}

							logger.info("Cleaning up downloaded SOAJS Console ...");
							setTimeout(() => {
								//remove folders of microservices
								async.eachOfSeries(SOAJS_RMS, (oneRepo, oneService, mCb) => {
									logger.debug(`Removing ${oneService} files ...`);
									logger.debug(path.normalize(installerConfig.workingDirectory + "/node_modules/" + SOAJS_RMS[oneService]) + "\n");
									rimraf(path.normalize(installerConfig.workingDirectory + "/node_modules/" + SOAJS_RMS[oneService]), (error) => {
										if (error) {
											return mCb(error);
										}
										logger.debug(`${oneService} --> ${oneRepo}: Removed!`);
										return mCb();
									});
								}, (error) => {
									if (error) {
										return callback("Error Cleaning up SOAJS Console ...");
									}

									//remove working directory
									rimraf(path.normalize(installerConfig.workingDirectory), () => {

										//clean up the configuration file
										updateConfigFile('', (error) => {
											logger.info("=========================\nSOAJS Console Removed!\n=========================\n\n");
											setTimeout(() => {
												return callback();
											}, 1000);
										});
									});
								});

							}, 2000);
						});
					});
				}, 2000);
			});

		}, 2000);
	},

	/**
	 * This function restarts all the services of the SOAJS Console
	 * @param args
	 * @param callback
	 */
	'restart': (args, callback) => {
		logger.info("Restarting SOAJS Console ...\n\n");
		setTimeout(() => {
			consoleModule.stop(args, (error) => {
				if (error) {
					return callback("Unable to Stop the SOAJS Console!");
				}

				consoleModule.start(args, (error) => {
					if (error) {
						return callback("Unable to Restart the SOAJS Console!");
					}

					return callback(null, "SOAJS Console Restarted!");
				});
			});
		}, 2000);
	},

	/**
	 * This command will calculate the needed env variables and
	 * start all the microservices in dashboard environment that the soajs console requires
	 * @param args {Array}
	 * @param callback {Function}
	 */
	'start': (args, callback) => {
		let requestedEnvironment = 'dashboard';

		//check if service is installed and downloaded
		if (!installerConfig.workingDirectory || installerConfig.workingDirectory === '') {
			return callback(`SOAJS Console is not installed!`);
		}

		logger.debug("Checking MongoDB Server ....");
		mongoModule.start([], (error, response) => {
			if (error) {
				return callback(error);
			}

			logger.info("Starting Microservices for SOAJS Console in Dashboard Environment ... \n");
			setTimeout(() => {
				async.eachOfSeries(SOAJS_RMS, (oneRepo, oneService, mCb) => {
					launchMyService(oneService, (error, response) => {
						if (error) {
							return mCb(error);
						}

						if (response && response !== '') {
							logger.debug(response + "\n");
						}
						return mCb(null, true);
					});
				}, (error) => {
					if (error) {
						return callback("Error starting the SOAJS Console");
					}

					logger.info("=========================\nSOAJS Console started!\n=========================\n\n");
					setTimeout(() => {
						return callback();
					}, 1000);
				});
			}, 1000);
		});

		function launchMyService(oneService, mCb) {
			serviceModule.start([oneService, "--env=" + requestedEnvironment], mCb)
		}
	},

	/**
	 * This command will find the process id of all microservices that the soajs console is using and kill them
	 * @param args
	 * @param callback
	 * @returns {*}
	 */
	'stop': (args, callback) => {
		let requestedEnvironment = 'dashboard';

		//check if service is installed and downloaded
		if (!installerConfig.workingDirectory || installerConfig.workingDirectory === '') {
			return callback(`SOAJS Console is not installed!`);
		}

		logger.info("Stopping Microservices for SOAJS Console in Dashboard Environment ... \n");
		setTimeout(() => {
			async.eachOfSeries(SOAJS_RMS, (oneRepo, oneService, mCb) => {
				launchMyService(oneService, (error, response) => {
					if (error) {
						return mCb(error);
					}

					if (response && response !== '') {
						logger.debug(response + "\n");
					}

					return mCb(null, true);
				});
			}, (error) => {
				if (error) {
					return callback("Error stop the SOAJS Console");
				}

				logger.info("=========================\nSOAJS Console Stopped!\n=========================\n\n");
				setTimeout(() => {
					return callback();
				}, 1000);
			});

		}, 1000);

		function launchMyService(oneService, mCb) {
			serviceModule.stop([oneService, "--env=" + requestedEnvironment], mCb)
		}
	}
};

module.exports = consoleModule;<|endoftext|>


<commit_before>define(['js/ui/View', 'js/type/Color'], function (View, Color) {

    return View.inherit('js.ui.ColorPickerClass', {
        defaults: {
            color: Color.HSB,
            paletteSize: 300,
            _palettePosition: {
                x: 0,
                y: 0
            },
            _scale: 0
        },

        events: ['on:selectColor'],

        _imageMouseDown: function (e) {
            e.preventDefault();
        },

        _paletteMouseDown: function (e) {
            this.$mouseDown = true;
            var domEvent = e.pointerEvent,
                pos = this.globalToLocal({x: domEvent.pageX, y: domEvent.pageY});

            e.preventDefault();
            var self = this;
            if(!this.$moveHandler){
                this.$moveHandler = function (e) {
                    e.preventDefault && e.preventDefault();
                    e.stopPropagation();

                    if (self.$mouseDown) {
                        var pos = self.$.paletteImage.globalToLocal({x: e.pageX, y: e.pageY});

                        self._updateColorAndPaletteCursor(pos);
                        self._triggerColorChange();
                    }
                    return false;
                };
            }

            if(!this.$upHandler){
                this.$upHandler = function () {
                    self.$mouseDown = false;

                    self.dom(self.$stage.$window).unbindDomEvent('pointermove', self.$moveHandler);
                    self.dom(self.$stage.$window).unbindDomEvent('pointerup', self.$upHandler);

                };
            }

            this.dom(this.$stage.$window).bindDomEvent('pointermove', this.$moveHandler);
            this.dom(this.$stage.$window).bindDomEvent('pointerup', this.$upHandler);

            this._updateColorAndPaletteCursor(pos);
            this._triggerColorChange();
        },

        _updateColorAndPaletteCursor: function (pos) {
            pos.x = pos.x < 0 ? 0 : pos.x;
            pos.x = pos.x > this.$.paletteSize ? this.$.paletteSize : pos.x;
            pos.y = pos.y < 0 ? 0 : pos.y;
            pos.y = pos.y > this.$.paletteSize ? this.$.paletteSize : pos.y;
            var b = 100 * (1 - (pos.y / this.$.paletteSize)),
                s = 100 * (pos.x / this.$.paletteSize);

            var hsbColor = this.$.color.toHSB();

            this.set('color', new Color.HSB(hsbColor.h, Math.round(s), Math.round(b)));
        },
        _updateColorAndHueCursor: function (scale) {
            scale = scale < 0 ? 0 : scale;
            scale = scale > this.$.paletteSize ? this.$.paletteSize : scale;

            var hsbColor = this.$.color.toHSB(),
                hue = Math.round(360 * (1 - scale / this.$.paletteSize));

            hue = hue >= 360 ? 359 : hue;

            this.set('color', new Color.HSB(hue, hsbColor.s, hsbColor.b));
        },

        _triggerColorChange: function(){
            this.$triggerColorTimeout && clearTimeout(this.$triggerColorTimeout);

            var self = this;

            this.$triggerColorTimeout = setTimeout(function(){
                self.trigger('on:selectColor', self.$.color);
            },300);
        },

        _renderColor: function(color){
            if(color){
                var hsbColor = color.toHSB();
                var pos = {
                    x: Math.round(this.$.paletteSize * hsbColor.s * 0.01),
                    y: Math.round(this.$.paletteSize * (1 - hsbColor.b * 0.01))
                };
                this.set({
                    '_palettePosition': pos,
                    '_scale': Math.round(this.$.paletteSize * (1 - hsbColor.h / 360))
                });
            }
        },
        _commitColor: function(color, oldColor){
            if(color){
                if(!oldColor || color.toHSB().h !== oldColor.toHSB().h){
                    this.trigger('hueChanged');
                }
            }
        },

        _hueBarDown: function (e) {
            this.$hueBarDown = true;
            var self = this;
            if(!this.$hueBarMoveHandler){
                this.$hueBarMoveHandler = function(e){
                    e.preventDefault && e.preventDefault();

                    e.stopPropagation();
                    if (self.$hueBarDown) {
                        self._updateColorAndHueCursor(self.$.hueBar.globalToLocal({x: 0, y: e.pageY}).y);
                        self._triggerColorChange();
                    }
                    return false;
                };
            }
            if(!this.$hueBarUpHandler){
                this.$hueBarUpHandler = function(e){
                    self.$hueBarDown = false;
                    self.dom(self.$stage.$window).unbindDomEvent('pointermove', self.$hueBarMoveHandler);
                    self.dom(self.$stage.$window).unbindDomEvent('pointerup', self.$hueBarUpHandler);

                }
            }

            this.dom(this.$stage.$window).bindDomEvent('pointermove', this.$hueBarMoveHandler);
            this.dom(this.$stage.$window).bindDomEvent('pointerup', this.$hueBarUpHandler);

            this._updateColorAndHueCursor(e.target.globalToLocal({x: 0, y: e.pointerEvent.pageY}).y);
            this._triggerColorChange();
        },

        _backgroundColor: function () {
            if (this.$.color) {
                var hsbColor = this.$.color.toHSB();
                return new Color.HSB(hsbColor.h, 100, 100).toRGB();
            }

            return Color.RGB(0, 0, 0);

        }.on('hueChanged'),

        _preventDefault: function(e){
            e.preventDefault();
        }

    })
});<commit_msg>fixed handling of touch events<commit_after>define(['js/ui/View', 'js/type/Color'], function (View, Color) {

    return View.inherit('js.ui.ColorPickerClass', {
        defaults: {
            color: Color.HSB,
            paletteSize: 300,
            _palettePosition: {
                x: 0,
                y: 0
            },
            _scale: 0
        },

        events: ['on:selectColor'],

        _imageMouseDown: function (e) {
            e.preventDefault();
        },

        _paletteMouseDown: function (e) {
            this.$mouseDown = true;
            var domEvent = e.pointerEvent,
                pos = this.globalToLocal({x: domEvent.pageX, y: domEvent.pageY});

            e.preventDefault();
            var self = this;
            if(!this.$moveHandler){
                this.$moveHandler = function (e) {
                    e.preventDefault && e.preventDefault();
                    e.stopPropagation();

                    if (self.$mouseDown) {
                        if(e.changedTouches){
                            e = e.changedTouches[0];
                        }
                        var pos = self.$.paletteImage.globalToLocal({x: e.pageX, y: e.pageY});

                        self._updateColorAndPaletteCursor(pos);
                        self._triggerColorChange();
                    }
                    return false;
                };
            }

            if(!this.$upHandler){
                this.$upHandler = function () {
                    self.$mouseDown = false;

                    self.dom(self.$stage.$window).unbindDomEvent('pointermove', self.$moveHandler);
                    self.dom(self.$stage.$window).unbindDomEvent('pointerup', self.$upHandler);

                };
            }

            this.dom(this.$stage.$window).bindDomEvent('pointermove', this.$moveHandler);
            this.dom(this.$stage.$window).bindDomEvent('pointerup', this.$upHandler);

            this._updateColorAndPaletteCursor(pos);
            this._triggerColorChange();
        },

        _updateColorAndPaletteCursor: function (pos) {
            pos.x = pos.x < 0 ? 0 : pos.x;
            pos.x = pos.x > this.$.paletteSize ? this.$.paletteSize : pos.x;
            pos.y = pos.y < 0 ? 0 : pos.y;
            pos.y = pos.y > this.$.paletteSize ? this.$.paletteSize : pos.y;
            var b = 100 * (1 - (pos.y / this.$.paletteSize)),
                s = 100 * (pos.x / this.$.paletteSize);

            var hsbColor = this.$.color.toHSB();

            this.set('color', new Color.HSB(hsbColor.h, Math.round(s), Math.round(b)));
        },
        _updateColorAndHueCursor: function (scale) {
            scale = scale < 0 ? 0 : scale;
            scale = scale > this.$.paletteSize ? this.$.paletteSize : scale;

            var hsbColor = this.$.color.toHSB(),
                hue = Math.round(360 * (1 - scale / this.$.paletteSize));

            hue = hue >= 360 ? 359 : hue;

            this.set('color', new Color.HSB(hue, hsbColor.s, hsbColor.b));
        },

        _triggerColorChange: function(){
            this.$triggerColorTimeout && clearTimeout(this.$triggerColorTimeout);

            var self = this;

            this.$triggerColorTimeout = setTimeout(function(){
                self.trigger('on:selectColor', self.$.color);
            },300);
        },

        _renderColor: function(color){
            if(color){
                var hsbColor = color.toHSB();
                var pos = {
                    x: Math.round(this.$.paletteSize * hsbColor.s * 0.01),
                    y: Math.round(this.$.paletteSize * (1 - hsbColor.b * 0.01))
                };
                this.set({
                    '_palettePosition': pos,
                    '_scale': Math.round(this.$.paletteSize * (1 - hsbColor.h / 360))
                });
            }
        },
        _commitColor: function(color, oldColor){
            if(color){
                if(!oldColor || color.toHSB().h !== oldColor.toHSB().h){
                    this.trigger('hueChanged');
                }
            }
        },

        _hueBarDown: function (e) {
            this.$hueBarDown = true;
            var self = this;
            if(!this.$hueBarMoveHandler){
                this.$hueBarMoveHandler = function(e){
                    e.preventDefault && e.preventDefault();

                    e.stopPropagation();
                    if (self.$hueBarDown) {
                        if (e.changedTouches) {
                            e = e.changedTouches[0];
                        }

                        self._updateColorAndHueCursor(self.$.hueBar.globalToLocal({x: 0, y: e.pageY}).y);
                        self._triggerColorChange();
                    }
                    return false;
                };
            }
            if(!this.$hueBarUpHandler){
                this.$hueBarUpHandler = function(e){
                    self.$hueBarDown = false;
                    self.dom(self.$stage.$window).unbindDomEvent('pointermove', self.$hueBarMoveHandler);
                    self.dom(self.$stage.$window).unbindDomEvent('pointerup', self.$hueBarUpHandler);

                }
            }

            this.dom(this.$stage.$window).bindDomEvent('pointermove', this.$hueBarMoveHandler);
            this.dom(this.$stage.$window).bindDomEvent('pointerup', this.$hueBarUpHandler);

            this._updateColorAndHueCursor(e.target.globalToLocal({x: 0, y: e.pointerEvent.pageY}).y);
            this._triggerColorChange();
        },

        _backgroundColor: function () {
            if (this.$.color) {
                var hsbColor = this.$.color.toHSB();
                return new Color.HSB(hsbColor.h, 100, 100).toRGB();
            }

            return Color.RGB(0, 0, 0);

        }.on('hueChanged'),

        _preventDefault: function(e){
            e.preventDefault();
        }

    })
});<|endoftext|>


<commit_before>
var Mongoose = require('mongoose');

var ProjectSchema = new Mongoose.Schema({
  "title": String,
  "date": Date,
  "summary": String,
  "image": String
});

exports.Project = Mongoose.model('Project', ProjectSchema);

<commit_msg>tweaking heroku<commit_after>
var Mongoose = require('mongoose');

var ProjectSchema = new Mongoose.Schema({
  "title": String,
  "date": Date,
  "summary": String,
  "image": String
});

exports.Project = Mongoose.model('Project', ProjectSchema);

<|endoftext|>


<commit_before>import config from '../config';
import webPush from 'web-push';
import Tarantool from '../db/tarantool';

webPush.setGCMAPIKey(config.gcm_key);

function notify(account, nparams, title, body, url) {
     var payload = JSON.stringify({
        title,
        body,
        url,
        icon: 'https://steemit.com/favicon.ico'
    });
    return new Promise((resolve, reject) => {
        webPush.sendNotification(nparams, payload).then(function() {
            resolve(account);
        }, function(err) {
            reject(err);
        });
    });
}

async function process_queue() {
    console.log('-- processing web push notifications queue -->');
    try {
        const queue = await Tarantool.instance().call('webpush_get_delivery_queue');
        for (const n of queue) {
            if (n.length === 0) return;
            const [account, nparams_array, title, body, url] = n;
            console.log('-- notification -->', account, body, url);
            for (const nparams of nparams_array) {
                try {
                    await notify(account, nparams, title, body, url);
                } catch (err) {
                    console.error('-- error in notify -->', account, err);
                }
            }
            break;
        }
        // console.log('-- run.run -->', queue);
    } catch (error) {
        console.error('-- process_queue error -->', error);
    }
}

function run() {
    process_queue().then(() => {
       setTimeout(run, 30000);
    });
}

run();

<commit_msg>add profile pics support to notifications<commit_after>import config from '../config';
import webPush from 'web-push';
import Tarantool from '../db/tarantool';

webPush.setGCMAPIKey(config.gcm_key);

function notify(account, nparams, title, body, url, pic) {
     var payload = JSON.stringify({
        title,
        body,
        url,
        icon: pic || 'https://steemit.com/favicon.ico'
    });
    return new Promise((resolve, reject) => {
        webPush.sendNotification(nparams, payload).then(function() {
            resolve(account);
        }, function(err) {
            reject(err);
        });
    });
}

async function process_queue() {
    console.log('-- processing web push notifications queue -->');
    try {
        const queue = await Tarantool.instance().call('webpush_get_delivery_queue');
        for (const n of queue) {
            if (n.length === 0) return;
            const [account, nparams_array, title, body, url, pic] = n;
            console.log('-- notification -->', account, body, url, pic);
            for (const nparams of nparams_array) {
                try {
                    await notify(account, nparams, title, body, url, pic);
                } catch (err) {
                    console.error('-- error in notify -->', account, err);
                }
            }
            break;
        }
        // console.log('-- run.run -->', queue);
    } catch (error) {
        console.error('-- process_queue error -->', error);
    }
}

function run() {
    process_queue().then(() => {
       setTimeout(run, 30000);
    });
}

run();

<|endoftext|>


<commit_before>'use strict';

angular.module('Marvin.Services')
  .factory('IMS', function($http, SERVICES, $q){
  var url = SERVICES.IMS;

  /**
  * Check for a valid UUID.
   *
  * @param check A string to check for a UUID.
  * @returns {boolean} True if a valid UUID.
  */
  function validUUID(check){
    return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(check);
  }

  /**
  * Returns a rejected promise with an appropriate error message.
  *
  * @param message An error message to send.
  * @returns {Promise} A rejected promise containing the error message.
  */
  function errorPromise(message){
    var deferred = $q.defer();
    deferred.reject({message: message});
    return deferred.promise;
  }

  /**
  * Searches for a query from IMS.
  *
  * @param query A valid Lucene query against the database.
  * @param count The number of results to be returned.
  * @param offset The offset.
  * @returns {HttpPromise}
  */
  function search(query, count, offset){
    var paramString = [];

    paramString.push('q=' + query);

    if (angular.isDefined(count)){
      paramString.push('count=' + count);
    }

    if (angular.isDefined(offset)){
      paramString.push('offset=' + offset);
    }

    return $http.get(url + '/search?' + paramString.join('&'));
  }

  function getBook(uuid){
    if (! validUUID(uuid)) {
      return errorPromise('Invalid UUID for book.');
    }

    return $http.get(url + '/books/' + uuid);
  }

  return {
    search: search,
    getBook: getBook
  };
});<commit_msg>Additional documentation for the service.<commit_after>'use strict';

/**
* IMS Service
*
* Interacts with the IMS service
*/
angular.module('Marvin.Services')
  .factory('IMS', function($http, SERVICES, $q){
  var url = SERVICES.IMS;

  /**
  * Check for a valid UUID.
   *
  * @param check A string to check for a UUID.
  * @returns {boolean} True if a valid UUID.
  */
  function validUUID(check){
    return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(check);
  }

  /**
  * Returns a rejected promise with an appropriate error message.
  *
  * @param message An error message to send.
  * @returns {Promise} A rejected promise containing the error message.
  */
  function errorPromise(message){
    var deferred = $q.defer();
    deferred.reject({message: message});
    return deferred.promise;
  }

  /**
  * Searches for a query from IMS.
  *
  * @param query A valid Lucene query against the database.
  * @param count The number of results to be returned.
  * @param offset The offset.
  * @returns {HttpPromise} A promise for the search.
  */
  function search(query, count, offset){
    var paramString = [];

    paramString.push('q=' + query);

    if (angular.isDefined(count)){
      paramString.push('count=' + count);
    }

    if (angular.isDefined(offset)){
      paramString.push('offset=' + offset);
    }

    return $http.get(url + '/search?' + paramString.join('&'));
  }

  /**
  * Gets a book from IMS.
  *
  * @param uuid A valid UUID of a book to locate.
  * @returns {Promise} A promise for the HTTP or a rejection if the UUID is wrong.
  */
  function getBook(uuid){
    if (! validUUID(uuid)) {
      return errorPromise('Invalid UUID for book.');
    }

    return $http.get(url + '/books/' + uuid);
  }

  return {
    search: search,
    getBook: getBook
  };
});<|endoftext|>


<commit_before>/*! UIkit 2.24.3 | http://www.getuikit.com | (c) 2014 YOOtheme | MIT License */
!function(i){var t;window.UIkit&&(t=i(UIkit)),"function"==typeof define&&define.amd&&define("uikit-lightbox",["uikit"],function(){return t||i(UIkit)})}(function(i){"use strict";function t(t){return e?(e.lightbox=t,e):(e=i.$(['
','
','','

','

',"
","
"].join("")).appendTo("body"),e.dialog=e.find(".uk-modal-dialog:first"),e.content=e.find(".uk-lightbox-content:first"),e.loader=e.find(".uk-modal-spinner:first"),e.closer=e.find(".uk-close.uk-close-alt"),e.modal=i.modal(e,{modal:!1}),e.on("swipeRight swipeLeft",function(i){e.lightbox["swipeLeft"==i.type?"next":"previous"]()}).on("click","[data-lightbox-previous], [data-lightbox-next]",function(t){t.preventDefault(),e.lightbox[i.$(this).is("[data-lightbox-next]")?"next":"previous"]()}),e.on("hide.uk.modal",function(){e.content.html("")}),i.$win.on("load resize orientationchange",i.Utils.debounce(function(){e.is(":visible")&&!i.Utils.isFullscreen()&&e.lightbox.fitSize()}.bind(this),100)),e.lightbox=t,e)}var e,o={};return i.component("lightbox",{defaults:{group:!1,duration:400,keyboard:!0},index:0,items:!1,boot:function(){i.$html.on("click","[data-uk-lightbox]",function(t){t.preventDefault();var e=i.$(this);e.data("lightbox")||i.lightbox(e,i.Utils.options(e.attr("data-uk-lightbox"))),e.data("lightbox").show(e)}),i.$doc.on("keyup",function(i){if(e&&e.is(":visible")&&e.lightbox.options.keyboard)switch(i.preventDefault(),i.keyCode){case 37:e.lightbox.previous();break;case 39:e.lightbox.next()}})},init:function(){var t=[];if(this.index=0,this.siblings=[],this.element&&this.element.length){var e=this.options.group?i.$(['[data-uk-lightbox*="'+this.options.group+'"]',"[data-uk-lightbox*='"+this.options.group+"']"].join(",")):this.element;e.each(function(){var e=i.$(this);t.push({source:e.attr("href"),title:e.attr("data-title")||e.attr("title"),type:e.attr("data-lightbox-type")||"auto",link:e})}),this.index=e.index(this.element),this.siblings=t}else this.options.group&&this.options.group.length&&(this.siblings=this.options.group);this.trigger("lightbox-init",[this])},show:function(e){this.modal=t(this),this.modal.dialog.stop(),this.modal.content.stop();var o,n,s=this,h=i.$.Deferred();e=e||0,"object"==typeof e&&this.siblings.forEach(function(i,t){e[0]===i.link[0]&&(e=t)}),0>e?e=this.siblings.length-e:this.siblings[e]||(e=0),n=this.siblings[e],o={lightbox:s,source:n.source,type:n.type,index:e,promise:h,title:n.title,item:n,meta:{content:"",width:null,height:null}},this.index=e,this.modal.content.empty(),this.modal.is(":visible")||(this.modal.content.css({width:"",height:""}).empty(),this.modal.modal.show()),this.modal.loader.removeClass("uk-hidden"),h.promise().done(function(){s.data=o,s.fitSize(o)}).fail(function(){o.meta.content='
Loading resource failed!
',o.meta.width=400,o.meta.height=300,s.data=o,s.fitSize(o)}),s.trigger("showitem.uk.lightbox",[o])},fitSize:function(){var t=this,e=this.data,o=this.modal.dialog.outerWidth()-this.modal.dialog.width(),n=parseInt(this.modal.dialog.css("margin-top"),10),s=parseInt(this.modal.dialog.css("margin-bottom"),10),h=n+s,a=e.meta.content,d=t.options.duration;this.siblings.length>1&&(a=[a,'',''].join(""));var l,r,u=i.$("

").css({opacity:0,position:"absolute",top:0,left:0,width:"100%","max-width":t.modal.dialog.css("max-width"),padding:t.modal.dialog.css("padding"),margin:t.modal.dialog.css("margin")}),c=e.meta.width,g=e.meta.height;u.appendTo("body").width(),l=u.width(),r=window.innerHeight-h,u.remove(),this.modal.dialog.find(".uk-modal-caption").remove(),e.title&&(this.modal.dialog.append('
'+e.title+"
"),r-=this.modal.dialog.find(".uk-modal-caption").outerHeight()),l<e.meta.width&&(g=Math.floor(g*(l/c)),c=l),g>r&&(g=Math.floor(r),c=Math.ceil(e.meta.width*(r/e.meta.height))),this.modal.content.css("opacity",0).width(c).html(a),"iframe"==e.type&&this.modal.content.find("iframe:first").height(g);var m=g+o,p=Math.floor(window.innerHeight/2-m/2)-h;0>p&&(p=0),this.modal.closer.addClass("uk-hidden"),t.modal.data("mwidth")==c&&t.modal.data("mheight")==g&&(d=0),this.modal.dialog.animate({width:c+o,height:g+o,top:p},d,"swing",function(){t.modal.loader.addClass("uk-hidden"),t.modal.content.css({width:""}).animate({opacity:1},function(){t.modal.closer.removeClass("uk-hidden")}),t.modal.data({mwidth:c,mheight:g})})},next:function(){this.show(this.siblings[this.index+1]?this.index+1:0)},previous:function(){this.show(this.siblings[this.index-1]?this.index-1:this.siblings.length-1)}}),i.plugin("lightbox","image",{init:function(i){i.on("showitem.uk.lightbox",function(i,t){if("image"==t.type||t.source&&t.source.match(/\.(jpg|jpeg|png|gif|svg)$/i)){var e=function(i,e,o){t.meta={content:'',width:e,height:o},t.type="image",t.promise.resolve()};if(o[t.source])e(t.source,o[t.source].width,o[t.source].height);else{var n=new Image;n.onerror=function(){t.promise.reject("Loading image failed")},n.onload=function(){o[t.source]={width:n.width,height:n.height},e(t.source,o[t.source].width,o[t.source].height)},n.src=t.source}}})}}),i.plugin("lightbox","youtube",{init:function(i){var t=/(\/\/.*?youtube\.[a-z]+)\/watch\?v=([^&]+)&?(.*)/,e=/youtu\.be\/(.*)/;i.on("showitem.uk.lightbox",function(i,n){var s,h,a=function(i,t,e){n.meta={content:'',width:t,height:e},n.type="iframe",n.promise.resolve()};if((h=n.source.match(t))&&(s=h[2]),(h=n.source.match(e))&&(s=h[1]),s){if(o[s])a(s,o[s].width,o[s].height);else{var d=new Image,l=!1;d.onerror=function(){o[s]={width:640,height:320},a(s,o[s].width,o[s].height)},d.onload=function(){120==d.width&&90==d.height?l?(o[s]={width:640,height:320},a(s,o[s].width,o[s].height)):(l=!0,d.src="//img.youtube.com/vi/"+s+"/0.jpg"):(o[s]={width:d.width,height:d.height},a(s,d.width,d.height))},d.src="//img.youtube.com/vi/"+s+"/maxresdefault.jpg"}i.stopImmediatePropagation()}})}}),i.plugin("lightbox","vimeo",{init:function(t){var e,n=/(\/\/.*?)vimeo\.[a-z]+\/([0-9]+).*?/;t.on("showitem.uk.lightbox",function(t,s){var h,a=function(i,t,e){s.meta={content:'',width:t,height:e},s.type="iframe",s.promise.resolve()};(e=s.source.match(n))&&(h=e[2],o[h]?a(h,o[h].width,o[h].height):i.$.ajax({type:"GET",url:"http://vimeo.com/api/oembed.json?url="+encodeURI(s.source),jsonp:"callback",dataType:"jsonp",success:function(i){o[h]={width:i.width,height:i.height},a(h,o[h].width,o[h].height)}}),t.stopImmediatePropagation())})}}),i.plugin("lightbox","video",{init:function(t){t.on("showitem.uk.lightbox",function(t,e){var n=function(i,t,o){e.meta={content:'<video class="uk-responsive-width" src="'+i+'" width="'+t+'" height="'+o+'" controls></video>',width:t,height:o},e.type="video",e.promise.resolve()};if("video"==e.type||e.source.match(/\.(mp4|webm|ogv)$/i))if(o[e.source])n(e.source,o[e.source].width,o[e.source].height);else var s=i.$('<video style="position:fixed;visibility:hidden;top:-10000px;"></video>').attr("src",e.source).appendTo("body"),h=setInterval(function(){s[0].videoWidth&&(clearInterval(h),o[e.source]={width:s[0].videoWidth,height:s[0].videoHeight},n(e.source,o[e.source].width,o[e.source].height),s.remove())},20)})}}),i.lightbox.create=function(t,e){if(t){var o,n=[];return t.forEach(function(t){n.push(i.$.extend({source:"",title:"",type:"auto",link:!1},"string"==typeof t?{source:t}:t))}),o=i.lightbox(i.$.extend({},e,{group:n}))}},i.lightbox});<commit_msg>UIkit 2.26.2<commit_after>/*! UIkit 2.26.2 | http://www.getuikit.com | (c) 2014 YOOtheme | MIT License */
!function(i){var t;window.UIkit&&(t=i(UIkit)),"function"==typeof define&&define.amd&&define("uikit-lightbox",["uikit"],function(){return t||i(UIkit)})}(function(i){"use strict";function t(t){return e?(e.lightbox=t,e):(e=i.$(['
','
','','

','

',"
","
"].join("")).appendTo("body"),e.dialog=e.find(".uk-modal-dialog:first"),e.content=e.find(".uk-lightbox-content:first"),e.loader=e.find(".uk-modal-spinner:first"),e.closer=e.find(".uk-close.uk-close-alt"),e.modal=i.modal(e,{modal:!1}),e.on("swipeRight swipeLeft",function(i){e.lightbox["swipeLeft"==i.type?"next":"previous"]()}).on("click","[data-lightbox-previous], [data-lightbox-next]",function(t){t.preventDefault(),e.lightbox[i.$(this).is("[data-lightbox-next]")?"next":"previous"]()}),e.on("hide.uk.modal",function(){e.content.html("")}),i.$win.on("load resize orientationchange",i.Utils.debounce(function(){e.is(":visible")&&!i.Utils.isFullscreen()&&e.lightbox.fitSize()}.bind(this),100)),e.lightbox=t,e)}var e,o={};return i.component("lightbox",{defaults:{group:!1,duration:400,keyboard:!0},index:0,items:!1,boot:function(){i.$html.on("click","[data-uk-lightbox]",function(t){t.preventDefault();var e=i.$(this);e.data("lightbox")||i.lightbox(e,i.Utils.options(e.attr("data-uk-lightbox"))),e.data("lightbox").show(e)}),i.$doc.on("keyup",function(i){if(e&&e.is(":visible")&&e.lightbox.options.keyboard)switch(i.preventDefault(),i.keyCode){case 37:e.lightbox.previous();break;case 39:e.lightbox.next()}})},init:function(){var t=[];if(this.index=0,this.siblings=[],this.element&&this.element.length){var e=this.options.group?i.$(['[data-uk-lightbox*="'+this.options.group+'"]',"[data-uk-lightbox*='"+this.options.group+"']"].join(",")):this.element;e.each(function(){var e=i.$(this);t.push({source:e.attr("href"),title:e.attr("data-title")||e.attr("title"),type:e.attr("data-lightbox-type")||"auto",link:e})}),this.index=e.index(this.element),this.siblings=t}else this.options.group&&this.options.group.length&&(this.siblings=this.options.group);this.trigger("lightbox-init",[this])},show:function(e){this.modal=t(this),this.modal.dialog.stop(),this.modal.content.stop();var o,n,s=this,h=i.$.Deferred();e=e||0,"object"==typeof e&&this.siblings.forEach(function(i,t){e[0]===i.link[0]&&(e=t)}),0>e?e=this.siblings.length-e:this.siblings[e]||(e=0),n=this.siblings[e],o={lightbox:s,source:n.source,type:n.type,index:e,promise:h,title:n.title,item:n,meta:{content:"",width:null,height:null}},this.index=e,this.modal.content.empty(),this.modal.is(":visible")||(this.modal.content.css({width:"",height:""}).empty(),this.modal.modal.show()),this.modal.loader.removeClass("uk-hidden"),h.promise().done(function(){s.data=o,s.fitSize(o)}).fail(function(){o.meta.content='
Loading resource failed!
',o.meta.width=400,o.meta.height=300,s.data=o,s.fitSize(o)}),s.trigger("showitem.uk.lightbox",[o])},fitSize:function(){var t=this,e=this.data,o=this.modal.dialog.outerWidth()-this.modal.dialog.width(),n=parseInt(this.modal.dialog.css("margin-top"),10),s=parseInt(this.modal.dialog.css("margin-bottom"),10),h=n+s,a=e.meta.content,d=t.options.duration;this.siblings.length>1&&(a=[a,'',''].join(""));var l,r,u=i.$("

").css({opacity:0,position:"absolute",top:0,left:0,width:"100%","max-width":t.modal.dialog.css("max-width"),padding:t.modal.dialog.css("padding"),margin:t.modal.dialog.css("margin")}),c=e.meta.width,g=e.meta.height;u.appendTo("body").width(),l=u.width(),r=window.innerHeight-h,u.remove(),this.modal.dialog.find(".uk-modal-caption").remove(),e.title&&(this.modal.dialog.append('
'+e.title+"
"),r-=this.modal.dialog.find(".uk-modal-caption").outerHeight()),l<e.meta.width&&(g=Math.floor(g*(l/c)),c=l),g>r&&(g=Math.floor(r),c=Math.ceil(e.meta.width*(r/e.meta.height))),this.modal.content.css("opacity",0).width(c).html(a),"iframe"==e.type&&this.modal.content.find("iframe:first").height(g);var m=g+o,p=Math.floor(window.innerHeight/2-m/2)-h;0>p&&(p=0),this.modal.closer.addClass("uk-hidden"),t.modal.data("mwidth")==c&&t.modal.data("mheight")==g&&(d=0),this.modal.dialog.animate({width:c+o,height:g+o,top:p},d,"swing",function(){t.modal.loader.addClass("uk-hidden"),t.modal.content.css({width:""}).animate({opacity:1},function(){t.modal.closer.removeClass("uk-hidden")}),t.modal.data({mwidth:c,mheight:g})})},next:function(){this.show(this.siblings[this.index+1]?this.index+1:0)},previous:function(){this.show(this.siblings[this.index-1]?this.index-1:this.siblings.length-1)}}),i.plugin("lightbox","image",{init:function(i){i.on("showitem.uk.lightbox",function(i,t){if("image"==t.type||t.source&&t.source.match(/\.(jpg|jpeg|png|gif|svg)$/i)){var e=function(i,e,o){t.meta={content:'',width:e,height:o},t.type="image",t.promise.resolve()};if(o[t.source])e(t.source,o[t.source].width,o[t.source].height);else{var n=new Image;n.onerror=function(){t.promise.reject("Loading image failed")},n.onload=function(){o[t.source]={width:n.width,height:n.height},e(t.source,o[t.source].width,o[t.source].height)},n.src=t.source}}})}}),i.plugin("lightbox","youtube",{init:function(i){var t=/(\/\/.*?youtube\.[a-z]+)\/watch\?v=([^&]+)&?(.*)/,e=/youtu\.be\/(.*)/;i.on("showitem.uk.lightbox",function(i,n){var s,h,a=function(i,t,e){n.meta={content:'',width:t,height:e},n.type="iframe",n.promise.resolve()};if((h=n.source.match(t))&&(s=h[2]),(h=n.source.match(e))&&(s=h[1]),s){if(o[s])a(s,o[s].width,o[s].height);else{var d=new Image,l=!1;d.onerror=function(){o[s]={width:640,height:320},a(s,o[s].width,o[s].height)},d.onload=function(){120==d.width&&90==d.height?l?(o[s]={width:640,height:320},a(s,o[s].width,o[s].height)):(l=!0,d.src="//img.youtube.com/vi/"+s+"/0.jpg"):(o[s]={width:d.width,height:d.height},a(s,d.width,d.height))},d.src="//img.youtube.com/vi/"+s+"/maxresdefault.jpg"}i.stopImmediatePropagation()}})}}),i.plugin("lightbox","vimeo",{init:function(t){var e,n=/(\/\/.*?)vimeo\.[a-z]+\/([0-9]+).*?/;t.on("showitem.uk.lightbox",function(t,s){var h,a=function(i,t,e){s.meta={content:'',width:t,height:e},s.type="iframe",s.promise.resolve()};(e=s.source.match(n))&&(h=e[2],o[h]?a(h,o[h].width,o[h].height):i.$.ajax({type:"GET",url:"http://vimeo.com/api/oembed.json?url="+encodeURI(s.source),jsonp:"callback",dataType:"jsonp",success:function(i){o[h]={width:i.width,height:i.height},a(h,o[h].width,o[h].height)}}),t.stopImmediatePropagation())})}}),i.plugin("lightbox","video",{init:function(t){t.on("showitem.uk.lightbox",function(t,e){var n=function(i,t,o){e.meta={content:'<video class="uk-responsive-width" src="'+i+'" width="'+t+'" height="'+o+'" controls></video>',width:t,height:o},e.type="video",e.promise.resolve()};if("video"==e.type||e.source.match(/\.(mp4|webm|ogv)$/i))if(o[e.source])n(e.source,o[e.source].width,o[e.source].height);else var s=i.$('<video style="position:fixed;visibility:hidden;top:-10000px;"></video>').attr("src",e.source).appendTo("body"),h=setInterval(function(){s[0].videoWidth&&(clearInterval(h),o[e.source]={width:s[0].videoWidth,height:s[0].videoHeight},n(e.source,o[e.source].width,o[e.source].height),s.remove())},20)})}}),UIkit.plugin("lightbox","iframe",{init:function(i){i.on("showitem.uk.lightbox",function(t,e){var o=function(i,t,o){e.meta={content:'',width:t,height:o},e.type="iframe",e.promise.resolve()};("iframe"===e.type||e.source.match(/\.(html|php)$/))&&o(e.source,i.options.width||800,i.options.height||600)})}}),i.lightbox.create=function(t,e){if(t){var o,n=[];return t.forEach(function(t){n.push(i.$.extend({source:"",title:"",type:"auto",link:!1},"string"==typeof t?{source:t}:t))}),o=i.lightbox(i.$.extend({},e,{group:n}))}},i.lightbox});
<|endoftext|>


<commit_before>/*global require: false, module: false */
'use strict';

var React = require('react');
var Select = require('../views/Select');
var _ = require('../underscore_ext');

function apply(features, state) {
	var {feature, dsID} = state,
		fieldTxt = _.find(features, f => f.value === feature).label;
	return {
		fields: [feature],
		dataType: 'clinicalMatrix',
		dsID: dsID,
		fieldLabel: {user: fieldTxt, 'default': fieldTxt}
	};
}

var valid = state => !!state.feature;
var stripFields = f => ({dsID: f.dsID, label: (f.longtitle || f.name), value: f.name});
var consolidateFeatures = featureSet => {
	return _.reduce(featureSet, (all, features, dsID) => {
		let strippedFeatures = _.toArray(_.mapObject(features, f =>
			_.extend(stripFields(f), {dsID: dsID})));
		return all.concat(strippedFeatures);
	}, []);
};
const LOCAL_DOMAIN = 'local.xena.ucsc.edu';
var sortFeatures = features => _.sortBy(features, f => f.label.toLowerCase());
// Select a phenotype feature from those on the server.
var PhenotypeEdit = React.createClass({
	name: 'View', // XXX change col-md-offset-10, etc. to react-boostrap style
	getInitialState: function() {
		var {allFeatures, chosenDs, metas} = this.props,
			dsHub = JSON.parse(chosenDs).host,
			filteredFeatures = _.pick(allFeatures, dsHub.includes(LOCAL_DOMAIN) ? chosenDs : _.keys(metas));
		return {
			features: sortFeatures(consolidateFeatures(filteredFeatures))
		}
	},
	onSelect: function(f) {
		var {callback, metas, setEditorState} = this.props,
			{features} = this.state,
			feature = _.findWhere(features, {value: f});
		callback(['edit-dataset', feature.dsID, metas[feature.dsID]]);
		setEditorState({feature: feature.value, dsID: feature.dsID});
	},
	render: function () {
		var {feature = {}, makeLabel} = this.props,
			{features} = this.state,
			labelValue = _.isEmpty(feature) ? `Choose a ${this.name} :` :
				`${this.name} chosen: `,
			//XXX Account for 'charLimit' prop after 'NewNavigation' branch is merged into master
			content = <Select value={feature} allowSearch={true}
				onSelect={this.onSelect} options={features}/>,
			label = makeLabel(content, labelValue);
		return (

Total Features: {_.toArray(features).length}

Features for Specific Phenotype: {_.toArray(this.props.features).length}

				{label}

		);
	}
});

module.exports = {
	Editor: PhenotypeEdit,
	valid,
	apply
};
<commit_msg>Changed sorting method based on upper case for PhenotypeEditor<commit_after>/*global require: false, module: false */
'use strict';

var React = require('react');
var Select = require('../views/Select');
var _ = require('../underscore_ext');

function apply(features, state) {
	var {feature, dsID} = state,
		fieldTxt = _.find(features, f => f.value === feature).label;
	return {
		fields: [feature],
		dataType: 'clinicalMatrix',
		dsID: dsID,
		fieldLabel: {user: fieldTxt, 'default': fieldTxt}
	};
}

var valid = state => !!state.feature;
var stripFields = f => ({dsID: f.dsID, label: (f.longtitle || f.name), value: f.name});
var consolidateFeatures = featureSet => {
	return _.reduce(featureSet, (all, features, dsID) => {
		let strippedFeatures = _.toArray(_.mapObject(features, f =>
			_.extend(stripFields(f), {dsID: dsID})));
		return all.concat(strippedFeatures);
	}, []);
};
const LOCAL_DOMAIN = 'local.xena.ucsc.edu';
var sortFeatures = features => _.sortBy(features, f => f.label.toUpperCase());
// Select a phenotype feature from those on the server.
var PhenotypeEdit = React.createClass({
	name: 'View', // XXX change col-md-offset-10, etc. to react-boostrap style
	getInitialState: function() {
		var {allFeatures, chosenDs, metas} = this.props,
			dsHub = JSON.parse(chosenDs).host,
			filteredFeatures = _.pick(allFeatures, dsHub.includes(LOCAL_DOMAIN) ? chosenDs : _.keys(metas));
		return {
			features: sortFeatures(consolidateFeatures(filteredFeatures))
		}
	},
	onSelect: function(f) {
		var {callback, metas, setEditorState} = this.props,
			{features} = this.state,
			feature = _.findWhere(features, {value: f});
		callback(['edit-dataset', feature.dsID, metas[feature.dsID]]);
		setEditorState({feature: feature.value, dsID: feature.dsID});
	},
	render: function () {
		var {feature = {}, makeLabel} = this.props,
			{features} = this.state,
			labelValue = _.isEmpty(feature) ? `Choose a ${this.name} :` :
				`${this.name} chosen: `,
			//XXX Account for 'charLimit' prop after 'NewNavigation' branch is merged into master
			content = <Select value={feature} allowSearch={true}
				onSelect={this.onSelect} options={features}/>,
			label = makeLabel(content, labelValue);
		return (

Total Features: {_.toArray(features).length}

Features for Specific Phenotype: {_.toArray(this.props.features).length}

				{label}

		);
	}
});

module.exports = {
	Editor: PhenotypeEdit,
	valid,
	apply
};
<|endoftext|>