<commit_before>// app/router.js
module.exports = app => {
    // 这两个接口用于测试
    app.get('/', app.controller.home.index);

    // socket.io
    app.io.of('/tomatobang', app.io.controllers.tomatobang);

    /**
     * 用户类
     */
    app.get('/api/user', app.controller.user.list);
    app.get('/api/user/:id', app.controller.user.findById);
    app.post('/api/user', app.controller.user.create);
    app.post('/api/user/:id', app.controller.user.updateById);
    app.del('/api/user/:id', app.controller.user.deleteById);
    app.post('/getRongyunToken', app.controller.user.getRongyunToken);
    app.post('/email_username/verify', app.controller.user.emailUserNameVerify);
    app.post('/api/login', app.controller.user.login);
    app.post('/api/logout', app.controller.user.logout);
    app.post('/api/user/headimg', app.controller.user.uploadHeadImg);
    app.get('/api/user/headimg/:path', app.controller.user.downloadHeadImg);

    //app.put('/api/user', app.controller.user.create);
    //app.put('/api/user/:id', app.controller.user.replaceById);
    //app.patch('/api/user/:id', app.controller.user.updateById);

    /**
     * 番茄钟类
     */
    app.get('/api/tomato', app.controller.tomato.list);
    app.get('/api/tomato/:id', app.controller.tomato.findById);
    app.post('/api/tomato', app.controller.tomato.create);
    app.post('/api/tomato/:id', app.controller.tomato.updateById);
    app.del('/api/tomato/:id', app.controller.tomato.deleteById);
    app.get('/filter/tomatotoday', app.controller.tomato.tomatoToday);

    /**
     * 任务类
     */
    app.get('/api/task', app.controller.task.list);
    app.get('/api/task/:id', app.controller.task.findById);
    app.post('/api/task', app.controller.task.create);
    app.post('/api/task/:id', app.controller.task.updateById);
    app.del('/api/task/:id', app.controller.task.deleteById);

    /**
     * 配置类
     */
    app.get('/api/options', app.controller.options.list);

    /**
     * 其它
     */
    app.post('/tool/dismissgroup', app.controller.other.dismissgroup);
    app.post('/upload/voicefile', app.controller.other.uploadVoiceFile);
    app.post('/download/voicefile/:path', app.controller.other.downloadVoiceFile);

  };<commit_msg>change audio download http method to get<commit_after>// app/router.js
module.exports = app => {
    // 这两个接口用于测试
    app.get('/', app.controller.home.index);

    // socket.io
    app.io.of('/tomatobang', app.io.controllers.tomatobang);

    /**
     * 用户类
     */
    app.get('/api/user', app.controller.user.list);
    app.get('/api/user/:id', app.controller.user.findById);
    app.post('/api/user', app.controller.user.create);
    app.post('/api/user/:id', app.controller.user.updateById);
    app.del('/api/user/:id', app.controller.user.deleteById);
    app.post('/getRongyunToken', app.controller.user.getRongyunToken);
    app.post('/email_username/verify', app.controller.user.emailUserNameVerify);
    app.post('/api/login', app.controller.user.login);
    app.post('/api/logout', app.controller.user.logout);
    app.post('/api/user/headimg', app.controller.user.uploadHeadImg);
    app.get('/api/user/headimg/:path', app.controller.user.downloadHeadImg);

    //app.put('/api/user', app.controller.user.create);
    //app.put('/api/user/:id', app.controller.user.replaceById);
    //app.patch('/api/user/:id', app.controller.user.updateById);

    /**
     * 番茄钟类
     */
    app.get('/api/tomato', app.controller.tomato.list);
    app.get('/api/tomato/:id', app.controller.tomato.findById);
    app.post('/api/tomato', app.controller.tomato.create);
    app.post('/api/tomato/:id', app.controller.tomato.updateById);
    app.del('/api/tomato/:id', app.controller.tomato.deleteById);
    app.get('/filter/tomatotoday', app.controller.tomato.tomatoToday);

    /**
     * 任务类
     */
    app.get('/api/task', app.controller.task.list);
    app.get('/api/task/:id', app.controller.task.findById);
    app.post('/api/task', app.controller.task.create);
    app.post('/api/task/:id', app.controller.task.updateById);
    app.del('/api/task/:id', app.controller.task.deleteById);

    /**
     * 配置类
     */
    app.get('/api/options', app.controller.options.list);

    /**
     * 其它
     */
    app.post('/tool/dismissgroup', app.controller.other.dismissgroup);
    app.post('/upload/voicefile', app.controller.other.uploadVoiceFile);
    app.get('/download/voicefile/:path', app.controller.other.downloadVoiceFile);

  };<|endoftext|>


<commit_before>import Ember from 'ember';
import config from './config/environment';

const Router = Ember.Router.extend({
  location: config.locationType,
  rootURL: config.rootURL,
  metrics: Ember.inject.service(),

  didTransition() {
    this._super(...arguments);
    this._trackPage();
  },

  _trackPage() {
    Ember.run.scheduleOnce('afterRender', this, () => {

      let page = this.get('currentPath').replace(/\./g, "/"),
            routeName = this.get('currentRouteName');

      if (routeName === "graph.index") {
        let state = this.get('router.state.queryParams.currentTab');
        routeName = routeName + "$" + state;
        page = page.replace(/\/index$/i, "/"+state);
      }

      let title = config.metricsRouteLabels[routeName];

      if (title) { //track only if a title has bean found
        this.get('metrics').trackPage({ page, title });
      }

    });
  }

});

Router.map(function() {

    this.route("index", {path: "/"});

    this.route("project", {path:"project/:uuid"}, function(){
        this.route("step1");
        this.route("step2", function() {
          this.route("column", {path: "column/:columnId"});
        });
    });

    this.route("graph", {path: "graph/:uuid"}, function() {
        this.route("projection");
        this.route("layer", {path: "layer/:layerId"}, function() {
          this.route("edit");
        });
    });

});

export default Router;
<commit_msg>correction analytics<commit_after>import Ember from 'ember';
import config from './config/environment';

const Router = Ember.Router.extend({
  location: config.locationType,
  rootURL: config.rootURL,
  metrics: Ember.inject.service(),

  didTransition() {
    this._super(...arguments);
    console.log("didTransition");
    Ember.run.scheduleOnce('afterRender', this, this._trackPage);
  },

  _trackPage() {

      let routeName = this.get('currentRouteName').replace(/\.index$/g, ""),
          page = routeName.replace(/\./g, "/");

      if (routeName === "graph") {
        let state = this.get('router.state.queryParams.currentTab');
        routeName = routeName + "$" + (state ? state : "visualizations");
        page = page.replace(/\/index$/i, "/"+state);
      }

      let title = config.metricsRouteLabels[routeName];

      if (title) { //track only if a title has bean found
        this.get('metrics').trackPage({ page, title });
      }

  }

});

Router.map(function() {

    this.route("index", {path: "/"});

    this.route("project", {path:"project/:uuid"}, function(){
        this.route("step1");
        this.route("step2", function() {
          this.route("column", {path: "column/:columnId"});
        });
    });

    this.route("graph", {path: "graph/:uuid"}, function() {
        this.route("projection");
        this.route("layer", {path: "layer/:layerId"}, function() {
          this.route("edit");
        });
    });

});

export default Router;
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();

router.get('/', function (req, res) {

  res.render('index');

});

// Example routes - feel free to delete these

// Passing data into a page

router.get('/examples/template-data', function (req, res) {

  res.render('examples/template-data', { 'name' : 'Foo' });

});

// Branching

router.get('/examples/over-18', function (req, res) {

  // get the answer from the query string (eg. ?over18=false)
  var over18 = req.query.over18;

  if (over18 == "false"){

    // redirect to the relevant page
    res.redirect("/examples/under-18");

  } else {

    // if over18 is any other value (or is missing) render the page requested
    res.render('examples/over-18');

  }

});

// More Loans to Directors

router.get('/accounts/accounts-loans-to-directors', function (req, res) {

  // get the answer from the query string (eg. ?over18=false)
  var moreloansdirectors = req.query.moreloansdirectors;

  if (moreloansdirectors == "no"){

    // redirect to the relevant page
    res.redirect("/accounts/accounts-balance-sheet-notes-completed-6");

  } else {

    // if over18 is any other value (or is missing) render the page requested
    res.render('accounts/accounts-loans-to-directors');

  }

});

// WebFiling to CHS

router.get('/chs/chs-from-webfiling', function (req, res) {

  // get the answer from the query string (eg. ?over18=false)
  var gotochs = req.query.gotochs;

  if (gotochs == "No"){

    // redirect to the relevant page
    res.redirect("/webfiling/webfiling-hmrc-third-party");

  } else {

    // if over18 is any other value (or is missing) render the page requested
    res.render('chs/chs-from-webfiling');

  }

});

// CHS from WebFiling (Register, CHS)

router.get('/chs/chs-choose-password', function (req, res) {

  // get the answer from the query string (eg. ?over18=false)
  var chsfromwebfiling = req.query.chsfromwebfiling;

  if (chsfromwebfiling == "no"){

    // redirect to the relevant page
    res.redirect("/chs/chs-register-page");

  } else {

    // if over18 is any other value (or is missing) render the page requested
    res.render('chs/chs-choose-password');

  }

});

// CHS Release 1 question

router.get('/accounts/accounts-start-page-abridged', function (req, res) {

  // get the answer from the query string (eg. ?over18=false)
  var chsrelease1 = req.query.chsrelease1;

  if (chsrelease1 == "No"){

    // redirect to the relevant page
    res.redirect("/chs/chs-alternative-abridged-filing-options");

  } else {

    // if over18 is any other value (or is missing) render the page requested
    res.render('accounts/accounts-start-page-abridged');

  }

});

// CHS Release 1 question (when user comes in stright to CHS, bypassing gov-uk)

router.get('/accounts/accounts-start-page-no-gov-uk', function (req, res) {

  // get the answer from the query string (eg. ?over18=false)
  var chsrelease1 = req.query.chsrelease1;

  if (chsrelease1 == "No"){

    // redirect to the relevant page
    res.redirect("/chs/chs-alternative-abridged-filing-options");

  } else {

    // if over18 is any other value (or is missing) render the page requested
    res.render('accounts/accounts-start-page-no-gov-uk');

  }

});

// CHS Release 1 question (no company search - directly into accounts)

router.get('/accounts/accounts-start-page-abridged-direct', function (req, res) {

  // get the answer from the query string (eg. ?over18=false)
  var chsrelease1 = req.query.chsrelease1;

  if (chsrelease1 == "No"){

    // redirect to the relevant page
    res.redirect("/chs/chs-choose-accounts-direct");

  } else {

    // if over18 is any other value (or is missing) render the page requested
    res.render('accounts/accounts-start-page-abridged-direct');

  }

});

// Resume accounts (from CHS profile when logged back in)

router.get('/accounts/accounts-balance-sheet-resume', function (req, res) {

  // get the answer from the query string (eg. ?over18=false)
  var resumefromprofile = req.query.resumefromprofile;

  if (resumefromprofile == "no"){

    // redirect to the relevant page
    res.redirect("/accounts/accounts-start-page");

  } else {

    // if over18 is any other value (or is missing) render the page requested
    res.render('accounts/accounts-balance-sheet-resume');

  }

});

// Do you have a creditors note?

//router.get('/accounts/accounts-review', function (req, res) {

  // get the answer from the query string (eg. ?over18=false)
  //var creditorsnoteyn = req.query.creditorsnoteyn;

//  if (creditorsnoteyn == "Yes"){

    // redirect to the relevant page
//    res.redirect("/accounts/accounts-creditors-amounts-falling-due-within-one-year");

//  } else {

    // if over18 is any other value (or is missing) render the page requested
  //  res.render('accounts/accounts-review');

//  }

//});

// Do you have Other notes - send them to Review or to the Employees note?

router.get('/accounts/accounts-abridged-employees-yes-no', function (req, res) {

  // get the answer from the query string (eg. ?over18=false)
  var othernotes = req.query.othernotes;

  if (othernotes == "No"){

    // redirect to the relevant page
    res.redirect("/accounts/accounts-review-no-other-notes");

  } else {

    // if over18 is any other value (or is missing) render the page requested
    res.render('accounts/accounts-abridged-employees-yes-no');

  }

});

// Do you have Other notes, second chance (ie did you miss any on the Review screen)

router.get('/accounts/accounts-abridged-fixed-assets-yes-no', function (req, res) {

  // get the answer from the query string (eg. ?over18=false)
  var othernotes = req.query.othernotes;

  if (othernotes == "Yes"){

    // redirect to the relevant page
    res.redirect("/accounts/accounts-approval");

  } else {

    // if over18 is any other value (or is missing) render the page requested
    res.render('accounts/accounts-abridged-fixed-assets-yes-no');

  }

});

// WIZARD - is the company trading

router.get('/accounts/wizard/wizard-ever-traded', function (req, res) {

  // get the answer from the query string
  var trading = req.query.trading;
  if (trading == "Yes"){

    // redirect to the relevant page
    res.redirect("/accounts/wizard/wizard-turnover");

  } else {
    // if trading is any other value (or is missing) render the page requested
    res.render('accounts/wizard/wizard-ever-traded');
  }

});

// WIZARD - has the company ever traded

router.get('/accounts/accounts-start-page-dormant', function (req, res) {

  // get the answer from the query string
  var evertraded = req.query.evertraded;
  if (evertraded == "Yes"){

    // redirect to the relevant page
    res.redirect("/accounts/accounts-start-page-cato");

  } else {
    // if evertraded is any other value (or is missing) render the page requested
    res.render('accounts/accounts-start-page-dormant');
  }

});

// WIZARD - Was the company's turnover more than £632,000?

router.get('/accounts/wizard/wizard-balance-sheet-less', function (req, res) {

  // get the answer from the query string
  var turnover632 = req.query.turnover632;
  if (turnover632 == "Yes"){

    // redirect to the relevant page
    res.redirect("/accounts/wizard/wizard-balance-sheet-more");

  } else {
    // if turnover632 is any other value (or is missing) render the page requested
    res.render('accounts/wizard/wizard-balance-sheet-less');
  }

});

// WIZARD - Was the company's balance sheet total less than £316,000?

router.get('/accounts/wizard/wizard-employees-more', function (req, res) {

  // get the answer from the query string
  var balanceless = req.query.balanceless;
  if (balanceless == "Yes"){

    // redirect to the relevant page
    res.redirect("/accounts/wizard/wizard-employees-less");

  } else {
    // if balanceless is any other value (or is missing) render the page requested
    res.render('accounts/wizard/wizard-employees-more');
  }

});

// WIZARD - Was the company's balance sheet total more than £316,000?

router.get('/accounts/wizard/wizard-breakdown', function (req, res) {

  // get the answer from the query string
  var balancemore = req.query.balancemore;
  if (balancemore == "No"){

    // redirect to the relevant page
    res.redirect("/accounts/wizard/wizard-employees-less");

  } else {
    // if balancemore is any other value (or is missing) render the page requested
    res.render('accounts/wizard/wizard-breakdown');
  }

});

// WIZARD - Did the company employ an average of more than 10 employees during the year?

router.get('/accounts/wizard/wizard-micros-abridged', function (req, res) {

  // get the answer from the query string
  var employeemore = req.query.employeemore;
  if (employeemore == "Yes"){

    // redirect to the relevant page
    res.redirect("/accounts/wizard/wizard-breakdown");

  } else {
    // if employeeless is any other value (or is missing) render the page requested
    res.render('accounts/wizard/wizard-micros-abridged');
  }

});

// WIZARD - Did the company employ an average less than 10 employees during the year?

router.get('/accounts/wizard/wizard-micros-abridged', function (req, res) {

  // get the answer from the query string
  var employeeless = req.query.employeeless;
  if (employeeless == "No"){

    // redirect to the relevant page
    res.redirect("/accounts/wizard/wizard-breakdown");

  } else {
    // if employeeless is any other value (or is missing) render the page requested
    res.render('accounts/wizard/wizard-micros-abridged');
  }

});

// WIZARD - You are eligible to file micro-entity accounts or abridged accounts

router.get('/accounts/accounts-start-page-micros', function (req, res) {

  // get the answer from the query string
  var microabridged = req.query.microabridged;
  if (microabridged == "abridged"){

    // redirect to the relevant page
    res.redirect("/accounts/accounts-start-page-abridged");

  } else {
    // if microabridged is any other value (or is missing) render the page requested
    res.render('accounts/accounts-start-page-micros');
  }

});

// WIZARD - Do you want to give a breakdown?

router.get('/accounts/wizard/wizard-joint', function (req, res) {

  // get the answer from the query string
  var breakdown = req.query.breakdown;
  if (breakdown == "No"){

    // redirect to the relevant page
    res.redirect("/accounts/accounts-start-page-abridged");

  } else {
    // if breakdown is any other value (or is missing) render the page requested
    res.render('accounts/wizard/wizard-joint');
  }

});

// WIZARD - Do you want to give a file to both Companies House and HMRC?

router.get('/accounts/accounts-start-page-cato-full', function (req, res) {

  // get the answer from the query string
  var joint = req.query.joint;
  if (joint == "No"){

    // redirect to the relevant page
    res.redirect("/accounts/accounts-start-page-full-software");

  } else {
    // if joint is any other value (or is missing) render the page requested
    res.render('accounts/accounts-start-page-cato-full');
  }

});

module.exports = router;
<commit_msg>Test commit<commit_after>var express = require('express');
var router = express.Router();

router.get('/', function (req, res) {

  res.render('index');

});

// Example routes - feel free to delete these

// Passing data into a page

router.get('/examples/template-data', function (req, res) {

  res.render('examples/template-data', { 'name' : 'Foo' });

});

// Branching

router.get('/examples/over-18', function (req, res) {

  // get the answer from the query string (eg. ?over18=false)
  var over18 = req.query.over18;

  if (over18 == "false"){

    // redirect to the relevant page
    res.redirect("/examples/under-18");

  } else {

    // if over18 is any other value (or is missing) render the page requested
    res.render('examples/over-18');

  }

});

// More Loans to Directors

router.get('/accounts/accounts-loans-to-directors', function (req, res) {

  // get the answer from the query string (eg. ?over18=false)
  var moreloansdirectors = req.query.moreloansdirectors;

  if (moreloansdirectors == "no"){

    // redirect to the relevant page
    res.redirect("/accounts/accounts-balance-sheet-notes-completed-6");

  } else {

    // if over18 is any other value (or is missing) render the page requested
    res.render('accounts/accounts-loans-to-directors');

  }

});

// WebFiling to CHS

router.get('/chs/chs-from-webfiling', function (req, res) {

  // get the answer from the query string (eg. ?over18=false)
  var gotochs = req.query.gotochs;

  if (gotochs == "No"){

    // redirect to the relevant page
    res.redirect("/webfiling/webfiling-hmrc-third-party");

  } else {

    // if over18 is any other value (or is missing) render the page requested
    res.render('chs/chs-from-webfiling');

  }

});

// CHS from WebFiling (Register, CHS)

router.get('/chs/chs-choose-password', function (req, res) {

  // get the answer from the query string (eg. ?over18=false)
  var chsfromwebfiling = req.query.chsfromwebfiling;

  if (chsfromwebfiling == "no"){

    // redirect to the relevant page
    res.redirect("/chs/chs-register-page");

  } else {

    // if over18 is any other value (or is missing) render the page requested
    res.render('chs/chs-choose-password');

  }

});

// CHS Release 1 question

router.get('/accounts/accounts-start-page-abridged', function (req, res) {

  // get the answer from the query string (eg. ?over18=false)
  var chsrelease1 = req.query.chsrelease1;

  if (chsrelease1 == "No"){

    // redirect to the relevant page
    res.redirect("/chs/chs-alternative-abridged-filing-options");

  } else {

    // if over18 is any other value (or is missing) render the page requested
    res.render('accounts/accounts-start-page-abridged');

  }

});

// CHS Release 1 question (when user comes in stright to CHS, bypassing gov-uk)

router.get('/accounts/accounts-start-page-no-gov-uk', function (req, res) {

  var chsrelease1 = req.query.chsrelease1;

  if (chsrelease1 == "No"){

    res.redirect("/chs/chs-alternative-abridged-filing-options");

  } else {

    res.render('accounts/accounts-start-page-no-gov-uk');

  }

});

// CHS Release 1 question (no company search - directly into accounts)

router.get('/accounts/accounts-start-page-abridged-direct', function (req, res) {

  // get the answer from the query string (eg. ?over18=false)
  var chsrelease1 = req.query.chsrelease1;

  if (chsrelease1 == "No"){

    // redirect to the relevant page
    res.redirect("/chs/chs-choose-accounts-direct");

  } else {

    // if over18 is any other value (or is missing) render the page requested
    res.render('accounts/accounts-start-page-abridged-direct');

  }

});

// Resume accounts (from CHS profile when logged back in)

router.get('/accounts/accounts-balance-sheet-resume', function (req, res) {

  // get the answer from the query string (eg. ?over18=false)
  var resumefromprofile = req.query.resumefromprofile;

  if (resumefromprofile == "no"){

    // redirect to the relevant page
    res.redirect("/accounts/accounts-start-page");

  } else {

    // if over18 is any other value (or is missing) render the page requested
    res.render('accounts/accounts-balance-sheet-resume');

  }

});

// Do you have a creditors note?

//router.get('/accounts/accounts-review', function (req, res) {

  // get the answer from the query string (eg. ?over18=false)
  //var creditorsnoteyn = req.query.creditorsnoteyn;

//  if (creditorsnoteyn == "Yes"){

    // redirect to the relevant page
//    res.redirect("/accounts/accounts-creditors-amounts-falling-due-within-one-year");

//  } else {

    // if over18 is any other value (or is missing) render the page requested
  //  res.render('accounts/accounts-review');

//  }

//});

// Do you have Other notes - send them to Review or to the Employees note?

router.get('/accounts/accounts-abridged-employees-yes-no', function (req, res) {

  // get the answer from the query string (eg. ?over18=false)
  var othernotes = req.query.othernotes;

  if (othernotes == "No"){

    // redirect to the relevant page
    res.redirect("/accounts/accounts-review-no-other-notes");

  } else {

    // if over18 is any other value (or is missing) render the page requested
    res.render('accounts/accounts-abridged-employees-yes-no');

  }

});

// Do you have Other notes, second chance (ie did you miss any on the Review screen)

router.get('/accounts/accounts-abridged-fixed-assets-yes-no', function (req, res) {

  // get the answer from the query string (eg. ?over18=false)
  var othernotes = req.query.othernotes;

  if (othernotes == "Yes"){

    // redirect to the relevant page
    res.redirect("/accounts/accounts-approval");

  } else {

    // if over18 is any other value (or is missing) render the page requested
    res.render('accounts/accounts-abridged-fixed-assets-yes-no');

  }

});

// WIZARD - is the company trading

router.get('/accounts/wizard/wizard-ever-traded', function (req, res) {

  // get the answer from the query string
  var trading = req.query.trading;
  if (trading == "Yes"){

    // redirect to the relevant page
    res.redirect("/accounts/wizard/wizard-turnover");

  } else {
    // if trading is any other value (or is missing) render the page requested
    res.render('accounts/wizard/wizard-ever-traded');
  }

});

// WIZARD - has the company ever traded

router.get('/accounts/accounts-start-page-dormant', function (req, res) {

  // get the answer from the query string
  var evertraded = req.query.evertraded;
  if (evertraded == "Yes"){

    // redirect to the relevant page
    res.redirect("/accounts/accounts-start-page-cato");

  } else {
    // if evertraded is any other value (or is missing) render the page requested
    res.render('accounts/accounts-start-page-dormant');
  }

});

// WIZARD - Was the company's turnover more than £632,000?

router.get('/accounts/wizard/wizard-balance-sheet-less', function (req, res) {

  // get the answer from the query string
  var turnover632 = req.query.turnover632;
  if (turnover632 == "Yes"){

    // redirect to the relevant page
    res.redirect("/accounts/wizard/wizard-balance-sheet-more");

  } else {
    // if turnover632 is any other value (or is missing) render the page requested
    res.render('accounts/wizard/wizard-balance-sheet-less');
  }

});

// WIZARD - Was the company's balance sheet total less than £316,000?

router.get('/accounts/wizard/wizard-employees-more', function (req, res) {

  // get the answer from the query string
  var balanceless = req.query.balanceless;
  if (balanceless == "Yes"){

    // redirect to the relevant page
    res.redirect("/accounts/wizard/wizard-employees-less");

  } else {
    // if balanceless is any other value (or is missing) render the page requested
    res.render('accounts/wizard/wizard-employees-more');
  }

});

// WIZARD - Was the company's balance sheet total more than £316,000?

router.get('/accounts/wizard/wizard-breakdown', function (req, res) {

  // get the answer from the query string
  var balancemore = req.query.balancemore;
  if (balancemore == "No"){

    // redirect to the relevant page
    res.redirect("/accounts/wizard/wizard-employees-less");

  } else {
    // if balancemore is any other value (or is missing) render the page requested
    res.render('accounts/wizard/wizard-breakdown');
  }

});

// WIZARD - Did the company employ an average of more than 10 employees during the year?

router.get('/accounts/wizard/wizard-micros-abridged', function (req, res) {

  // get the answer from the query string
  var employeemore = req.query.employeemore;
  if (employeemore == "Yes"){

    // redirect to the relevant page
    res.redirect("/accounts/wizard/wizard-breakdown");

  } else {
    // if employeeless is any other value (or is missing) render the page requested
    res.render('accounts/wizard/wizard-micros-abridged');
  }

});

// WIZARD - Did the company employ an average less than 10 employees during the year?

router.get('/accounts/wizard/wizard-micros-abridged', function (req, res) {

  // get the answer from the query string
  var employeeless = req.query.employeeless;
  if (employeeless == "No"){

    // redirect to the relevant page
    res.redirect("/accounts/wizard/wizard-breakdown");

  } else {
    // if employeeless is any other value (or is missing) render the page requested
    res.render('accounts/wizard/wizard-micros-abridged');
  }

});

// WIZARD - You are eligible to file micro-entity accounts or abridged accounts

router.get('/accounts/accounts-start-page-micros', function (req, res) {

  // get the answer from the query string
  var microabridged = req.query.microabridged;
  if (microabridged == "abridged"){

    // redirect to the relevant page
    res.redirect("/accounts/accounts-start-page-abridged");

  } else {
    // if microabridged is any other value (or is missing) render the page requested
    res.render('accounts/accounts-start-page-micros');
  }

});

// WIZARD - Do you want to give a breakdown?

router.get('/accounts/wizard/wizard-joint', function (req, res) {

  // get the answer from the query string
  var breakdown = req.query.breakdown;
  if (breakdown == "No"){

    // redirect to the relevant page
    res.redirect("/accounts/accounts-start-page-abridged");

  } else {
    // if breakdown is any other value (or is missing) render the page requested
    res.render('accounts/wizard/wizard-joint');
  }

});

// WIZARD - Do you want to give a file to both Companies House and HMRC?

router.get('/accounts/accounts-start-page-cato-full', function (req, res) {

  // get the answer from the query string
  var joint = req.query.joint;
  if (joint == "No"){

    // redirect to the relevant page
    res.redirect("/accounts/accounts-start-page-full-software");

  } else {
    // if joint is any other value (or is missing) render the page requested
    res.render('accounts/accounts-start-page-cato-full');
  }

});

module.exports = router;
<|endoftext|>


<commit_before>// Copyright (C) 2014 Makoto Mizukami

(function () {
	"use strict";

	var DEFAULTS = {
		timeout : 180 * 1000	// Unit: second
	},

	CONST = {
		FCGIVersion : 1,
		FCGINullReqId : 0,
		FCGIRecordTypes : [
			undefined,
			"FCGI_BEGIN_REQUEST",
			"FCGI_ABORT_REQUEST",
			"FCGI_END_REQUEST",
			"FCGI_PARAMS",
			"FCGI_STDIN",
			"FCGI_STDOUT",
			"FCGI_STDERR",
			"FCGI_DATA",
			"FCGI_GET_VALUES",
			"FCGI_GET_VALUES_RESULT",
			"FCGI_UNKNOWN_TYPE"
		],
		FCGIEndReasons : [
			"FCGI_REQUEST_COMPLETE",
			"FCGI_CANT_MPX_CONN",
			"FCGI_OVERLOADED",
			"FCGI_UNKNOWN_ROLE"
		],
		FCGIRole : 1,
		FCGIHeaderLength : 8,
		FCGIVersionOffset : 0,
		FCGITypeOffset : 1,
		FCGIReqIdOffset : 2,
		FCGIContentLengthOffset : 4,
		FCGIPaddingLengthOffset : 6,
		FCGIRoleOffset : 0,
		FCGIFlagsOffset : 2,
	},

	// Classes
	Server, ClientRequest, ServerResponse,
	// Methods
	createServer,
	// Internal functions
	defaultStatusPhrase, sendFCGIRecord, sendFCGIEndRecord, onConnection, onClientData, onClientError, onClientFin, onSocketError, onSocketClose, onSocketTimeout,
	// Internal values
	CRLF = "\r\n", wellknownStatuses = require("./http_status.js").IANAStatuses,

	EE = require("events").EventEmitter, net = require("net"), util = require("util");

	Server = function (requestListener) {
		net.Server.call(this, { allowHalfOpen : true });

		if (typeof requestListener === typeof Function) {
			this.on("request", requestListener);
		}

		this.on("connection", onConnection);
		this.on("clientError", onClientError);
	};
	util.inherits(Server, net.Server);

	Server.prototype.timeout = DEFAULTS.timeout;

	Server.prototype.setTimeout = function (timeoutAfter, callback) {
		this.timeout = timeoutAfter;

		if (callback !== undefined) {
			this.on("timeout", callback);
		}
	};

	ClientRequest = function (id, socket) {
		EE.call(this);

		this.reqId = id;
		this.socket = socket;
		this.params = {};

		this.on("close", this.removeAllListeners);
	};
	util.inherits(ClientRequest, EE);

	ClientRequest.prototype.setTimeout = function (timeoutAfter, callback) {
		this.socket.setTimeout(timeoutAfter);

		if (callback !== undefined) {
			this.socket.on("timeout", callback);
		}
	};

	ServerResponse = function (id, socket) {
		var headerInfo = {
			fields : {},
			fieldQueue : [],
		};

		EE.call(this);

		this.reqId = id;
		this.socket = socket;
		this.closeSocketOnEnd = false;

		this.setHeader = ServerResponse.prototype.setHeader.bind(this, headerInfo);
		this.flushHeaders = ServerResponse.prototype.flushHeaders.bind(this, headerInfo);

		this.setStatus(200);

		this.on("close", this.removeAllListeners);
		this.on("finish", this.removeAllListeners);
	};
	util.inherits(ServerResponse, EE);

	ServerResponse.prototype.headerFinalized = false;

	ServerResponse.prototype.setStatus = function (sCode, reasonPhrase) {
		this.setHeader(["Status:", sCode.toString(), reasonPhrase !== undefined ? reasonPhrase : defaultStatusPhrase(sCode)].join(" "));
	};

	ServerResponse.prototype.setHeader = function (headerInfo, headerStatement) {
		var fieldName = headerStatement.split(":").shift().toLowerCase(),
		queued = headerInfo.fieldQueue.indexOf(fieldName);

		if (headerInfo.fields[fieldName] !== undefined && queued === -1) {
			return;
		}

		headerInfo.fields[fieldName] = headerStatement.trim();

		if (queued >= 0) {
			headerInfo.fieldQueue.splice(queued, 1);
		}

		headerInfo.fieldQueue.push(fieldName);
	};

	ServerResponse.prototype.flushHeaders = function (headerInfo, finalizeHeader) {
		if (this.socket.writable !== true || this.headerFinalized === true) {
			return;
		}

		if (headerInfo.fieldQueue.length > 0) {
			headerInfo.fieldQueue.forEach(function (field) {
				sendFCGIRecord(this.socket, "FCGI_STDOUT", this.reqId, new Buffer(headerInfo.fields[field] + CRLF));
			}.bind(this));
		}
		headerInfo.fieldQueue = [];

		if (finalizeHeader === true) {
			sendFCGIRecord(this.socket, "FCGI_STDOUT", this.reqId, new Buffer(CRLF));
			this.headerFinalized = true;
		}
	};

	ServerResponse.prototype.write = function (data) {
		this.headerFinalized !== true && this.flushHeaders(true);
		sendFCGIRecord(this.socket, "FCGI_STDOUT", this.reqId, new Buffer(data));
	};

	ServerResponse.prototype.end = function (data) {
		data !== undefined && this.write(data);
		sendFCGIRecord(this.socket, "FCGI_STDOUT", this.reqId, new Buffer(0));
		sendFCGIEndRecord(this.socket, this.reqId, "FCGI_REQUEST_COMPLETE");

		if (this.closeSocketOnEnd) {
			if (this.socket._writableState.writing === false) {
				this.socket.end();
			} else {
				this.socket.once("drain", this.socket.end);
			}
		}
	};

	createServer = function (requestListener) {
		return new Server(requestListener);
	};

	defaultStatusPhrase = function (sCode) {
		return wellknownStatuses[sCode] !== undefined ? wellknownStatuses[sCode] : [sCode.toString(), "Unknown Reason"].join(" ");
	};

	sendFCGIRecord = function (socket, type, reqId, content) {
		var msgHeader = new Buffer(CONST.FCGIHeaderLength);

		msgHeader.fill(0);
		msgHeader[CONST.FCGIVersionOffset] = CONST.FCGIVersion;
		msgHeader[CONST.FCGITypeOffset] = CONST.FCGIRecordTypes.indexOf(type);
		msgHeader.writeUInt16BE(reqId, CONST.FCGIReqIdOffset);
		msgHeader.writeUInt16BE(content.length, CONST.FCGIContentLengthOffset);
		msgHeader[CONST.FCGIPaddingLengthOffset] = 0;

		if (socket.writable === true) {
			socket.write(Buffer.concat([msgHeader, content], CONST.FCGIHeaderLength + content.length));
		}
	};

	sendFCGIEndRecord = function (socket, reqId, reason) {
		sendFCGIRecord(socket, "FCGI_END_REQUEST", reqId, new Buffer([0, 0, 0, 0, CONST.FCGIEndReasons.indexOf(reason), 0, 0, 0]));
	};

	onConnection = function (socket) {
		var connection = {
			server : this,
			socket : socket,
			cDataBuffered : null,
			sessions : []
		};

		socket.setTimeout(this.timeout);

		socket.on("data", onClientData.bind(connection));
		socket.on("error", onSocketError.bind(connection));
		socket.on("end", onClientFin.bind(connection));
		socket.on("close", onSocketClose.bind(connection));
		socket.on("timeout", onSocketTimeout.bind(connection));
	};

	onClientData = function (data) {
		this.cDataBuffered = this.cDataBuffered !== null ? Buffer.concat([this.cDataBuffered, data], this.cDataBuffered.length + data.length) : data;

		while (this.cDataBuffered !== null) {
			let parsingData = this.cDataBuffered, msgHeader = {}, msgContent = null;

			if (parsingData.length < CONST.FCGIHeaderLength) {
				break;
			}

			msgHeader.version = parsingData[CONST.FCGIVersionOffset];
			msgHeader.type = parsingData[CONST.FCGITypeOffset];
			msgHeader.reqId = parsingData.readUInt16BE(CONST.FCGIReqIdOffset);
			msgHeader.contentLength = parsingData.readUInt16BE(CONST.FCGIContentLengthOffset);
			msgHeader.paddingLength = parsingData[CONST.FCGIPaddingLengthOffset];

			if (parsingData.length < CONST.FCGIHeaderLength + msgHeader.contentLength + msgHeader.paddingLength) {
				this.cDataBuffered = parsingData;
				break;
			} else if (parsingData.length > CONST.FCGIHeaderLength + msgHeader.contentLength + msgHeader.paddingLength) {
				this.cDataBuffered = parsingData.slice(CONST.FCGIHeaderLength + msgHeader.contentLength + msgHeader.paddingLength);
			} else {
				this.cDataBuffered = null;
			}

			if (! CONST.FCGIRecordTypes[msgHeader.type]) {
				sendFCGIRecord(this.socket, "FCGI_UNKNOWN_TYPE", 0, new Buffer([msgHeader.type, 0, 0, 0, 0, 0, 0, 0]));
				continue;
			}

			msgContent = parsingData.slice(CONST.FCGIHeaderLength, CONST.FCGIHeaderLength + msgHeader.contentLength);

			if (msgHeader.reqId === CONST.FCGINullReqId && CONST.FCGIRecordTypes[msgHeader.type] === "FCGI_GET_VALUES") {
				sendFCGIRecord(this.socket, "FCGI_GET_VALUES_RESULT", 0, new Buffer(0));
			} else if (CONST.FCGIRecordTypes[msgHeader.type] === "FCGI_BEGIN_REQUEST") {
				if (this.sessions[msgHeader.reqId] !== undefined) {
					sendFCGIEndRecord(this.socket, msgHeader.reqId, "FCGI_DUPLICATED_REQUEST");
				}

				if (msgContent.readUInt16BE(CONST.FCGIRoleOffset) !== CONST.FCGIRole) {
					sendFCGIEndRecord(this.socket, msgHeader.reqId, "FCGI_UNKNOWN_ROLE");
				}

				this.sessions[msgHeader.reqId] = {
					req : new ClientRequest(msgHeader.reqId, this.socket),
					res : new ServerResponse(msgHeader.reqId, this.socket),
					paramsEnded : false,
					bodyEnded : false,
				};

				if (msgContent[CONST.FCGIFlagsOffset] % 2 === 0) {
					this.sessions[msgHeader.reqId].res.closeSocketOnEnd = true;
				}
			} else {
				let session = this.sessions[msgHeader.reqId];

				if (session === undefined) {
					sendFCGIEndRecord(this.socket, msgHeader.reqId, "FCGI_UNOPENED_REQUEST");
					return;
				}

				switch (CONST.FCGIRecordTypes[msgHeader.type]) {
					case "FCGI_PARAMS":
						if (session.paramsEnded) {
							break;
						}

						if (msgContent.length === 0) {
							this.server.emit("request", session.req, session.res);
							session.paramsEnded = true;
							break;
						}

						for (let p = 0, s = 0, r = [0, 0, "", ""]; p < msgContent.length;) {
							switch (s) {
								case 0:
								case 1:
									r[s] += msgContent[p];

									if (msgContent[p] >= 0x80) {
										r[s] = msgContent.readUInt32BE(p) - 0x80000000;
										p += 4;
									} else {
										r[s] = msgContent[p];
										p += 1;
									}

									break;

								case 2:
								case 3:
									if (r[s % 2] !== 0) {
										r[s] = msgContent.slice(p, p += r[s % 2]).toString();
									}
									break;
							}

							s += 1;

							if (s === 4) {
								session.req.params[r[2]] = r[3];
								s = 0;
								r = [0, 0, "", ""];
							}
						}

						break;

					case "FCGI_STDIN":
					case "FCGI_DATA":
						if (session.bodyEnded) {
							break;
						}

						if (msgContent.length === 0) {
							session.req.emit("end");
							session.dataEnded = true;
						}

						session.req.emit("data", msgContent);

						break;
					case "FCGI_ABORT_REQUEST":
						sendFCGIEndRecord(this.socket, msgHeader.reqId, "FCGI_REQUEST_COMPLETE");
						return;

					default:
						sendFCGIEndRecord(this.socket, msgHeader.reqId, "FCGI_BAD_RECORD");
						return;
				}
			}
		}
	};

	onClientError = function (e, socket) {
		socket.destroy();
	};

	onClientFin = function () {
		if (this.clientPhase < 2) {
			this.server.emit("clientError", new Error("Client FIN before request completes"), this.socket);
		}
	};

	onSocketError = function (e) {
		this.server.emit("clientError", e, this.socket);
	};

	onSocketClose = function (hadError) {
		var self = this;

		self.socket.removeAllListeners();

		self.sessions.forEach(function (session) {
			session.req.emit("close");
			session.res.emit((hadError === false && self.socket._writableState.ended === true) ? "finish" : "close");
		});
	};

	onSocketTimeout = function () {
		this.server.emit("timeout", this.socket);

		process.nextTick(this.socket.end.bind(this.socket));
		process.nextTick(this.socket.destroy.bind(this.socket));
	};

	// Exporting
	exports.Server = Server;
	exports.ClientRequest = ClientRequest;
	exports.ServerResponse = ServerResponse;
	exports.createServer = createServer;
})();
<commit_msg>[fcgi] More secure socket handling [fcgi] Bulk HTTP header records<commit_after>// Copyright (C) 2014 Makoto Mizukami

(function () {
	"use strict";

	var DEFAULTS = {
		timeout : 180 * 1000	// Unit: second
	},

	CONST = {
		FCGIVersion : 1,
		FCGINullReqId : 0,
		FCGIRecordTypes : [
			undefined,
			"FCGI_BEGIN_REQUEST",
			"FCGI_ABORT_REQUEST",
			"FCGI_END_REQUEST",
			"FCGI_PARAMS",
			"FCGI_STDIN",
			"FCGI_STDOUT",
			"FCGI_STDERR",
			"FCGI_DATA",
			"FCGI_GET_VALUES",
			"FCGI_GET_VALUES_RESULT",
			"FCGI_UNKNOWN_TYPE"
		],
		FCGIEndReasons : [
			"FCGI_REQUEST_COMPLETE",
			"FCGI_CANT_MPX_CONN",
			"FCGI_OVERLOADED",
			"FCGI_UNKNOWN_ROLE"
		],
		FCGIRole : 1,
		FCGIHeaderLength : 8,
		FCGIVersionOffset : 0,
		FCGITypeOffset : 1,
		FCGIReqIdOffset : 2,
		FCGIContentLengthOffset : 4,
		FCGIPaddingLengthOffset : 6,
		FCGIRoleOffset : 0,
		FCGIFlagsOffset : 2,
	},

	// Classes
	Server, ClientRequest, ServerResponse,
	// Methods
	createServer,
	// Internal functions
	defaultStatusPhrase, formatFCGIRecord, sendFCGIRecord, sendFCGIEndRecord, onConnection, onClientData, onClientError, onClientFin, onSocketError, onSocketClose, onSocketTimeout,
	// Internal values
	CRLF = "\r\n", wellknownStatuses = require("./http_status.js").IANAStatuses,

	EE = require("events").EventEmitter, net = require("net"), util = require("util");

	Server = function (requestListener) {
		net.Server.call(this, { allowHalfOpen : true });

		if (typeof requestListener === typeof Function) {
			this.on("request", requestListener);
		}

		this.on("connection", onConnection);
		this.on("clientError", onClientError);
	};
	util.inherits(Server, net.Server);

	Server.prototype.timeout = DEFAULTS.timeout;

	Server.prototype.setTimeout = function (timeoutAfter, callback) {
		this.timeout = timeoutAfter;

		if (callback !== undefined) {
			this.on("timeout", callback);
		}
	};

	ClientRequest = function (id, socket) {
		EE.call(this);

		this.reqId = id;
		this.socket = socket;
		this.params = {};

		this.on("close", this.removeAllListeners);
	};
	util.inherits(ClientRequest, EE);

	ClientRequest.prototype.setTimeout = function (timeoutAfter, callback) {
		this.socket.setTimeout(timeoutAfter);

		if (callback !== undefined) {
			this.socket.on("timeout", callback);
		}
	};

	ServerResponse = function (id, socket) {
		var headerInfo = {
			fields : {},
			fieldQueue : [],
		};

		EE.call(this);

		this.reqId = id;
		this.socket = socket;
		this.closeSocketOnEnd = false;

		this.setHeader = ServerResponse.prototype.setHeader.bind(this, headerInfo);
		this.flushHeaders = ServerResponse.prototype.flushHeaders.bind(this, headerInfo);

		this.setStatus(200);

		this.on("close", this.removeAllListeners);
		this.on("finish", this.removeAllListeners);
	};
	util.inherits(ServerResponse, EE);

	ServerResponse.prototype.headerFinalized = false;

	ServerResponse.prototype.setStatus = function (sCode, reasonPhrase) {
		this.setHeader(["Status:", sCode.toString(), reasonPhrase !== undefined ? reasonPhrase : defaultStatusPhrase(sCode)].join(" "));
	};

	ServerResponse.prototype.setHeader = function (headerInfo, headerStatement) {
		var fieldName = headerStatement.split(":").shift().toLowerCase(),
		queued = headerInfo.fieldQueue.indexOf(fieldName);

		if (headerInfo.fields[fieldName] !== undefined && queued === -1) {
			return;
		}

		headerInfo.fields[fieldName] = headerStatement.trim();

		if (queued >= 0) {
			headerInfo.fieldQueue.splice(queued, 1);
		}

		headerInfo.fieldQueue.push(fieldName);
	};

	ServerResponse.prototype.flushHeaders = function (headerInfo, finalizeHeader) {
		var headerRecords = [];

		if (this.socket.writable !== true || this.headerFinalized === true) {
			return;
		}

		if (headerInfo.fieldQueue.length > 0) {
			headerInfo.fieldQueue.forEach(function (field) {
				headerRecords.push(formatFCGIRecord("FCGI_STDOUT", this.reqId, new Buffer(headerInfo.fields[field] + CRLF)));
			}.bind(this));
		}
		headerInfo.fieldQueue = [];

		if (finalizeHeader === true) {
			headerRecords.push(formatFCGIRecord("FCGI_STDOUT", this.reqId, new Buffer(CRLF)));
			this.headerFinalized = true;
		}

		if (this.socket.writable === true) {
			this.socket.write(Buffer.concat(headerRecords));
		}
	};

	ServerResponse.prototype.write = function (data) {
		this.headerFinalized !== true && this.flushHeaders(true);
		sendFCGIRecord(this.socket, "FCGI_STDOUT", this.reqId, new Buffer(data));
	};

	ServerResponse.prototype.end = function (data) {
		data !== undefined && this.write(data);
		sendFCGIRecord(this.socket, "FCGI_STDOUT", this.reqId, new Buffer(0));
		sendFCGIEndRecord(this.socket, this.reqId, "FCGI_REQUEST_COMPLETE");

		if (this.closeSocketOnEnd) {
			if (this.socket._writableState.writing === false) {
				this.socket.end();
			} else {
				this.socket.once("drain", this.socket.end);
			}
		}
	};

	createServer = function (requestListener) {
		return new Server(requestListener);
	};

	defaultStatusPhrase = function (sCode) {
		return wellknownStatuses[sCode] !== undefined ? wellknownStatuses[sCode] : [sCode.toString(), "Unknown Reason"].join(" ");
	};

	formatFCGIRecord = function (type, reqId, content) {
		var msgHeader = new Buffer(CONST.FCGIHeaderLength);

		msgHeader.fill(0);
		msgHeader[CONST.FCGIVersionOffset] = CONST.FCGIVersion;
		msgHeader[CONST.FCGITypeOffset] = CONST.FCGIRecordTypes.indexOf(type);
		msgHeader.writeUInt16BE(reqId, CONST.FCGIReqIdOffset);
		msgHeader.writeUInt16BE(content.length, CONST.FCGIContentLengthOffset);
		msgHeader[CONST.FCGIPaddingLengthOffset] = 0;

		return Buffer.concat([msgHeader, content], CONST.FCGIHeaderLength + content.length);
	};

	sendFCGIRecord = function (socket, type, reqId, content) {
		if (socket.writable === true) {
			socket.write(formatFCGIRecord(type, reqId, content));
		}
	};

	sendFCGIEndRecord = function (socket, reqId, reason) {
		sendFCGIRecord(socket, "FCGI_END_REQUEST", reqId, new Buffer([0, 0, 0, 0, CONST.FCGIEndReasons.indexOf(reason), 0, 0, 0]));
	};

	onConnection = function (socket) {
		var connection = {
			server : this,
			socket : socket,
			cDataBuffered : null,
			sessions : []
		};

		socket.setTimeout(this.timeout);

		socket.on("data", onClientData.bind(connection));
		socket.on("error", onSocketError.bind(connection));
		socket.on("end", onClientFin.bind(connection));
		socket.on("close", onSocketClose.bind(connection));
		socket.on("timeout", onSocketTimeout.bind(connection));
	};

	onClientData = function (data) {
		this.cDataBuffered = this.cDataBuffered !== null ? Buffer.concat([this.cDataBuffered, data], this.cDataBuffered.length + data.length) : data;

		while (this.cDataBuffered !== null) {
			let parsingData = this.cDataBuffered, msgHeader = {}, msgContent = null;

			if (parsingData.length < CONST.FCGIHeaderLength) {
				break;
			}

			msgHeader.version = parsingData[CONST.FCGIVersionOffset];
			msgHeader.type = parsingData[CONST.FCGITypeOffset];
			msgHeader.reqId = parsingData.readUInt16BE(CONST.FCGIReqIdOffset);
			msgHeader.contentLength = parsingData.readUInt16BE(CONST.FCGIContentLengthOffset);
			msgHeader.paddingLength = parsingData[CONST.FCGIPaddingLengthOffset];

			if (parsingData.length < CONST.FCGIHeaderLength + msgHeader.contentLength + msgHeader.paddingLength) {
				this.cDataBuffered = parsingData;
				break;
			} else if (parsingData.length > CONST.FCGIHeaderLength + msgHeader.contentLength + msgHeader.paddingLength) {
				this.cDataBuffered = parsingData.slice(CONST.FCGIHeaderLength + msgHeader.contentLength + msgHeader.paddingLength);
			} else {
				this.cDataBuffered = null;
			}

			if (! CONST.FCGIRecordTypes[msgHeader.type]) {
				sendFCGIRecord(this.socket, "FCGI_UNKNOWN_TYPE", 0, new Buffer([msgHeader.type, 0, 0, 0, 0, 0, 0, 0]));
				continue;
			}

			msgContent = parsingData.slice(CONST.FCGIHeaderLength, CONST.FCGIHeaderLength + msgHeader.contentLength);

			if (msgHeader.reqId === CONST.FCGINullReqId && CONST.FCGIRecordTypes[msgHeader.type] === "FCGI_GET_VALUES") {
				sendFCGIRecord(this.socket, "FCGI_GET_VALUES_RESULT", 0, new Buffer(0));
			} else if (CONST.FCGIRecordTypes[msgHeader.type] === "FCGI_BEGIN_REQUEST") {
				if (this.sessions[msgHeader.reqId] !== undefined) {
					sendFCGIEndRecord(this.socket, msgHeader.reqId, "FCGI_DUPLICATED_REQUEST");
					this.socket.end();
					break;
				}

				if (msgContent.readUInt16BE(CONST.FCGIRoleOffset) !== CONST.FCGIRole) {
					sendFCGIEndRecord(this.socket, msgHeader.reqId, "FCGI_UNKNOWN_ROLE");
					this.socket.end();
					break;
				}

				this.sessions[msgHeader.reqId] = {
					req : new ClientRequest(msgHeader.reqId, this.socket),
					res : new ServerResponse(msgHeader.reqId, this.socket),
					paramsEnded : false,
					bodyEnded : false,
				};

				if (msgContent[CONST.FCGIFlagsOffset] % 2 === 0) {
					this.sessions[msgHeader.reqId].res.closeSocketOnEnd = true;
				}
			} else {
				let session = this.sessions[msgHeader.reqId];

				if (session === undefined) {
					sendFCGIEndRecord(this.socket, msgHeader.reqId, "FCGI_UNOPENED_REQUEST");
					this.socket.end();
					return;
				}

				switch (CONST.FCGIRecordTypes[msgHeader.type]) {
					case "FCGI_PARAMS":
						if (session.paramsEnded) {
							break;
						}

						if (msgContent.length === 0) {
							this.server.emit("request", session.req, session.res);
							session.paramsEnded = true;
							break;
						}

						for (let p = 0, s = 0, r = [0, 0, "", ""]; p < msgContent.length;) {
							switch (s) {
								case 0:
								case 1:
									r[s] += msgContent[p];

									if (msgContent[p] >= 0x80) {
										r[s] = msgContent.readUInt32BE(p) - 0x80000000;
										p += 4;
									} else {
										r[s] = msgContent[p];
										p += 1;
									}

									break;

								case 2:
								case 3:
									if (r[s % 2] !== 0) {
										r[s] = msgContent.slice(p, p += r[s % 2]).toString();
									}
									break;
							}

							s += 1;

							if (s === 4) {
								session.req.params[r[2]] = r[3];
								s = 0;
								r = [0, 0, "", ""];
							}
						}

						break;

					case "FCGI_STDIN":
					case "FCGI_DATA":
						if (session.bodyEnded) {
							break;
						}

						if (msgContent.length === 0) {
							session.req.emit("end");
							session.dataEnded = true;
						}

						session.req.emit("data", msgContent);

						break;
					case "FCGI_ABORT_REQUEST":
						sendFCGIEndRecord(this.socket, msgHeader.reqId, "FCGI_REQUEST_COMPLETE");
						this.socket.end();
						return;

					default:
						sendFCGIEndRecord(this.socket, msgHeader.reqId, "FCGI_BAD_RECORD");
						this.socket.end();
						return;
				}
			}
		}
	};

	onClientError = function (e, socket) {
		socket.destroy();
	};

	onClientFin = function () {
		this.socket.end();
	};

	onSocketError = function (e) {
		this.server.emit("clientError", e, this.socket);
	};

	onSocketClose = function (hadError) {
		var self = this;

		self.socket.removeAllListeners();

		self.sessions.forEach(function (session) {
			session.req.emit("close");
			session.res.emit((hadError === false && self.socket._writableState.ended === true) ? "finish" : "close");
		});
	};

	onSocketTimeout = function () {
		this.server.emit("timeout", this.socket);

		process.nextTick(this.socket.end.bind(this.socket));
		process.nextTick(this.socket.destroy.bind(this.socket));
	};

	// Exporting
	exports.Server = Server;
	exports.ClientRequest = ClientRequest;
	exports.ServerResponse = ServerResponse;
	exports.createServer = createServer;
})();
<|endoftext|>


<commit_before>define(['app', 'jquery', 'lodash', 'providers/extended-route'], function(app, $, _) { 'use strict';

	app.config(['extendedRouteProvider', '$locationProvider', function($routeProvider, $locationProvider) {

		var baseHref = $("base").attr('href').toLowerCase();

		$locationProvider.html5Mode(true);
		$locationProvider.hashPrefix('!');

		//CONDITIONAL ROUTES

        if(baseHref == '/database/lmo/') {

            $routeProvider.when('/decisions.shtml',  { templateUrl: 'views/lmos/decisions-lmo-id.html', resolveController: true});

		}
        else if(baseHref == '/database/reports/') {

            $routeProvider.when('/',          { templateUrl: 'views/reports/index.html',    resolveController: true});
            $routeProvider.when('/analyzer',  { templateUrl: 'views/reports/analyzer.html', resolveController: true});

		}
		else {
			throw "Unhandled base:" + baseHref;
		}
	}]);
});
<commit_msg>Remove unused references<commit_after>define(['app', 'jquery', 'providers/extended-route'], function(app, $) { 'use strict';

	app.config(['extendedRouteProvider', '$locationProvider', function($routeProvider, $locationProvider) {

		var baseHref = $("base").attr('href').toLowerCase();

		$locationProvider.html5Mode(true);
		$locationProvider.hashPrefix('!');

		//CONDITIONAL ROUTES

        if(baseHref == '/database/lmo/') {

            $routeProvider.when('/decisions.shtml',  { templateUrl: 'views/lmos/decisions-lmo-id.html', resolveController: true});

		}
        else if(baseHref == '/database/reports/') {

            $routeProvider.when('/',          { templateUrl: 'views/reports/index.html',    resolveController: true});
            $routeProvider.when('/analyzer',  { templateUrl: 'views/reports/analyzer.html', resolveController: true});

		}
		else {
			throw "Unhandled base:" + baseHref;
		}
	}]);
});
<|endoftext|>


<commit_before>'use strict';

describe('search', function() {
  var createTokens = function() {
    return {
      '01' : {
        id: '01',
        string: 'Arma'
      },
      '02': {
        id: '02',
        string: 'virum'
      },
      '03': {
        id: '03',
        string: 'virum'
      }
    };
  };

  var mockConfigurator = {
    configurationFor: function(name) {
      return {};
    },

    getRetrievers: function(name) {
      return {};
    }
  };

  beforeEach(module('arethusa.core', function($provide) {
    $provide.value('configurator', mockConfigurator);
  }));

  beforeEach(module('arethusa.search'));

  var search;
  var state;
  beforeEach(inject(function(_search_, _state_) {
    search = _search_;
    state = _state_;
    state.tokens = createTokens();
    search.init();
  }));

  describe('this.findByRegex', function() {
    describe('finds tokens by a regex and returns their id in an array', function() {
      it('with simple regex', function() {
        var arg = 'um';
        expect(search.findByRegex(arg)).toEqual(['02', '03']);
      });
    });

    describe('with meta characters', function() {
      it('with .', function() {
        var arg = 'r.m';
        expect(search.findByRegex(arg)).toEqual(['02', '03']);
      });

      it('...', function() {
        // more tests to follow
      });
    });
  });

  describe('this.collectTokenStrings', function() {
    it('collects all strings of tokens as keys with their ids as values in an array', function() {
      var res = {'Arma': ['01'], 'virum': ['02', '03']};
      expect(search.collectTokenStrings()).toEqual(res);
    });
  });

  describe('this.pluginsWithSearch', function() {
    it('returns an array of plugins that have a search function', function() {
      var pluginA = { canSearch: true };
      var pluginB = { canSearch: false };
      var pluginC = { canSearch: true };
      var plugins = { "a": pluginA, "b": pluginB, "c": pluginC };
      expect(search.pluginsWithSearch(plugins)).toEqual([ pluginA, pluginC ]);
    });
  });
});
<commit_msg>Add specs for queryTokens()<commit_after>'use strict';

describe('search', function() {
  var createTokens = function() {
    return {
      '01' : {
        id: '01',
        string: 'Arma'
      },
      '02': {
        id: '02',
        string: 'virum'
      },
      '03': {
        id: '03',
        string: 'virum'
      },
      '04': {
        id: '04',
        string: 'cano'
      }
    };
  };

  var mockConfigurator = {
    configurationFor: function(name) {
      return {};
    },

    getRetrievers: function(name) {
      return {};
    }
  };

  beforeEach(module('arethusa.core', function($provide) {
    $provide.value('configurator', mockConfigurator);
  }));

  beforeEach(module('arethusa.search'));

  var search;
  var state;
  beforeEach(inject(function(_search_, _state_) {
    search = _search_;
    state = _state_;
    state.tokens = createTokens();
    search.init();
  }));

  describe('this.findByRegex', function() {
    describe('finds tokens by a regex and returns their id in an array', function() {
      it('with simple regex', function() {
        var arg = 'um';
        expect(search.findByRegex(arg)).toEqual(['02', '03']);
      });
    });

    describe('with meta characters', function() {
      it('with .', function() {
        var arg = 'r.m';
        expect(search.findByRegex(arg)).toEqual(['02', '03']);
      });

      it('...', function() {
        // more tests to follow
      });
    });
  });

  describe('this.queryTokens', function() {
    describe('returns a multiselection', function() {
      it('with one search lemma', function() {
        search.tokenQuery = 'virum';
        var res = state.multiSelect(['02', '03']);
        expect(search.queryTokens()).toEqual(res);
      });

      it('with two search lemmata', function() {
        search.tokenQuery = 'Arma virum';
        var res = state.multiSelect(['01', '02', '03']);
        expect(search.queryTokens()).toEqual(res);
      });

      it('with a lemma and a regex', function() {
        search.tokenQuery = 'Arma v.*m';
        var res = state.multiSelect(['01', '02', '03']);
        expect(search.queryTokens()).toEqual(res);
      });
    });
  });

  describe('this.collectTokenStrings', function() {
    it('collects all strings of tokens as keys with their ids as values in an array', function() {
      var res = {'Arma': ['01'], 'virum': ['02', '03'], 'cano': ['04']};
      expect(search.collectTokenStrings()).toEqual(res);
    });
  });

  describe('this.pluginsWithSearch', function() {
    it('returns an array of plugins that have a search function', function() {
      var pluginA = { canSearch: true };
      var pluginB = { canSearch: false };
      var pluginC = { canSearch: true };
      var plugins = { "a": pluginA, "b": pluginB, "c": pluginC };
      expect(search.pluginsWithSearch(plugins)).toEqual([ pluginA, pluginC ]);
    });
  });
});
<|endoftext|>


<commit_before>function drawAllPeopleDivsAtOnce(list_of_people_data) {
    var MAX_TO_DISPLAY = 100;
    var $text = $("
Drawing people...
");
    var i;
    var f;
    var $div;
    var $a;
    var $span;
    var text;
    var $results = $('

');

    $("#results").replaceWith($text);

    for (i = 0; i < list_of_people_data.length && i < MAX_TO_DISPLAY; i++) {
        f = list_of_people_data[i];
        href = "/people/" + f.attributes.all_data.extra_person_info.username;
        $a = $("", {class: 'person', href: href}).text(f.attributes.name);
        $span = $("", {class: 'geocode'}).text(f.attributes.location);
        $div = $("

").append($a).append($span);
        $results.append($div);
    }
    if (list_of_people_data.length >= MAX_TO_DISPLAY) {
        text = "and " + (list_of_people_data.length - MAX_TO_DISPLAY) + " more; zoom the map to see them, or search for them specifically.";
        $div = $("

").text(text);
        $results.append($div);
    }

    $text.replaceWith($results);
}

function drawResults() {
    var people_to_display_now = [];
    var extent = map.getExtent();
    var i;
    var feat;
    var j;
    var f;

    for (i = 0; i < layer.features.length; i++) {
        feat = layer.features[i];
        if (extent.intersectsBounds(feat.geometry.getBounds()))  {
            for (j = 0 ; j < feat.cluster.length; j++) {
                f = feat.cluster[j];
		people_to_display_now.push(f);
	    }
	}
    }
    drawAllPeopleDivsAtOnce(people_to_display_now);
}

function handleResults(data) {
    var key;
    var features = [];
    var person;
    var feature;

    for (key in data) {
	if (data.hasOwnProperty(key)) {
            person = data[key];
            feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(
		person.lat_long_data.longitude,
		person.lat_long_data.latitude),
						    {'name':person.name, 'location': person.location, 'all_data': person});
            feature.geometry.transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913"));
            features.push(feature);
	}
    }
    layer.destroyFeatures();
    layer.addFeatures(features);
    drawResults();
}

function init() {
    map = new OpenLayers.Map("map_canvas");
    var l = new OpenLayers.Layer.OSM();
    l.transitionEffect = "resize";
    map.addLayer(l);
    var styleMap =new OpenLayers.StyleMap({'default': new OpenLayers.Style(
        { fillColor: 'red','pointRadius':'${radius}', 'label': "${label}" },
                {
                    context: {
                        label: function(feature) {
                            return feature.cluster.length;
                        },
                        radius: function(feature) {
                            return feature.cluster ?
                                Math.min((Math.max(feature.cluster.length, 7) + 8)/2, 16) :
                                15;
                        }
                    }
                })});

    var s = new OpenLayers.Strategy.Cluster();
    layer = new OpenLayers.Layer.Vector("", {strategies: [ s ], styleMap: styleMap});
    map.addLayer(layer);
    s.activate();
    map.setCenter(new OpenLayers.LonLat(0, 0), 1);
    var query_string = 'person_ids=' + person_ids;
    jQuery.getJSON("/+profile_api/location_data/?" + query_string, handleResults);
    map.events.register("moveend", null, drawResults);
}
<commit_msg>Add a space in between person and location<commit_after>function drawAllPeopleDivsAtOnce(list_of_people_data) {
    var MAX_TO_DISPLAY = 100;
    var $text = $("
Drawing people...
");
    var i;
    var f;
    var $div;
    var $a;
    var $span;
    var text;
    var $results = $('

');

    $("#results").replaceWith($text);

    for (i = 0; i < list_of_people_data.length && i < MAX_TO_DISPLAY; i++) {
        f = list_of_people_data[i];
        href = "/people/" + f.attributes.all_data.extra_person_info.username;
        $a = $("", {class: 'person', href: href}).text(f.attributes.name);
        $span = $("", {class: 'geocode'}).text(f.attributes.location);
        $div = $("

").append($a).append(" ").append($span);
        $results.append($div);
    }
    if (list_of_people_data.length >= MAX_TO_DISPLAY) {
        text = "and " + (list_of_people_data.length - MAX_TO_DISPLAY) + " more; zoom the map to see them, or search for them specifically.";
        $div = $("

").text(text);
        $results.append($div);
    }

    $text.replaceWith($results);
}

function drawResults() {
    var people_to_display_now = [];
    var extent = map.getExtent();
    var i;
    var feat;
    var j;
    var f;

    for (i = 0; i < layer.features.length; i++) {
        feat = layer.features[i];
        if (extent.intersectsBounds(feat.geometry.getBounds()))  {
            for (j = 0 ; j < feat.cluster.length; j++) {
                f = feat.cluster[j];
		people_to_display_now.push(f);
	    }
	}
    }
    drawAllPeopleDivsAtOnce(people_to_display_now);
}

function handleResults(data) {
    var key;
    var features = [];
    var person;
    var feature;

    for (key in data) {
	if (data.hasOwnProperty(key)) {
            person = data[key];
            feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(
		person.lat_long_data.longitude,
		person.lat_long_data.latitude),
						    {'name':person.name, 'location': person.location, 'all_data': person});
            feature.geometry.transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913"));
            features.push(feature);
	}
    }
    layer.destroyFeatures();
    layer.addFeatures(features);
    drawResults();
}

function init() {
    map = new OpenLayers.Map("map_canvas");
    var l = new OpenLayers.Layer.OSM();
    l.transitionEffect = "resize";
    map.addLayer(l);
    var styleMap =new OpenLayers.StyleMap({'default': new OpenLayers.Style(
        { fillColor: 'red','pointRadius':'${radius}', 'label': "${label}" },
                {
                    context: {
                        label: function(feature) {
                            return feature.cluster.length;
                        },
                        radius: function(feature) {
                            return feature.cluster ?
                                Math.min((Math.max(feature.cluster.length, 7) + 8)/2, 16) :
                                15;
                        }
                    }
                })});

    var s = new OpenLayers.Strategy.Cluster();
    layer = new OpenLayers.Layer.Vector("", {strategies: [ s ], styleMap: styleMap});
    map.addLayer(layer);
    s.activate();
    map.setCenter(new OpenLayers.LonLat(0, 0), 1);
    var query_string = 'person_ids=' + person_ids;
    jQuery.getJSON("/+profile_api/location_data/?" + query_string, handleResults);
    map.events.register("moveend", null, drawResults);
}
<|endoftext|>


<commit_before>define(['app', 'lodash', 'text!views/index.html', 'views/index', 'providers/extended-route', 'authentication'], function(app, _, rootTemplate) { 'use strict';

    app.config(['extendedRouteProvider', '$locationProvider', function($routeProvider, $locationProvider) {

        $locationProvider.html5Mode(true);
        $locationProvider.hashPrefix('!');

        $routeProvider.
            when('/',                             { template:    rootTemplate,  label:'Home',  resolveController: 'views/index', reloadOnSearch : false }).
            when('/home', { redirectTo: '/' }).

            when('/about',                        { redirectTo: '/about/undb' }).
            when('/about/undb',                   { templateUrl: 'views/about/index.html',         label:'UNDB',          }).
            when('/about/goals',                  { templateUrl: 'views/about/goals.html',         label:'Goals',         }).
            when('/about/biodiversity',           { templateUrl: 'views/about/biodiversity.html',  label:'Biodiversity',  resolveController: true }).
            when('/about/iyb2010',                { templateUrl: 'views/about/iyb2010.html',       label:'IYB2010',       }).
            when('/about/sdgs',                   { templateUrl: 'views/about/sdgs.html',          label:'SDGs',          }).

            when('/actions',                      { redirectTo:  '/actions/worldwide' }).
            when('/actions/worldwide',            { templateUrl: 'views/actions/worldwide.html',        label:'Worldwide',            resolveController: true , reloadOnSearch : false}).
            when('/actions/country',              { templateUrl: 'views/actions/country.html',          label:'By Country',           resolveController: true }).
            when('/actions/countries/:code',      { templateUrl: 'views/actions/country-profile.html',  label :'Profile',             resolveController: true }).
            when('/actions/countries/edit/:code', { templateUrl: 'views/actions/country-profile-form.html', label:'Edit Party Profile',   resolveController: true, resolve : { user : securize(["UNDBPublishingAuthority", "undb-administrator"]) } }).
           // when('/actions/un',                 { templateUrl: 'views/actions/un.html',               label:'By UN Organization',   resolveController: true }).
            when('/actions/calendar',             { templateUrl: 'views/actions/calendar.html',         label:'Calendar',             resolveController: true }).
            when('/actions/participate',          { templateUrl: 'views/actions/participate.html',      label:'Participate'           }).
            when('/actions/submit',               { templateUrl: 'views/actions/submit.html',           label:'Participate',          resolveController: true, resolve : { user : securize(['User']) }, reloadOnSearch : false }).
            when('/actions/submit-form/:uid?',    { templateUrl: 'views/actions/submit-form.html',      label:'Form',                 resolveController: true, resolve : { user : securize(['User']) } }).
            when('/actions/submit-form-done',     { templateUrl: 'views/actions/submit-form-done.html', label:'Thanks',                                        resolve : { user : securize(['User']) } }).
            when('/actions/:identifier',          { templateUrl: 'views/actions/action.html',           label:'Action',               resolveController: true }).

            when('/actors',                      { templateUrl: 'views/actors/index.html',       label:'Actors'                   }).
            when('/actors/abttf',                { templateUrl: 'views/actors/abttf.html',       label:'ABTTF'                    }).
            when('/actors/champions',            { templateUrl: 'views/actors/champions.html',   label:'Biodiversity Champions'   }).
            when('/actors/blg',                  { templateUrl: 'views/actors/blg.html',         label:'BLG'                      }).
            when('/actors/jlg',                  { templateUrl: 'views/actors/jlg.html',         label:'JLG'                      }).
            when('/actors/partners',             { templateUrl: 'views/actors/partners.html',    label:'UNDB Partners',           resolveController: true, resolve : { user : currentUser() } }).
            when('/actors/partners/register',    { templateUrl: 'views/actors/submit-form.html', label:'Become a UNDB Partner',   resolveController: true, resolve : { user : securize(['User']) } }).
            when('/actors/partners/edit/:uid',   { templateUrl: 'views/actors/submit-form.html', label:'Become a UNDB Partner',   resolveController: true, resolve : { user : securize(['User']) } }).

            when('/resources',                   { templateUrl: 'views/resources/index.html',      label:'Resources'         }).
            when('/resources/logo',              { templateUrl: 'views/resources/logo.html',       label:'Logo'              }).
            when('/resources/materials',         { templateUrl: 'views/resources/materials.html',  label:'Printed Materials' }).
            when('/resources/multimedia',        { templateUrl: 'views/resources/multimedia.html', label:'Multimedia'        }).

            when('/help/404',                    { templateUrl: 'views/404.html',  label : 'Not found' }).
            when('/help/403',                    { templateUrl: 'views/403.html',  label : 'Forbidden' }).
            otherwise({ redirectTo: '/help/404' });
    }]);

    //============================================================
    //
    //
    //============================================================
    function currentUser() {

        return ['authentication', function (authentication) {

            return authentication.getUser();
        }];
    }

    //============================================================
    //
    //
    //============================================================
    function securize(roles) {

        return ['$location', '$window', '$q', 'authentication', function ($location, $window, $q, authentication) {

            return authentication.getUser().then(function (user) {

                if (!user.isAuthenticated) {

                    var returnUrl = $window.encodeURIComponent($window.location.href);
                    $window.location.href = 'https://accounts.cbd.int/signin?returnUrl=' + returnUrl; // force sign in
                    return $q(function () {});
                }
                else if (roles && !_.isEmpty(roles) && _.isEmpty(_.intersection(roles, user.roles))) {

                    $location.url('/help/403'); // not authorized
                }

                return user;
            });
        }];
    }

});
<commit_msg>routes for action and partner<commit_after>define(['app', 'lodash', 'text!views/index.html', 'views/index', 'providers/extended-route', 'authentication'], function(app, _, rootTemplate) { 'use strict';

    app.config(['extendedRouteProvider', '$locationProvider', function($routeProvider, $locationProvider) {

        $locationProvider.html5Mode(true);
        $locationProvider.hashPrefix('!');

        $routeProvider.
            when('/',                             { template:    rootTemplate,  label:'Home',  resolveController: 'views/index', reloadOnSearch : false }).
            when('/home', { redirectTo: '/' }).

            when('/about',                        { redirectTo: '/about/undb' }).
            when('/about/undb',                   { templateUrl: 'views/about/index.html',         label:'UNDB',          }).
            when('/about/goals',                  { templateUrl: 'views/about/goals.html',         label:'Goals',         }).
            when('/about/biodiversity',           { templateUrl: 'views/about/biodiversity.html',  label:'Biodiversity',  resolveController: true }).
            when('/about/iyb2010',                { templateUrl: 'views/about/iyb2010.html',       label:'IYB2010',       }).
            when('/about/sdgs',                   { templateUrl: 'views/about/sdgs.html',          label:'SDGs',          }).

            when('/actions',                      { redirectTo:  '/actions/worldwide' }).
            when('/actions/worldwide',            { templateUrl: 'views/actions/worldwide.html',        label:'Worldwide',            resolveController: true , reloadOnSearch : false}).
            when('/actions/country',              { templateUrl: 'views/actions/country.html',          label:'By Country',           resolveController: true }).
            when('/actions/countries/:code',      { templateUrl: 'views/actions/country-profile.html',  label :'Profile',             resolveController: true }).
            when('/actions/countries/edit/:code', { templateUrl: 'views/actions/country-profile-form.html', label:'Edit Party Profile',   resolveController: true, resolve : { user : securize(["UNDBPublishingAuthority", "undb-administrator"]) } }).
           // when('/actions/un',                 { templateUrl: 'views/actions/un.html',               label:'By UN Organization',   resolveController: true }).
            when('/actions/calendar',             { templateUrl: 'views/actions/calendar.html',         label:'Calendar',             resolveController: true }).
            when('/actions/participate',          { templateUrl: 'views/actions/participate.html',      label:'Participate'           }).
            when('/actions/submit',               { templateUrl: 'views/actions/submit.html',           label:'Participate',          resolveController: true, resolve : { user : securize(['User']) }, reloadOnSearch : false }).
            when('/actions/submit-form/:uid?',    { templateUrl: 'views/actions/submit-form.html',      label:'Form',                 resolveController: true, resolve : { user : securize(['User']) } }).
            when('/actions/submit-form-done',     { templateUrl: 'views/actions/submit-form-done.html', label:'Thanks',                                        resolve : { user : securize(['User']) } }).
            when('/actions/:uid',          { templateUrl: 'views/actions/action.html',           label:'Action',               resolveController: true }).

            when('/actors',                      { templateUrl: 'views/actors/index.html',       label:'Actors'                   }).
            when('/actors/abttf',                { templateUrl: 'views/actors/abttf.html',       label:'ABTTF'                    }).
            when('/actors/champions',            { templateUrl: 'views/actors/champions.html',   label:'Biodiversity Champions'   }).
            when('/actors/blg',                  { templateUrl: 'views/actors/blg.html',         label:'BLG'                      }).
            when('/actors/jlg',                  { templateUrl: 'views/actors/jlg.html',         label:'JLG'                      }).
            when('/actors/partners',             { templateUrl: 'views/actors/partners.html',    label:'UNDB Partners',           resolveController: true, resolve : { user : currentUser() } }).
            when('/actors/partners/register',    { templateUrl: 'views/actors/submit-form.html', label:'Become a UNDB Partner',   resolveController: true, resolve : { user : securize(['User']) } }).
            when('/actors/partners/edit/:uid',   { templateUrl: 'views/actors/submit-form.html', label:'Become a UNDB Partner',   resolveController: true, resolve : { user : securize(['User']) } }).
            when('/actors/partners/:uid',       { templateUrl: 'views/actors/actor.html',       label:'Actor',                   resolveController: true }).

            when('/resources',                   { templateUrl: 'views/resources/index.html',      label:'Resources'         }).
            when('/resources/logo',              { templateUrl: 'views/resources/logo.html',       label:'Logo'              }).
            when('/resources/materials',         { templateUrl: 'views/resources/materials.html',  label:'Printed Materials' }).
            when('/resources/multimedia',        { templateUrl: 'views/resources/multimedia.html', label:'Multimedia'        }).

            when('/help/404',                    { templateUrl: 'views/404.html',  label : 'Not found' }).
            when('/help/403',                    { templateUrl: 'views/403.html',  label : 'Forbidden' }).
            otherwise({ redirectTo: '/help/404' });
    }]);

    //============================================================
    //
    //
    //============================================================
    function currentUser() {

        return ['authentication', function (authentication) {

            return authentication.getUser();
        }];
    }

    //============================================================
    //
    //
    //============================================================
    function securize(roles) {

        return ['$location', '$window', '$q', 'authentication', function ($location, $window, $q, authentication) {

            return authentication.getUser().then(function (user) {

                if (!user.isAuthenticated) {

                    var returnUrl = $window.encodeURIComponent($window.location.href);
                    $window.location.href = 'https://accounts.cbd.int/signin?returnUrl=' + returnUrl; // force sign in
                    return $q(function () {});
                }
                else if (roles && !_.isEmpty(roles) && _.isEmpty(_.intersection(roles, user.roles))) {

                    $location.url('/help/403'); // not authorized
                }

                return user;
            });
        }];
    }

});
<|endoftext|>


<commit_before>/*
 * Copyright © Enable Software Pty Ltd 2013 - All rights reserved
 */

function FileSystem() {
    var _this = this;
    var deferred = new $.Deferred();

    var _this = this;
    this.filer = new Filer();
    this.filer.init({ persistent: false, size: 1024 * 1024 }, function () {
        deferred.resolveWith(_this);
    }, function() {
        console.log("FileSystem failed to initialise");
        deferred.rejectWith(_this);
    });

    return deferred.promise();
}

FileSystem.prototype.rename = function (src, dest) {
    GetGui().PushFileSystemOperation("local");
    var deferred = new $.Deferred();
    var _this = this;

    var bits = dest.split("/");
    var destFilename = _.last(bits);
    var destFolder = bits.slice(0, bits.length-1).join("/");

    this.filer.mv(src, destFolder, destFilename, function (fileEntry) {
        deferred.resolveWith(_this, [fileEntry]);
        GetGui().PopFileSystemOperation("local");
    }, function(e) {
        console.log("FileSystem.mv: Error[" + e.name +"] " + src + " " + dest);
        deferred.rejectWith(_this, [e]);
        GetGui().PopFileSystemOperation("local");
    });

    return deferred.promise();
}

FileSystem.prototype.save = function (path, data) {
    GetGui().PushFileSystemOperation("local");
    var deferred = new $.Deferred();
    var _this = this;

    this.filer.write(path, { data: data }, function (fileEntry, fileWriter) {
        deferred.resolveWith(_this, [fileEntry, fileWriter]);
        GetGui().PopFileSystemOperation("local");
    }, function(e) {
        console.log("FileSystem.save: Error[" + e.name +"] " + path);
        deferred.rejectWith(_this, [path, e]);
        GetGui().PopFileSystemOperation("local");
    });

    return deferred.promise();
};

FileSystem.prototype.stat = function (path) {
    GetGui().PushFileSystemOperation("local");
    var deferred = $.Deferred();
    var _this = this;

    this.filer.open(path, function(file) {
        GetGui().PopFileSystemOperation("local");
        deferred.resolveWith(_this, [file]);

    } , function() {
        GetGui().PopFileSystemOperation("local");
        deferred.reject();
    });
    return deferred.promise();
};

FileSystem.prototype.ls = function (path) {
    this.filer.ls(path, function (e) {
        for (var i in e) {
            console.log(e[i].name);
        }
    });
};

FileSystem.prototype.list = function (path, functor) {
    var _this = this;
    var deferred = $.Deferred();

    this.filer.ls(path, function (e) {
        var num = e.length;
        for (var i in e) {
            if (functor !== undefined) {
                functor(e[i], i == num-1);
            }
            e[i].title = e[i].name;
        }
        deferred.resolveWith(_this, [e]);
    }, function(e) {
        deferred.rejectWith(_this);
    });

    return deferred.promise();
};

FileSystem.prototype.rm = function (path) {
    var deferred = $.Deferred();
    var _this = this;

    //console.log("FileSystem.rm: " + path);

    //this.filer.open(path, function() {
        _this.filer.rm(path, function() {
            deferred.resolve();
        }, function() {
            deferred.reject();
        });
    //}, function() {
     //   deferred.reject();
//    });

    return deferred.promise();
};

FileSystem.prototype.mkdir = function (path) {
    var deferred = $.Deferred();
    this.filer.mkdir(path, false, function() {
        deferred.resolveWith(this);
    });
    return deferred.promise();
};

FileSystem.prototype.read = function (path, text) {
    GetGui().PushFileSystemOperation("local");
    var deferred = $.Deferred();

    var _this = this;
    _this.filer.open(path, function(file) {
        var reader = new FileReader();
        reader.onload = function (e) {
            deferred.resolveWith(this, [e.target.result]);
            GetGui().PopFileSystemOperation("local");
        };
        reader.onerror = function(e) {
            GetGui().PopFileSystemOperation("local");
        };
        if (text) {
            reader.readAsText(file);
        } else {
            reader.readAsArrayBuffer(file);
        }
    }, function(e) {
        deferred.rejectWith(this, [e]);
        GetGui().PopFileSystemOperation("local");
    });

    return deferred.promise();
};
<commit_msg>Hacked symlinks<commit_after>/*
 * Copyright © Enable Software Pty Ltd 2013 - All rights reserved
 */

function FileSystem() {
    var _this = this;
    var deferred = new $.Deferred();

    var _this = this;
    this.filer = new Filer();
    this.filer.init({ persistent: false, size: 1024 * 1024 }, function () {
        deferred.resolveWith(_this);
    }, function() {
        console.log("FileSystem failed to initialise");
        deferred.rejectWith(_this);
    });

    return deferred.promise();
}

FileSystem.prototype.rename = function (src, dest) {
    GetGui().PushFileSystemOperation("local");
    var deferred = new $.Deferred();
    var _this = this;

    var bits = dest.split("/");
    var destFilename = _.last(bits);
    var destFolder = bits.slice(0, bits.length-1).join("/");

    this.filer.mv(src, destFolder, destFilename, function (fileEntry) {
        deferred.resolveWith(_this, [fileEntry]);
        GetGui().PopFileSystemOperation("local");
    }, function(e) {
        console.log("FileSystem.mv: Error[" + e.name +"] " + src + " " + dest);
        deferred.rejectWith(_this, [e]);
        GetGui().PopFileSystemOperation("local");
    });

    return deferred.promise();
}

FileSystem.prototype.save = function (path, data) {
    GetGui().PushFileSystemOperation("local");
    var deferred = new $.Deferred();
    var _this = this;

    this.filer.write(path, { data: data }, function (fileEntry, fileWriter) {
        deferred.resolveWith(_this, [fileEntry, fileWriter]);
        GetGui().PopFileSystemOperation("local");
    }, function(e) {
        console.log("FileSystem.save: Error[" + e.name +"] " + path);
        deferred.rejectWith(_this, [path, e]);
        GetGui().PopFileSystemOperation("local");
    });

    return deferred.promise();
};

FileSystem.prototype.stat = function (path) {
    GetGui().PushFileSystemOperation("local");
    var deferred = $.Deferred();
    var _this = this;

    this.filer.open(path, function(file) {
        GetGui().PopFileSystemOperation("local");
        deferred.resolveWith(_this, [file]);

    } , function() {
        GetGui().PopFileSystemOperation("local");
        deferred.reject();
    });
    return deferred.promise();
};

FileSystem.prototype.ls = function (path) {
    this.filer.ls(path, function (e) {
        for (var i in e) {
            console.log(e[i].name);
        }
    });
};

FileSystem.prototype.list = function (path, functor) {
    var _this = this;
    var deferred = $.Deferred();

    this.filer.ls(path, function (e) {
        var num = e.length;
        for (var i in e) {
            if (functor !== undefined) {
                functor(e[i], i == num-1);
            }
            e[i].title = e[i].name;
        }
        deferred.resolveWith(_this, [e]);
    }, function(e) {
        deferred.rejectWith(_this);
    });

    return deferred.promise();
};

FileSystem.prototype.rm = function (path) {
    var deferred = $.Deferred();
    var _this = this;

    //console.log("FileSystem.rm: " + path);

    //this.filer.open(path, function() {
        _this.filer.rm(path, function() {
            deferred.resolve();
        }, function() {
            deferred.reject();
        });
    //}, function() {
     //   deferred.reject();
//    });

    return deferred.promise();
};

FileSystem.prototype.mkdir = function (path) {
    var deferred = $.Deferred();
    this.filer.mkdir(path, false, function() {
        deferred.resolveWith(this);
    });
    return deferred.promise();
};

FileSystem.prototype._read = function (path, text) {
    GetGui().PushFileSystemOperation("local");
    var deferred = $.Deferred();

    var _this = this;
    _this.filer.open(path, function (file) {
        var reader = new FileReader();
        reader.onload = function (e) {
            deferred.resolveWith(this, [e.target.result]);
            GetGui().PopFileSystemOperation("local");
        };
        reader.onerror = function (e) {
            GetGui().PopFileSystemOperation("local");
        };
        if (text) {
            reader.readAsText(file);
        } else {
            reader.readAsArrayBuffer(file);
        }
    }, function (e) {
        deferred.rejectWith(this, [e]);
        GetGui().PopFileSystemOperation("local");
    });

    return deferred.promise();
};

FileSystem.prototype.read = function (path, text) {
    var deferred = $.Deferred();
    var _this = this;

    function success(fileData) {
       	if (fileData.byteLength == 64) {
	    var dv = new DataView(fileData);
	    if (String.fromCharCode(dv.getUint8(0)) == "#" &&
		String.fromCharCode(dv.getUint8(1)) == "!" &&
		String.fromCharCode(dv.getUint8(2)) == "!" &&
		String.fromCharCode(dv.getUint8(3)) == "#") {
		path = String.fromCharCode.apply(null, new Uint8Array(fileData)).slice(4).trim();
		doread();
	    } else {
		deferred.resolveWith(this, [fileData]);
	    }
	} else {
	    deferred.resolveWith(this, [fileData]);
	}
    }

    function doread() {
        _this._read(path, text).done(function (fileData) {
            success(fileData);
        }).fail(function (e) {
            deferred.rejectWith(this, [e]);
        });
    }

    doread();

    return deferred.promise();
};
<|endoftext|>


<commit_before>//when we go to deployment, switch to "express" as the server
// var webpack = require('webpack-dev-server');
// var app = webpack();
var express = require('express')
var app = express();
var path = require('path')
var port = 8080;

var teachers_routes = require('./routes/teacher')

console.log(teachers_routes)

app.use('/teachers', teachers_routes)

app.use(express.static(path.join(__dirname, 'public')));

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs')

var server = app.listen(port, function(){
	var host = server.address().address;
	var port = server.address().port;
	console.log('Listening on http://', host, port)
});

<commit_msg>add socket.io<commit_after>//when we go to deployment, switch to "express" as the server
// var webpack = require('webpack-dev-server');
// var app = webpack();
var express = require('express')
var app = express();
var path = require('path')
var io = require('socket.io').listen(app);
var port = 8080;

var teachers_routes = require('./routes/teacher')

console.log(teachers_routes)

app.use('/teachers', teachers_routes)

app.use(express.static(path.join(__dirname, 'public')));

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs')

var server = app.listen(port, function(){
	var host = server.address().address;
	var port = server.address().port;
	console.log('Listening on http://', host, port)
});

io.of('teacher').on('connection', function(socket){
  console.log('data received');
  socket.on('start', function(data){
    io.emit('start', data);
  })

})

<|endoftext|>


<commit_before>import Express from 'express';
import favicon from 'serve-favicon';
import compression from 'compression';
import httpProxy from 'http-proxy';
import path from 'path';
import PrettyError from 'pretty-error';
import http from 'http';
import config from './config';
import Html from './Html';
import createStore from './redux/createStore';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import { StaticRouter } from 'react-router';
import ServerTemplate from './ServerTemplate';
import { Provider } from 'react-redux';

const targetUrl = `http://${config.apiHost}:${config.apiPort}`;
const pretty = new PrettyError();
const app = new Express();
const server = new http.Server(app);
const maxAge = 86400000 * 7; // a week
const proxy = httpProxy.createProxyServer({
  target: targetUrl,
  ws: true
});

app.use(compression());
app.use((req, res, next) => {
  if (req.url.match(/^\/(css|js|img|font|woff2|svg|ttf|eot|woff)\/.+/)) {
    res.setHeader('Cache-Control', 'public, max-age=' + maxAge);
  }
  next();
});
app.use(favicon(path.join(__dirname, '..', 'static', 'favicon.ico')));
app.use(Express.static(path.join(__dirname, '..', 'static')));

// Proxy to API server
app.use('/api', (req, res) => {
  proxy.web(req, res, { target: targetUrl });
});

app.use('/ws', (req, res) => {
  proxy.web(req, res, { target: targetUrl + '/ws' });
});

server.on('upgrade', (req, socket, head) => {
  proxy.ws(req, socket, head);
});

// added the error handling to avoid https://github.com/nodejitsu/node-http-proxy/issues/527
proxy.on('error', (error, req, res) => {
  if (error.code !== 'ECONNRESET') {
    console.error('proxy error', error);
  }
  if (!res.headersSent) {
    res.writeHead(500, { 'content-type': 'application/json' });
  }

  const json = { error: 'proxy_error', reason: error.message };
  res.end(JSON.stringify(json));
});

app.use((req, res) => {
  if (__DEVELOPMENT__) {
    // Do not cache webpack stats: the script file would change since
    // hot module replacement is enabled in the development env
    webpackIsomorphicTools.refresh();
  }
  const store = createStore();

  function hydrateOnClient() {
    res.send('<!doctype html>\n' +
      ReactDOMServer.renderToString(<Html assets={webpackIsomorphicTools.assets()} store={store} />));
  }

  if (__DISABLE_SSR__) {
    hydrateOnClient();
    return;
  }

  const context = {};
  const component = (
    <Provider store={store} key="provider">
      <StaticRouter location={req.url} context={context}>
        <ServerTemplate />
      </StaticRouter>
    </Provider>
  );
  const html = ReactDOM.renderToString(
    <Html
      assets={webpackIsomorphicTools.assets()}
      component={component}
      store={store}
    />
  );

  if (context.url) {
    res.writeHead(302, {
      Location: context.url
    });
    res.end();
  } else {
    res.send('<!doctype html>\n' + html);
  }
});

if (config.port) {
  server.listen(config.port, (err) => {
    if (err) {
      console.error(err);
    }
    console.info('----\n==> ✅  %s is running, talking to API server on %s.', config.app.title, config.apiPort);
    console.info('==> 💻  Open http://%s:%s in a browser to view the app.', config.host, config.port);
  });
} else {
  console.error('==>     ERROR: No PORT environment variable has been specified');
}
<commit_msg>fix port<commit_after>import Express from 'express';
import favicon from 'serve-favicon';
import compression from 'compression';
import httpProxy from 'http-proxy';
import path from 'path';
import PrettyError from 'pretty-error';
import http from 'http';
import config from './config';
import Html from './Html';
import createStore from './redux/createStore';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import { StaticRouter } from 'react-router';
import ServerTemplate from './ServerTemplate';
import { Provider } from 'react-redux';

const targetUrl = `http://${config.apiHost}:${config.apiPort}`;
const pretty = new PrettyError();
const app = new Express();
const server = new http.Server(app);
const maxAge = 86400000 * 7; // a week
const proxy = httpProxy.createProxyServer({
  target: targetUrl,
  ws: true
});

app.use(compression());
app.use((req, res, next) => {
  if (req.url.match(/^\/(css|js|img|font|woff2|svg|ttf|eot|woff)\/.+/)) {
    res.setHeader('Cache-Control', 'public, max-age=' + maxAge);
  }
  next();
});
app.use(favicon(path.join(__dirname, '..', 'static', 'favicon.ico')));
app.use(Express.static(path.join(__dirname, '..', 'static')));

// Proxy to API server
app.use('/api', (req, res) => {
  proxy.web(req, res, { target: targetUrl });
});

app.use('/ws', (req, res) => {
  proxy.web(req, res, { target: targetUrl + '/ws' });
});

server.on('upgrade', (req, socket, head) => {
  proxy.ws(req, socket, head);
});

// added the error handling to avoid https://github.com/nodejitsu/node-http-proxy/issues/527
proxy.on('error', (error, req, res) => {
  if (error.code !== 'ECONNRESET') {
    console.error('proxy error', error);
  }
  if (!res.headersSent) {
    res.writeHead(500, { 'content-type': 'application/json' });
  }

  const json = { error: 'proxy_error', reason: error.message };
  res.end(JSON.stringify(json));
});

app.use((req, res) => {
  if (__DEVELOPMENT__) {
    // Do not cache webpack stats: the script file would change since
    // hot module replacement is enabled in the development env
    webpackIsomorphicTools.refresh();
  }
  const store = createStore();

  function hydrateOnClient() {
    res.send('<!doctype html>\n' +
      ReactDOMServer.renderToString(<Html assets={webpackIsomorphicTools.assets()} store={store} />));
  }

  if (__DISABLE_SSR__) {
    hydrateOnClient();
    return;
  }

  const context = {};
  const component = (
    <Provider store={store} key="provider">
      <StaticRouter location={req.url} context={context}>
        <ServerTemplate />
      </StaticRouter>
    </Provider>
  );
  const html = ReactDOM.renderToString(
    <Html
      assets={webpackIsomorphicTools.assets()}
      component={component}
      store={store}
    />
  );

  if (context.url) {
    res.writeHead(302, {
      Location: context.url
    });
    res.end();
  } else {
    res.send('<!doctype html>\n' + html);
  }
});

if (process.env.PORT || config.port) {
  server.listen(process.env.PORT || config.port, (err) => {
    if (err) {
      console.error(err);
    }
    console.info('----\n==> ✅  %s is running, talking to API server on %s.', config.app.title, config.apiPort);
    console.info('==> 💻  Open http://%s:%s in a browser to view the app.', config.host, config.port);
  });
} else {
  console.error('==>     ERROR: No PORT environment variable has been specified');
}
<|endoftext|>