<commit_before>"use strict";


/*global nodeca*/


// nodeca
var NLib = require('nlib');


// 3rd-party
var _ = NLib.Vendor.Underscore;
var connect = require('connect');


// HELPERS /////////////////////////////////////////////////////////////////////


function find_view(scope, api_path) {
  var parts = api_path.split('.');

  while (scope && parts.length) {
    scope = scope[parts.shift()];
  }

  return scope;
}


function start_server(app, next) {
  var server, host, port, err_handler, attempt = 0;

  // create server
  host    = nodeca.config.listen.host || 'localhost';
  port    = nodeca.config.listen.port || 3000;
  server  = require('http').createServer(app);

  err_handler = function (err) {
    if (err.code === 'EADDRINUSE') {
      if (3 <= attempt) {
        next("Maximum amount of attempts reached. Can't continue.");
        return;
      }

      attempt += 1;
      nodeca.logger.warn('Address <' + host + ':' + port + '> in use, retrying... ');
      setTimeout(function () { server.listen(port, host); }, 1000);
    }
  };

  server.on('error', err_handler);

  // start server
  server.listen(port, host, function () {
    server.removeListener('error', err_handler);
    next();
  });
}


// MODULE EXPORTS //////////////////////////////////////////////////////////////


module.exports = function (next) {
  var app = connect(), default_host = nodeca.config.listen.host, static_helpers;

  if (!!nodeca.config.listen.port && 80 !== +nodeca.config.listen.port) {
    default_host += ":" + nodeca.config.listen.port;
  }

  app.use("/assets/", nodeca.runtime.assets_server.middleware);

  // middlewares
  app.use(connect.query());

  // define some request/session insensitive view helpers
  static_helpers = {
    link_to: function (name, params) {
      return nodeca.runtime.router.linkTo(name, params) || '#';
    }
  };

  // main worker
  app.use(function (req, res) {
    var host = req.headers.host || default_host, env, match, params;

    // remove port part if it's 80
    if ('80' === host.split(':')[1]) {
      host = host.split(':')[0];
    }

    match = nodeca.runtime.router.match('//' + host + req.url.split('?').shift());

    if (!match) {
      // TODO: Fix not found handling
      res.statusCode = 404;
      res.end('Not found');
      return;
    }

    // prefill environment
    env = {
      request: {
        origin: 'HTTP',
        method: match.meta.name
      },
      session: {
        // FIXME: use req.session instead
        theme: 'desktop',
        lang: nodeca.config.locales.default
      },
      response: {
        err: {
          code: null,
          message: null
        },
        data: {},
        layout: 'default',
        view: match.meta.name
      }
    };

    // mix GET QUERY params (part after ? in URL) and params from router
    // params from router tke precedence<commit_msg>Expose request namespace in http server<commit_after>"use strict";


/*global nodeca*/


// nodeca
var NLib = require('nlib');


// 3rd-party
var _ = NLib.Vendor.Underscore;
var connect = require('connect');


// HELPERS /////////////////////////////////////////////////////////////////////


function find_view(scope, api_path) {
  var parts = api_path.split('.');

  while (scope && parts.length) {
    scope = scope[parts.shift()];
  }

  return scope;
}


function start_server(app, next) {
  var server, host, port, err_handler, attempt = 0;

  // create server
  host    = nodeca.config.listen.host || 'localhost';
  port    = nodeca.config.listen.port || 3000;
  server  = require('http').createServer(app);

  err_handler = function (err) {
    if (err.code === 'EADDRINUSE') {
      if (3 <= attempt) {
        next("Maximum amount of attempts reached. Can't continue.");
        return;
      }

      attempt += 1;
      nodeca.logger.warn('Address <' + host + ':' + port + '> in use, retrying... ');
      setTimeout(function () { server.listen(port, host); }, 1000);
    }
  };

  server.on('error', err_handler);

  // start server
  server.listen(port, host, function () {
    server.removeListener('error', err_handler);
    next();
  });
}


// MODULE EXPORTS //////////////////////////////////////////////////////////////


module.exports = function (next) {
  var app = connect(), default_host = nodeca.config.listen.host, static_helpers;

  if (!!nodeca.config.listen.port && 80 !== +nodeca.config.listen.port) {
    default_host += ":" + nodeca.config.listen.port;
  }

  app.use("/assets/", nodeca.runtime.assets_server.middleware);

  // middlewares
  app.use(connect.query());

  // define some request/session insensitive view helpers
  static_helpers = {
    link_to: function (name, params) {
      return nodeca.runtime.router.linkTo(name, params) || '#';
    }
  };

  // main worker
  app.use(function (req, res) {
    var host = req.headers.host || default_host, env, match, params;

    // remove port part if it's 80
    if ('80' === host.split(':')[1]) {
      host = host.split(':')[0];
    }

    match = nodeca.runtime.router.match('//' + host + req.url.split('?').shift());

    if (!match) {
      // TODO: Fix not found handling
      res.statusCode = 404;
      res.end('Not found');
      return;
    }

    // prefill environment
    env = {
      request: {
        origin: 'HTTP',
        method: match.meta.name,
        namespace: match.meta.name.split('.').shift()
      },
      session: {
        // FIXME: use req.session instead
        theme: 'desktop',
        lang: nodeca.config.locales.default
      },
      response: {
        err: {
          code: null,
          message: null
        },
        data: {},
        layout: 'default',
        view: match.meta.name
      }
    };

    // mix GET QUERY params (part after ? in URL) and params from router
    // params from router tke precedence
{'fraction_non_alphanumeric': 0.197185515702763, 'fraction_numerical': 0.00789428522395744, 'mean_word_length': 2.0787110406761755, 'pattern_counts': {'":': 2, '<': 7, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2814323', 'n_tokens_mistral': 1856, 'n_tokens_neox': 1765, 'n_words': 418}