<commit_before>'use strict';

var _ = require('lodash');
var path = require('path');
var util = require('util');
var crypto = require('crypto');
var hget = require('hget');
var accepts = require('./accepts');
var resolvers = require('./resolvers');
var optionalRequire = require('./optionalRequire');
var state = require('./state');
var rc = require('./rc');

function md5 (value) {
  return crypto.createHash('md5').update(value).digest('hex');
}

function render (defaultAction, vm, req, res, next) {
  var data = _.merge({}, state.defaults, vm);
  var accept = accepts(req);

  if (data.skip || !accept) {
    next(); return;
  }

  data.requestUrl = req.url + '?json';
  data.model = data.model || {};
  data.version = state.version;

  var action = data.model.action || defaultAction;
  var strategy;

  if (req.flash) {
    data.model.flash = req.flash();
  }

  if (req.user) {
    data.model.user = req.user;
  }

  if (data.statusCode) {
    res.status(data.statusCode);
    delete data.statusCode;
  }

  headers();

  if (accept === 'json' || 'json' in req.query) {
    strategy = 'callback' in req.query ? 'jsonp' : 'json';
    res[strategy]({
      version: data.version,
      model: data.model
    });
  } else if (accept === 'html') {
    html(res.send.bind(res));
  } else if (accept === 'text') {
    html(toText);
  }

  function headers () {
    var etag = md5(JSON.stringify(data));
    res.set('Vary', 'Accept');
    res.set('ETag', etag);
    res.set('cache-control', 'private, must-revalidate, max-age=0');
  }

  function html (done) {
    var location = resolvers.getView(action);
    var relative = path.relative(__dirname, location);
    var template = optionalRequire(location);
    if (template === null) {
      console.warn('Missing view template for "%s" action. Searched location: "%s"', action, location);
      data.partial = '';
    } else {
      data.partial = template(data.model);
    }

    try {
      if (typeof rc.layout === 'function') {
        done(rc.layout(data));
      } else {
        console.warn('Missing Taunus view layout. Should be assigned as a method on `options`: taunus.mount(addRoute, { layout })');
        done(util.format('
%s
', JSON.stringify(data, null, 2)));
      }
    } catch (err) {
      next(err);
    }
  }

  function toText (html) {
    res.send(hget(html, state.plaintext));
  }
}

function defer () {
  var args = Array.prototype.slice.call(arguments);
  if (state.defaults) {
    deferred();
  } else {
    state.once('defaults', deferred);
  }
  function deferred () {
    render.apply(null, args);
  }
}

module.exports = defer;
<commit_msg>rm statusCode option<commit_after>'use strict';

var _ = require('lodash');
var path = require('path');
var util = require('util');
var crypto = require('crypto');
var hget = require('hget');
var accepts = require('./accepts');
var resolvers = require('./resolvers');
var optionalRequire = require('./optionalRequire');
var state = require('./state');
var rc = require('./rc');

function md5 (value) {
  return crypto.createHash('md5').update(value).digest('hex');
}

function render (defaultAction, vm, req, res, next) {
  var data = _.merge({}, state.defaults, vm);
  var accept = accepts(req);

  if (data.skip || !accept) {
    next(); return;
  }

  data.requestUrl = req.url + '?json';
  data.model = data.model || {};
  data.version = state.version;

  var action = data.model.action || defaultAction;
  var strategy;

  if (req.flash) {
    data.model.flash = req.flash();
  }

  if (req.user) {
    data.model.user = req.user;
  }

  headers();

  if (accept === 'json' || 'json' in req.query) {
    strategy = 'callback' in req.query ? 'jsonp' : 'json';
    res[strategy]({
      version: data.version,
      model: data.model
    });
  } else if (accept === 'html') {
    html(res.send.bind(res));
  } else if (accept === 'text') {
    html(toText);
  }

  function headers () {
    var etag = md5(JSON.stringify(data));
    res.set('Vary', 'Accept');
    res.set('ETag', etag);
    res.set('cache-control', 'private, must-revalidate, max-age=0');
  }

  function html (done) {
    var location = resolvers.getView(action);
    var relative = path.relative(__dirname, location);
    var template = optionalRequire(location);
    if (template === null) {
      console.warn('Missing view template for "%s" action. Searched location: "%s"', action, location);
      data.partial = '';
    } else {
      data.partial = template(data.model);
    }

    try {
      if (typeof rc.layout === 'function') {
        done(rc.layout(data));
      } else {
        console.warn('Missing Taunus view layout. Should be assigned as a method on `options`: taunus.mount(addRoute, { layout })');
        done(util.format('
%s
', JSON.stringify(data, null, 2)));
      }
    } catch (err) {
      next(err);
    }
  }

  function toText (html) {
    res.send(hget(html, state.plaintext));
  }
}

function defer () {
  var args = Array.prototype.slice.call(arguments);
  if (state.defaults) {
    deferred();
  } else {
    state.once('defaults', deferred);
  }
  function deferred () {
    render.apply(null, args);
  }
}

module.exports = defer;
<|endoftext|>


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

/**
 * @module rindle
 */

var _ = require('lodash');
var Promise = require('bluebird');
var stringToStream = require('string-to-stream');

/**
 * @summary Wait for a stream to close
 * @function
 * @public
 *
 * @description
 * This functions listens for the following events:
 *
 * - `close`.
 * - `end`.
 * - `done`.
 *
 * If those events pass any argument when being emitted, you'll be able to access them as arguments to the callback.
 *
 * @param {Stream} stream - stream
 * @param {Function} callback - callback (error, args...)
 *
 * @example
 * var fs = require('fs');
 * var rindle = require('rindle');
 *
 * var input = fs.createReadStream('foo/bar');
 * var output = fs.createWriteStream('foo/baz');
 *
 * input.pipe(output);
 *
 * rindle.wait(output, function(error) {
 *   if (error) throw error;
 *   console.log('The output stream was closed!');
 * });
 */
exports.wait = function(stream, callback) {
  'use strict';

  return new Promise(function(resolve, reject) {
    var done = function() {
      return resolve(_.values(arguments));
    };

		stream.on('error', reject);
    stream.on('close', done);
    stream.on('end', done);
    stream.on('done', done);
  }).nodeify(callback, {
    spread: true
  });
};

/**
 * @summary Extract data from readable stream
 * @function
 * @public
 *
 * @description
 * Notice this function only extracts the *remaining data* from the stream.
 *
 * @param {StreamReadable} stream - stream
 * @param {Function} callback - callback (error, data)
 *
 * @example
 * var fs = require('fs');
 * var rindle = require('rindle');
 *
 * var input = fs.createReadStream('foo/bar');
 *
 * rindle.extract(input, function(error, data) {
 *   if (error) throw error;
 *   console.log('The file contains: ' + data);
 * });
 */
exports.extract = function(stream, callback) {
  'use strict';

  var chunks = '';

  stream.on('data', function(chunk) {
    chunks += chunk;
  });

  return exports.wait(stream).then(function() {
    return chunks;
  }).nodeify(callback);
};

/**
 * @summary Bifurcate readable stream to two writable streams
 * @function
 * @public
 *
 * @description
 * The callback is called when both output stream close.
 *
 * @param {StreamReadable} stream - input stream
 * @param {StreamWritable} output1 - first output stream
 * @param {StreamWritable} output2 - second output stream
 * @param {Function} callback - callback (error)
 *
 * @example
 *
 * var fs = require('fs');
 * var rindle = require('rindle');
 *
 * var input = fs.createReadStream('foo/bar');
 * var output1 = fs.createWriteStream('foo/baz');
 * var output2 = fs.createWriteStream('foo/qux');
 *
 * rindle.bifurcate(input, output1, output2, function(error) {
 *   if (error) throw error;
 *
 *   console.log('All files written!');
 * });
 */
exports.bifurcate = function(stream, output1, output2, callback) {
  'use strict';

  stream.pipe(output1);
  stream.pipe(output2);

  // Fulfil once we finish writing to both output streams
  return Promise.all([
    exports.wait(output1),
    exports.wait(output2)
  ]).nodeify(callback);
};

/**
 * @summary Pipe a stream along with certain events
 * @function
 * @public
 *
 * @param {StreamReadable} stream - input stream
 * @param {StreamWritable} output - output stream
 * @param {String[]} events - events to pipe
 *
 * @returns {StreamReadable} resulting stream
 *
 * @example
 * var rindle = require('rindle');
 *
 * rindle.pipeWithEvents(input, output, [
 *   'response',
 *   'request'
 * ]);
 */
exports.pipeWithEvents = function(stream, output, events) {
  'use strict';

  _.each(events, function(event) {
    stream.on(event, function() {
      var args = Array.prototype.slice.call(arguments);
      args.unshift(event);
      output.emit.apply(output, args);
    });
  });

  return stream.pipe(output);
};

/**
 * @summary Wait for a stream to emit a certain event
 * @function
 * @public
 *
 * @param {Stream} stream - stream
 * @param {String} event - event name
 * @param {Function} callback - callback (error, args...)
 *
 * @example
 * var rindle = require('rindle');
 * var fs = require('fs');
 *
 * rindle.onEvent(fs.createReadStream('foo/bar'), 'open', function(error, fd) {
 *   if (error) throw error;
 *
 *   console.log('The "open" event was emitted');
 *   console.log(fd);
 * });
 */
exports.onEvent = function(stream, event, callback) {
  'use strict';

  return new Promise(function(resolve) {
    stream.on(event, function() {
      var args = Array.prototype.slice.call(arguments);

      if (_.isEmpty(args)) {
        args = undefined;
      }
      else if (args.length === 1) {
        args = _.head(args);
      }

      return resolve(args);
    });
  }).nodeify(callback, {
    spread: true
  });
};

/**
 * @summary Get a readable stream from a string
 * @function
 * @public
 *
 * @param {String} string - input string
 * @returns {ReadableStream} - string stream
 *
 * @example
 * var rindle = require('rindle');
 * rindle.getStreamFromString('Hello World!').pipe(process.stdout);
 */
exports.getStreamFromString = function(string) {
  'use strict';

  if (!_.isString(string)) {
    throw new Error('Not a string: ' + string);
  }

  return stringToStream(string);
};
<commit_msg>Should import lodash methods independently to reduce bundle size<commit_after>/*
 * The MIT License
 *
 * Copyright (c) 2015 Juan Cruz Viotti. https://jviotti.github.io
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/**
 * @module rindle
 */

var Promise = require('bluebird');
var each = require('lodash/each');
var head = require('lodash/head');
var isEmpty = require('lodash/isEmpty');
var isString = require('lodash/isString');
var values = require('lodash/values');
var stringToStream = require('string-to-stream');

/**
 * @summary Wait for a stream to close
 * @function
 * @public
 *
 * @description
 * This functions listens for the following events:
 *
 * - `close`.
 * - `end`.
 * - `done`.
 *
 * If those events pass any argument when being emitted, you'll be able to access them as arguments to the callback.
 *
 * @param {Stream} stream - stream
 * @param {Function} callback - callback (error, args...)
 *
 * @example
 * var fs = require('fs');
 * var rindle = require('rindle');
 *
 * var input = fs.createReadStream('foo/bar');
 * var output = fs.createWriteStream('foo/baz');
 *
 * input.pipe(output);
 *
 * rindle.wait(output, function(error) {
 *   if (error) throw error;
 *   console.log('The output stream was closed!');
 * });
 */
exports.wait = function(stream, callback) {
  'use strict';

  return new Promise(function(resolve, reject) {
    var done = function() {
      return resolve(values(arguments));
    };

		stream.on('error', reject);
    stream.on('close', done);
    stream.on('end', done);
    stream.on('done', done);
  }).nodeify(callback, {
    spread: true
  });
};

/**
 * @summary Extract data from readable stream
 * @function
 * @public
 *
 * @description
 * Notice this function only extracts the *remaining data* from the stream.
 *
 * @param {StreamReadable} stream - stream
 * @param {Function} callback - callback (error, data)
 *
 * @example
 * var fs = require('fs');
 * var rindle = require('rindle');
 *
 * var input = fs.createReadStream('foo/bar');
 *
 * rindle.extract(input, function(error, data) {
 *   if (error) throw error;
 *   console.log('The file contains: ' + data);
 * });
 */
exports.extract = function(stream, callback) {
  'use strict';

  var chunks = '';

  stream.on('data', function(chunk) {
    chunks += chunk;
  });

  return exports.wait(stream).then(function() {
    return chunks;
  }).nodeify(callback);
};

/**
 * @summary Bifurcate readable stream to two writable streams
 * @function
 * @public
 *
 * @description
 * The callback is called when both output stream close.
 *
 * @param {StreamReadable} stream - input stream
 * @param {StreamWritable} output1 - first output stream
 * @param {StreamWritable} output2 - second output stream
 * @param {Function} callback - callback (error)
 *
 * @example
 *
 * var fs = require('fs');
 * var rindle = require('rindle');
 *
 * var input = fs.createReadStream('foo/bar');
 * var output1 = fs.createWriteStream('foo/baz');
 * var output2 = fs.createWriteStream('foo/qux');
 *
 * rindle.bifurcate(input, output1, output2, function(error) {
 *   if (error) throw error;
 *
 *   console.log('All files written!');
 * });
 */
exports.bifurcate = function(stream, output1, output2, callback) {
  'use strict';

  stream.pipe(output1);
  stream.pipe(output2);

  // Fulfil once we finish writing to both output streams
  return Promise.all([
    exports.wait(output1),
    exports.wait(output2)
  ]).nodeify(callback);
};

/**
 * @summary Pipe a stream along with certain events
 * @function
 * @public
 *
 * @param {StreamReadable} stream - input stream
 * @param {StreamWritable} output - output stream
 * @param {String[]} events - events to pipe
 *
 * @returns {StreamReadable} resulting stream
 *
 * @example
 * var rindle = require('rindle');
 *
 * rindle.pipeWithEvents(input, output, [
 *   'response',
 *   'request'
 * ]);
 */
exports.pipeWithEvents = function(stream, output, events) {
  'use strict';

  each(events, function(event) {
    stream.on(event, function() {
      var args = Array.prototype.slice.call(arguments);
      args.unshift(event);
      output.emit.apply(output, args);
    });
  });

  return stream.pipe(output);
};

/**
 * @summary Wait for a stream to emit a certain event
 * @function
 * @public
 *
 * @param {Stream} stream - stream
 * @param {String} event - event name
 * @param {Function} callback - callback (error, args...)
 *
 * @example
 * var rindle = require('rindle');
 * var fs = require('fs');
 *
 * rindle.onEvent(fs.createReadStream('foo/bar'), 'open', function(error, fd) {
 *   if (error) throw error;
 *
 *   console.log('The "open" event was emitted');
 *   console.log(fd);
 * });
 */
exports.onEvent = function(stream, event, callback) {
  'use strict';

  return new Promise(function(resolve) {
    stream.on(event, function() {
      var args = Array.prototype.slice.call(arguments);

      if (isEmpty(args)) {
        args = undefined;
      }
      else if (args.length === 1) {
        args = head(args);
      }

      return resolve(args);
    });
  }).nodeify(callback, {
    spread: true
  });
};

/**
 * @summary Get a readable stream from a string
 * @function
 * @public
 *
 * @param {String} string - input string
 * @returns {ReadableStream} - string stream
 *
 * @example
 * var rindle = require('rindle');
 * rindle.getStreamFromString('Hello World!').pipe(process.stdout);
 */
exports.getStreamFromString = function(string) {
  'use strict';

  if (!isString(string)) {
    throw new Error('Not a string: ' + string);
  }

  return stringToStream(string);
};
<|endoftext|>


<commit_before>/* globals state, createObj, findObjs, getObj, getAttrByName, sendChat, on, log, Campaign, playerIsGM, spawnFx,
 spawnFxBetweenPoints, filterObjs, randomInteger, setDefaultTokenForCharacter, onSheetWorkerCompleted */
'use strict';
const _ = require('underscore');

// noinspection JSUnusedLocalSymbols
module.exports = class Roll20Wrapper {

  getState(module) {
    if (!state[module]) {
      state[module] = {};
    }
    return state[module];
  }

  createObj(type, attributes) {
    return createObj(type, attributes);
  }

  findObjs(attributes, options) {
    return findObjs(attributes, options);
  }

  filterObjs(attributes) {
    return filterObjs(attributes);
  }

  getObj(type, id) {
    return getObj(type, id);
  }

  getOrCreateObj(type, attributes) {
    const newAttributes = _.extend(_.clone(attributes), { type });
    const existing = this.findObjs(newAttributes);
    switch (existing.length) {
      case 0:
        return this.createObj(type, newAttributes);
      case 1:
        return existing[0];
      default:
        throw new Error(`Asked for a single ${type} but more than 1 was found matching attributes: ` +
          `${JSON.stringify(attributes)}`);
    }
  }

  getAttrByName(character, attrName, valueType) {
    return getAttrByName(character, attrName, valueType);
  }

  checkCharacterFlag(character, flag) {
    const value = this.getAttrByName(character, flag);
    switch (typeof value) {
      case 'boolean':
        return value;
      case 'number':
        return !!value;
      default:
        return value === '1' || value === 'on';
    }
  }

  getAttrObjectByName(character, attrName) {
    const attr = this.findObjs({ type: 'attribute', characterid: character, name: attrName },
      { caseInsensitive: true });
    return attr && attr.length > 0 ? attr[0] : null;
  }

  getOrCreateAttr(characterId, attrName) {
    return this.getOrCreateObj('attribute', { characterid: characterId, name: attrName });
  }

  setAttrByName(characterId, attrName, value) {
    this.getOrCreateAttr(characterId, attrName).set('current', value);
  }

  processAttrValue(characterId, attrName, cb) {
    const attribute = this.getOrCreateAttr(characterId, attrName);
    const newVal = cb(attribute.get('current'));
    attribute.set('current', newVal);
    return newVal;
  }

  getRepeatingSectionAttrs(characterId, sectionName) {
    const prefix = `repeating_${sectionName}`;
    return _.filter(this.findObjs({ type: 'attribute', characterid: characterId }),
      attr => attr.get('name').indexOf(prefix) === 0);
  }

  getRepeatingSectionItemIdsByName(characterId, sectionName) {
    const re = new RegExp(`repeating_${sectionName}_([^_]+)_name$`);
    return _.reduce(this.getRepeatingSectionAttrs(characterId, sectionName),
      (lookup, attr) => {
        const match = attr.get('name').match(re);
        if (match) {
          lookup[attr.get('current').toLowerCase()] = match[1];
        }
        return lookup;
      }, {});
  }

  getCurrentPage(playerId) {
    let pageId;
    if (this.playerIsGM(playerId)) {
      pageId = this.getObj('player', playerId).get('lastpage');
    }
    else {
      pageId = this.getCampaign().get('playerspecificpages')[playerId] || this.getCampaign().get('playerpageid');
    }

    return pageId ? this.getObj('page', pageId) : null;
  }

  spawnFx(pointsArray, fxType, pageId) {
    switch (pointsArray.length) {
      case 1:
        spawnFx(pointsArray[0].x, pointsArray[0].y, fxType, pageId);
        break;
      case 2:
        spawnFxBetweenPoints(pointsArray[0], pointsArray[1], fxType, pageId);
        break;
      default:
        throw new Error('Wrong number of points supplied to spawnFx: $$$', pointsArray);
    }
  }

  playerIsGM(playerId) {
    return playerIsGM(playerId);
  }

  getCampaign() {
    return Campaign(); // eslint-disable-line
  }

  sendChat(sendAs, message, callback, options) {
    return sendChat(sendAs, message, callback, options);
  }

  on(event, callback) {
    return on(event, callback);
  }

  randomInteger(max) {
    return randomInteger(max);
  }

  log(msg) {
    return log(msg);
  }

  setDefaultTokenForCharacter(character, token) {
    return setDefaultTokenForCharacter(character, token);
  }

  onSheetWorkerCompleted(cb) {
    onSheetWorkerCompleted(cb);
  }

  setAttrWithWorker(character, attrName, attrValue, cb) {
    const attr = this.getOrCreateAttr(character, attrName);
    if (cb) {
      onSheetWorkerCompleted(cb);
    }
    attr.setWithWorker({ current: attrValue });
  }

  createAttrWithWorker(character, attrName, attrValue, cb) {
    const attr = this.createObj('attribute', { characterid: character, name: attrName });
    if (cb) {
      onSheetWorkerCompleted(cb);
    }
    attr.setWithWorker({ current: attrValue });
  }
};

<commit_msg>Add better debug information for duplicate attribute problem<commit_after>/* globals state, createObj, findObjs, getObj, getAttrByName, sendChat, on, log, Campaign, playerIsGM, spawnFx,
 spawnFxBetweenPoints, filterObjs, randomInteger, setDefaultTokenForCharacter, onSheetWorkerCompleted */
'use strict';
const _ = require('underscore');

// noinspection JSUnusedLocalSymbols
module.exports = class Roll20Wrapper {

  getState(module) {
    if (!state[module]) {
      state[module] = {};
    }
    return state[module];
  }

  createObj(type, attributes) {
    return createObj(type, attributes);
  }

  findObjs(attributes, options) {
    return findObjs(attributes, options);
  }

  filterObjs(attributes) {
    return filterObjs(attributes);
  }

  getObj(type, id) {
    return getObj(type, id);
  }

  getOrCreateObj(type, attributes) {
    const newAttributes = _.extend(_.clone(attributes), { type });
    const existing = this.findObjs(newAttributes);
    switch (existing.length) {
      case 0:
        return this.createObj(type, newAttributes);
      case 1:
        return existing[0];
      default:
        throw new Error(`Asked for a single ${type} but more than 1 was found matching attributes: ` +
          `${JSON.stringify(attributes)}. Found attributes: ${JSON.stringify(existing)}`);
    }
  }

  getAttrByName(character, attrName, valueType) {
    return getAttrByName(character, attrName, valueType);
  }

  checkCharacterFlag(character, flag) {
    const value = this.getAttrByName(character, flag);
    switch (typeof value) {
      case 'boolean':
        return value;
      case 'number':
        return !!value;
      default:
        return value === '1' || value === 'on';
    }
  }

  getAttrObjectByName(character, attrName) {
    const attr = this.findObjs({ type: 'attribute', characterid: character, name: attrName },
      { caseInsensitive: true });
    return attr && attr.length > 0 ? attr[0] : null;
  }

  getOrCreateAttr(characterId, attrName) {
    return this.getOrCreateObj('attribute', { characterid: characterId, name: attrName });
  }

  setAttrByName(characterId, attrName, value) {
    this.getOrCreateAttr(characterId, attrName).set('current', value);
  }

  processAttrValue(characterId, attrName, cb) {
    const attribute = this.getOrCreateAttr(characterId, attrName);
    const newVal = cb(attribute.get('current'));
    attribute.set('current', newVal);
    return newVal;
  }

  getRepeatingSectionAttrs(characterId, sectionName) {
    const prefix = `repeating_${sectionName}`;
    return _.filter(this.findObjs({ type: 'attribute', characterid: characterId }),
      attr => attr.get('name').indexOf(prefix) === 0);
  }

  getRepeatingSectionItemIdsByName(characterId, sectionName) {
    const re = new RegExp(`repeating_${sectionName}_([^_]+)_name$`);
    return _.reduce(this.getRepeatingSectionAttrs(characterId, sectionName),
      (lookup, attr) => {
        const match = attr.get('name').match(re);
        if (match) {
          lookup[attr.get('current').toLowerCase()] = match[1];
        }
        return lookup;
      }, {});
  }

  getCurrentPage(playerId) {
    let pageId;
    if (this.playerIsGM(playerId)) {
      pageId = this.getObj('player', playerId).get('lastpage');
    }
    else {
      pageId = this.getCampaign().get('playerspecificpages')[playerId] || this.getCampaign().get('playerpageid');
    }

    return pageId ? this.getObj('page', pageId) : null;
  }

  spawnFx(pointsArray, fxType, pageId) {
    switch (pointsArray.length) {
      case 1:
        spawnFx(pointsArray[0].x, pointsArray[0].y, fxType, pageId);
        break;
      case 2:
        spawnFxBetweenPoints(pointsArray[0], pointsArray[1], fxType, pageId);
        break;
      default:
        throw new Error('Wrong number of points supplied to spawnFx: $$$', pointsArray);
    }
  }

  playerIsGM(playerId) {
    return playerIsGM(playerId);
  }

  getCampaign() {
    return Campaign(); // eslint-disable-line
  }

  sendChat(sendAs, message, callback, options) {
    return sendChat(sendAs, message, callback, options);
  }

  on(event, callback) {
    return on(event, callback);
  }

  randomInteger(max) {
    return randomInteger(max);
  }

  log(msg) {
    return log(msg);
  }

  setDefaultTokenForCharacter(character, token) {
    return setDefaultTokenForCharacter(character, token);
  }

  onSheetWorkerCompleted(cb) {
    onSheetWorkerCompleted(cb);
  }

  setAttrWithWorker(character, attrName, attrValue, cb) {
    const attr = this.getOrCreateAttr(character, attrName);
    if (cb) {
      onSheetWorkerCompleted(cb);
    }
    attr.setWithWorker({ current: attrValue });
  }

  createAttrWithWorker(character, attrName, attrValue, cb) {
    const attr = this.createObj('attribute', { characterid: character, name: attrName });
    if (cb) {
      onSheetWorkerCompleted(cb);
    }
    attr.setWithWorker({ current: attrValue });
  }
};

<|endoftext|>


<commit_before>'use strict';

var express = require('express'),
    linz = require('../'),
    routes = require('../routes'),
    middleware = require('../middleware'),
    params = require('../params'),
    router;

exports.getRouter = function () {

    if (router === undefined) {
        router = express.Router();
    }

    return router;

};

exports.setupParams = function () {

    Object.keys(params).forEach(function (param) {
        params[param](router);
    });

};

exports.setupAdminRoutes = function () {

    // map forgotten password
    router.get(linz.get('admin forgot password path'), routes.forgottenPassword.get);
    router.post(linz.get('admin forgot password path'), middleware.forgottenPassword.post, routes.forgottenPassword.post);

    // map password reset
    router.get(linz.get('admin password reset path') + '/:id/:hash', publicMiddleware.namespace, middleware.passwordReset.get, routes.passwordReset.get);
    router.post(linz.get('admin password reset path'), middleware.passwordReset.post, routes.passwordReset.post);

    router.get('*', publicMiddleware.namespace, linz.middleware.exclusions(middleware.adminEnsureAuthenticated(), middleware.navigation, middleware.attributes), publicMiddleware.notifications);
    router.post('*', publicMiddleware.namespace, linz.middleware.exclusions(middleware.adminEnsureAuthenticated(), middleware.navigation, middleware.attributes));
    router.get('/', routes.adminHome);
    router.get('/login', linz.get('login middleware').get);
    router.post('/login', linz.get('login middleware').post);
    router.get('/logout', linz.get('logout middleware').get);

};

exports.setupModelRoutes = function () {

    router.use('/model/:model', linz.api.middleware.setLinzModel());

    // model routes
    router.get('/models/list', middleware.permissions('canList', 'models'), routes.modelList);
    router.get('/model/:model/list', middleware.namespaceList, middleware.permissions('canList', 'model'), middleware.modelIndex.get, routes.modelIndex);
    router.post('/model/:model/list', middleware.namespaceList, middleware.permissions('canList', 'model'), middleware.modelIndex.post, routes.modelIndex);
    router.get('/model/:model/new', middleware.permissions('canCreate', 'model'), routes.modelCreate);
    router.post('/model/:model/create', middleware.permissions('canCreate', 'model'), linz.api.middleware.setModelForm(), routes.modelSave);
    router.get('/model/:model/export', middleware.permissions('canExport', 'model'), middleware.modelExport.get, routes.modelExport.get);
    router.post('/model/:model/export', middleware.permissions('canExport', 'model'), middleware.modelExport.post);

    // record routes
    router.get('/model/:model/:id/overview', middleware.namespaceOverview, middleware.permissions('canView', 'model'), middleware.recordOverview(), routes.recordOverview);
    router.get('/model/:model/:id/edit', middleware.permissions('canEdit', 'model'), middleware.recordEdit(), routes.recordEdit);
    router.post('/model/:model/:id/save', middleware.permissions('canEdit', 'model'), linz.api.middleware.setModelForm(), linz.api.middleware.setRecord(), routes.recordSave);
    router.get('/model/:model/:id/delete', middleware.permissions('canDelete', 'model'), middleware.recordDelete(), routes.recordDelete);
    router.get('/model/:model/:id/json', middleware.permissions('canViewRaw', 'model'), routes.recordJSON);

    // custom actions for records
    router.get('/model/:model/:id/action/:action', middleware.permissions('action', 'model'));

    // version routes
    router.get('/model/:model/:id/versions-compare/:revisionAId/:revisionBId', middleware.modelVersionsCompare.get, routes.modelVersionsCompare.get);
    router.get('/model/:model/:id/versions-rollback/:revisionAId/:revisionBId', middleware.modelVersionsRollback.get, routes.modelVersionsRollback.get);
    router.post('/model/:model/:id/versions-rollback/:revisionAId/:revisionBId', middleware.modelVersionsRollback.post, routes.modelVersionsRollback.post);

    // concurrency control routes
    router.post('/model/:model/:id/change/:versionNo?', middleware.recordChange);
    router.get('/merge-data-conflict-guide', routes.mergeDataConflictGuide);

};

exports.setupConfigsRoutes = function () {

    // config routes
    router.get('/configs/list', middleware.permissions('canList', 'configs'), middleware.configList(), routes.configList);
    router.get('/config/:config/overview', middleware.permissions('canView', 'config'), middleware.configOverview(), routes.configOverview);
    router.get('/config/:config/edit', middleware.permissions('canEdit', 'config'), middleware.configEdit(), routes.configEdit);
    router.post('/config/:config/save', middleware.permissions('canEdit', 'config'), middleware.configSave(), routes.configSave);
    router.get('/config/:config/default', middleware.permissions('canReset', 'config'), middleware.configDefault(), routes.configDefault);
    router.get('/config/:config/json', middleware.permissions('canViewRaw', 'config'), routes.configJSON);

};

exports.setupLoggingRoutes = function (logPath) {

    router.get('/logs/request/list', middleware.requestLog(logPath), routes.requestLog);

};
<commit_msg>fix merge conflicts<commit_after>'use strict';

var express = require('express'),
    linz = require('../'),
    routes = require('../routes'),
    middleware = require('../middleware'),
    params = require('../params'),
    router;

exports.getRouter = function () {

    if (router === undefined) {
        router = express.Router();
    }

    return router;

};

exports.setupParams = function () {

    Object.keys(params).forEach(function (param) {
        params[param](router);
    });

};

exports.setupAdminRoutes = function () {

    // map forgotten password
    router.get(linz.get('admin forgot password path'), routes.forgottenPassword.get);
    router.post(linz.get('admin forgot password path'), middleware.forgottenPassword.post, routes.forgottenPassword.post);

    // map password reset
    router.get(linz.get('admin password reset path') + '/:id/:hash', linz.api.middleware.setLinzNamespace(), middleware.passwordReset.get, routes.passwordReset.get);
    router.post(linz.get('admin password reset path'), middleware.passwordReset.post, routes.passwordReset.post);

    router.get('*', linz.api.middleware.setLinzNamespace(), linz.middleware.exclusions(middleware.adminEnsureAuthenticated(), middleware.navigation, middleware.attributes), linz.api.middleware.notifications);
    router.post('*', linz.api.middleware.setLinzNamespace(), linz.middleware.exclusions(middleware.adminEnsureAuthenticated(), middleware.navigation, middleware.attributes));
    router.get('/', routes.adminHome);
    router.get('/login', linz.get('login middleware').get);
    router.post('/login', linz.get('login middleware').post);
    router.get('/logout', linz.get('logout middleware').get);

};

exports.setupModelRoutes = function () {

    router.use('/model/:model', linz.api.middleware.setLinzModel());

    // model routes
    router.get('/models/list', middleware.permissions('canList', 'models'), middleware.routesHook, routes.modelList);
    router.get('/model/:model/list', middleware.namespaceList, middleware.permissions('canList', 'model'), middleware.modelIndex.get, middleware.routesHook, routes.modelIndex);
    router.post('/model/:model/list', middleware.namespaceList, middleware.permissions('canList', 'model'), middleware.modelIndex.post, middleware.routesHook, routes.modelIndex);
    router.get('/model/:model/new', middleware.permissions('canCreate', 'model'), middleware.routesHook, routes.modelCreate);
    router.post('/model/:model/create', middleware.permissions('canCreate', 'model'), linz.api.middleware.setModelForm(), middleware.routesHook, routes.modelSave);
    router.get('/model/:model/export', middleware.permissions('canExport', 'model'), middleware.modelExport.get, middleware.routesHook, routes.modelExport.get);
    router.post('/model/:model/export', middleware.permissions('canExport', 'model'), middleware.routesHook, middleware.modelExport.post);

    // record routes
    router.get('/model/:model/:id/overview', middleware.namespaceOverview, middleware.permissions('canView', 'model'), middleware.recordOverview(), middleware.routesHook, routes.recordOverview);
    router.get('/model/:model/:id/edit', middleware.permissions('canEdit', 'model'), middleware.recordEdit(), middleware.routesHook, routes.recordEdit);
    router.post('/model/:model/:id/save', middleware.permissions('canEdit', 'model'), linz.api.middleware.setModelForm(), linz.api.middleware.setRecord(), middleware.routesHook, routes.recordSave);
    router.get('/model/:model/:id/delete', middleware.permissions('canDelete', 'model'), middleware.recordDelete(), middleware.routesHook, routes.recordDelete);
    router.get('/model/:model/:id/json', middleware.permissions('canViewRaw', 'model'), middleware.routesHook, routes.recordJSON);

    // custom actions for records
    router.get('/model/:model/:id/action/:action', middleware.permissions('action', 'model'), middleware.routesHook);

    // version routes
    router.get('/model/:model/:id/versions-compare/:revisionAId/:revisionBId', middleware.modelVersionsCompare.get, routes.modelVersionsCompare.get);
    router.get('/model/:model/:id/versions-rollback/:revisionAId/:revisionBId', middleware.modelVersionsRollback.get, routes.modelVersionsRollback.get);
    router.post('/model/:model/:id/versions-rollback/:revisionAId/:revisionBId', middleware.modelVersionsRollback.post, routes.modelVersionsRollback.post);

    // concurrency control routes
    router.post('/model/:model/:id/change/:versionNo?', middleware.recordChange);
    router.get('/merge-data-conflict-guide', routes.mergeDataConflictGuide);

};

exports.setupConfigsRoutes = function () {

    // config routes
    router.get('/configs/list', middleware.permissions('canList', 'configs'), middleware.configList(), middleware.routesHook, routes.configList);
    router.get('/config/:config/overview', middleware.permissions('canView', 'config'), middleware.configOverview(), middleware.routesHook, routes.configOverview);
    router.get('/config/:config/edit', middleware.permissions('canEdit', 'config'), middleware.configEdit(), middleware.routesHook, routes.configEdit);
    router.post('/config/:config/save', middleware.permissions('canEdit', 'config'), middleware.configSave(), middleware.routesHook, routes.configSave);
    router.get('/config/:config/default', middleware.permissions('canReset', 'config'), middleware.configDefault(), middleware.routesHook, routes.configDefault);
    router.get('/config/:config/json', middleware.permissions('canViewRaw', 'config'), middleware.routesHook, routes.configJSON);

};

exports.setupLoggingRoutes = function (logPath) {

    router.get('/logs/request/list', middleware.requestLog(logPath), routes.requestLog);

};
<|endoftext|>


<commit_before>publicAccessible = FlowRouter.group({});

signInRequired = FlowRouter.group({
  triggersEnter: [AccountsTemplates.ensureSignedIn]
});

signInRequired.route('/', {
  name: 'feed',
  action: () => {
    BlazeLayout.render('layout', {
      main: 'feed'
    });
    setTitle('Feed');
  }
});

signInRequired.route('/update-profile', {
  name: 'updateProfile',
  action: () => {
    BlazeLayout.render('layout', {
      main: 'updateProfile'
    });
  }
});

signInRequired.route('/users/:_id', {
  name: 'profile',
  action: () => {
    BlazeLayout.render('layout', {
      main: 'profile'
    });
    setTitle('Profile');
  }
});
<commit_msg>Add setTitle call to update profile<commit_after>publicAccessible = FlowRouter.group({});

signInRequired = FlowRouter.group({
  triggersEnter: [AccountsTemplates.ensureSignedIn]
});

signInRequired.route('/', {
  name: 'feed',
  action: () => {
    BlazeLayout.render('layout', {
      main: 'feed'
    });
    setTitle('Feed');
  }
});

signInRequired.route('/update-profile', {
  name: 'updateProfile',
  action: () => {
    BlazeLayout.render('layout', {
      main: 'updateProfile'
    });
    setTitle('Update profile');
  }
});

signInRequired.route('/users/:_id', {
  name: 'profile',
  action: () => {
    BlazeLayout.render('layout', {
      main: 'profile'
    });
    setTitle('Profile');
  }
});
<|endoftext|>


<commit_before>const bodyParser = require('body-parser');
const controller = require('./controller');

module.exports = (config) => {
  var session = require('./controller/library/session')(config);
  var cookie = require('./controller/library/cookie')(config);

  var bodyParserUrlEncodedOpts = {extended: true};

  if (config.cfg.requestSizeLimit != undefined) {
    bodyParserUrlEncodedOpts.limit = config.cfg.requestSizeLimit;
  }

  var bodyParserUrlEncoded = bodyParser.urlencoded(bodyParserUrlEncodedOpts);

  var handler = (delegate, req, res) => {
    return async (() => {
      var ctrl = controller.delegate(config, req, res, session, cookie);

      try {
        await (delegate(ctrl))
      }
      catch (err) {
        controller.handler.serverError(ctrl, req, res, config.handler.error, err);
      }
    })()
  }

  var delegates = {
    route: (method, path, delegate, replaceAll, replaceMethod, suffix, middlewares) => {
      path = replaceAll || replaceMethod || path;
      path = path + (suffix ? suffix : '');

      var params = [path];
      var fn = undefined;

      if (method == 'get') {
        fn = config.app.get;
      }
      else if (method == 'post') {
        fn = config.app.post;
        params.push(bodyParserUrlEncoded);
      }
      else if (method == 'delete') {
        fn = config.app.delete;
        params.push(bodyParserUrlEncoded);
      }
      else if (method == 'put') {
        fn = config.app.put;
        params.push(bodyParserUrlEncoded);
      }

      // Add middlewares
      if (middlewares && typeof(middlewares) === 'object') {
        params.push((req, res, next) => {
          var dp = (callback) => {
            return async(() => {
              var ctrl = controller.delegate(config, req, res, session, cookie);
              var handler = {
                controller: ctrl,
                helper: config.helper,
                model: config.model
              };

              try {
                await (callback(handler))
              }
              catch (err) {
                controller.handler.serverError(ctrl, req, res, config.handler.error, err);
              }
            })();
          };

          req.async = dp;
          res.async = dp;

          next();
        });

        middlewares.forEach((middleware) => {
          params.push(middleware);
        });
      }

      // Add action
      params.push((req, res) => {
        handler(delegate, req, res)
      });

      if (fn) {
        fn.apply(config.app, params);
      }
    }
  }

  if (config.cfg.controller) {
    var fs = require('fs');

    var traverse = (path, dirPath) => {
      try {
        if (!fs.statSync(dirPath).isDirectory()) {
          return;
        }
      } catch(_) {
        console.error('Controller path load error, ' + dirPath);
        return;
      }

      fs.readdirSync(dirPath).forEach(function(name) {
        var fullPath = dirPath + '/' + name

        if (name.startsWith('.')) { return }

        if (fs.statSync(fullPath).isDirectory()) {
          traverse(path + '/' + name, fullPath)
        }
        else {
          include(
            name != 'index.js' ? path + '/' + name.substr(0, name.lastIndexOf('.')) : path,
            fullPath
          )
        }
      })
    }

    var include = (path, filePath) => {
      if (!fs.statSync(filePath).isFile()) { return false }

      var routes = require(filePath)
      var methods = ['get', 'post', 'delete', 'put']

      methods.forEach((method) => {
        if (typeof routes[method] == 'function') {
          var replaceAll = routes.path;
          var replaceMethod = routes['_' + method];
          var suffix = routes[method + '_'];
          var middlewares = routes['_' + method + '_'];

          if (middlewares && typeof(middlewares) === 'function') {
            middlewares = [middlewares];
          }

          delegates.route(method, path, routes[method], replaceAll, replaceMethod, suffix, middlewares);
        }
      })
    }

    traverse('', config.cfg.controller)
  }

  return delegates
}
<commit_msg>add status code for error handler and handling 404 error.<commit_after>const bodyParser = require('body-parser');
const controller = require('./controller');

module.exports = (config) => {
  var session = require('./controller/library/session')(config);
  var cookie = require('./controller/library/cookie')(config);

  var bodyParserUrlEncodedOpts = {extended: true};

  if (config.cfg.requestSizeLimit != undefined) {
    bodyParserUrlEncodedOpts.limit = config.cfg.requestSizeLimit;
  }

  var bodyParserUrlEncoded = bodyParser.urlencoded(bodyParserUrlEncodedOpts);

  var handler = (delegate, req, res) => {
    return async (() => {
      var ctrl = controller.delegate(config, req, res, session, cookie);

      try {
        await (delegate(ctrl))
      }
      catch (err) {
        controller.handler.serverError(ctrl, req, res, config.handler.error, err);
      }
    })()
  }

  var delegates = {
    route: (method, path, delegate, replaceAll, replaceMethod, suffix, middlewares) => {
      path = replaceAll || replaceMethod || path;
      path = path + (suffix ? suffix : '');

      var params = [path];
      var fn = undefined;

      if (method == 'get') {
        fn = config.app.get;
      }
      else if (method == 'post') {
        fn = config.app.post;
        params.push(bodyParserUrlEncoded);
      }
      else if (method == 'delete') {
        fn = config.app.delete;
        params.push(bodyParserUrlEncoded);
      }
      else if (method == 'put') {
        fn = config.app.put;
        params.push(bodyParserUrlEncoded);
      }

      // Add middlewares
      if (middlewares && typeof(middlewares) === 'object') {
        params.push((req, res, next) => {
          var dp = (callback) => {
            return async(() => {
              var ctrl = controller.delegate(config, req, res, session, cookie);
              var handler = {
                controller: ctrl,
                helper: config.helper,
                model: config.model
              };

              try {
                await (callback(handler))
              }
              catch (err) {
                controller.handler.serverError(ctrl, req, res, config.handler.error, err, 500);
              }
            })();
          };

          req.async = dp;
          res.async = dp;

          next();
        });

        middlewares.forEach((middleware) => {
          params.push(middleware);
        });
      }

      // Add action
      params.push((req, res, next) => {
        handler(delegate, req, res, next)
      });

      if (fn) {
        fn.apply(config.app, params);
      }
    }
  }

  if (config.cfg.controller) {
    var fs = require('fs');

    var traverse = (path, dirPath) => {
      try {
        if (!fs.statSync(dirPath).isDirectory()) {
          return;
        }
      } catch(_) {
        console.error('Controller path load error, ' + dirPath);
        return;
      }

      fs.readdirSync(dirPath).forEach(function(name) {
        var fullPath = dirPath + '/' + name

        if (name.startsWith('.')) { return }

        if (fs.statSync(fullPath).isDirectory()) {
          traverse(path + '/' + name, fullPath)
        }
        else {
          include(
            name != 'index.js' ? path + '/' + name.substr(0, name.lastIndexOf('.')) : path,
            fullPath
          )
        }
      })
    }

    var include = (path, filePath) => {
      if (!fs.statSync(filePath).isFile()) { return false }

      var routes = require(filePath)
      var methods = ['get', 'post', 'delete', 'put']

      methods.forEach((method) => {
        if (typeof routes[method] == 'function') {
          var replaceAll = routes.path;
          var replaceMethod = routes['_' + method];
          var suffix = routes[method + '_'];
          var middlewares = routes['_' + method + '_'];

          if (middlewares && typeof(middlewares) === 'function') {
            middlewares = [middlewares];
          }

          delegates.route(method, path, routes[method], replaceAll, replaceMethod, suffix, middlewares);
        }
      })
    }

    traverse('', config.cfg.controller)

    config.app.use((req, res, next) => {
      var ctrl = controller.delegate(config, req, res, session, cookie);
      controller.handler.serverError(ctrl, req, res, config.handler.error, null, 404);
    });
  }

  return delegates
}
<|endoftext|>


<commit_before>module.exports = router;

var events = require('events'),
    methods = require('methods'),
    pathRegexp = require('path-to-regexp');

function router() {
  var app = handler,
      stack = [],
      emitter = new events.EventEmitter();

  for (var prop in emitter) {
    propProxy(handler, emitter, prop);
  }

  //NOTE: pending https://github.com/tessel/runtime/issues/487
  if (process.platform === 'tessel') {
    ['emit', 'on', 'once'].forEach(function (prop) {
      propProxy(handler, emitter, prop);
    });
  }

  function propProxy(target, source, prop) {
    target[prop] = function () {
      return source[prop].apply(source, arguments);
    };
  }

  app.on('mount', function (parent, path) {
    app.mountpath = path;
    console.log('mounted at', path);
  });
  });

  function handler(req, res, done) {
    // console.log('incoming request', req.url);

    //FIXME: done === undefined ? req.url : req.path is a bit hackish...
    var routes = stack.filter(function (route) {
      var match;

      if (req.method.toLowerCase() === route.method) {
        match = route.path.exec(done === undefined ? req.url : req.path);

        if (match) {
          if (route.path.keys.length) {
            req.params = {};

            route.path.keys.forEach(function (key, index) {
              req.params[key.name] = match[index + 1];
            });
          }
          return true;
        }
      }

      if (route.method === null) {
        if (route.callback.mountpath === req.url && req.url[req.url.length - 1] !== '/') {
          req.url = req.url + '/';
        }
        match = route.path.exec(done === undefined ? req.url : req.path);
        // console.log('*** next route is router', !!route.callback.use);
        // console.log('in app', done === undefined, match);
        // console.log('match use', route.path, req.url, req.path);
        // console.log('mounted router', route.callback.mountpath);

        if (match) {
          if (route.callback.mountpath) {
            req.path = match[1] ? match[1] : '/';
          }
          return true;
        }
      }
    });

    if (routes.length === 0) {
      notFound(req, res);
    } else {
      var index = 0;

      routes[0].callback(req, res, next);
    }

    function next(err) {
      if (err) {
        if (done === undefined) {
          return res.status(500).send(err).end();
        } else {
          return done(err);
        }
      }

      if (index === routes.length) {
        return done && done();
      } else {
        index++;
        if (routes[index] === undefined) {
          notFound(req, res);
        } else {
          routes[index].callback(req, res, next);
        }
      }
    }
  }

  function notFound(req, res) {
    res.status(404).end('Not Found');
  }

  function addRoute(method, path, callback) {
    // console.log('>>> path', path);
    stack.push({
      path: pathRegexp(path),
      callback: callback,
      method: method
    });
  }

  methods.forEach(function (method) {
    app[method] = function(path, callback) {
      addRoute(method, path, callback);
    };
  });

  app.all = function all(path, callback) {
    methods.forEach(function (method) {
      addRoute(method, path, callback);
    });
  };

  app.use = function use() {
    var path, fn;

    switch (arguments.length) {
    case 1: // middleware
      if (typeof arguments[0] === 'function') {
        // path = '/';
        fn = arguments[0];

        stack.push({
          path: new RegExp('.*'),
          callback: fn,
          method: null
        });
      }
      break;
    case 2: // router
      if (typeof arguments[0] === 'string' && typeof arguments[1] === 'function') {
        path = arguments[0];
        fn = arguments[1];
      }

      stack.push({
        // path: new RegExp('^\\' + path + '(\\/.*)(?=\\/|$)'),
        path: new RegExp('^\\' + path + '(\\/.*)'),
        callback: fn,
        method: null
      });

      // fn.mountpath = path;
      fn.emit('mount', app, path);
      break;
    default:

    }

    return this;
  };

  return app;
}
<commit_msg>Update router.js<commit_after>module.exports = router;

var events = require('events'),
    methods = require('methods'),
    pathRegexp = require('path-to-regexp');

function router() {
  var app = handler,
      stack = [],
      emitter = new events.EventEmitter();

  for (var prop in emitter) {
    propProxy(handler, emitter, prop);
  }

  //NOTE: pending https://github.com/tessel/runtime/issues/487
  if (process.platform === 'tessel') {
    ['emit', 'on', 'once'].forEach(function (prop) {
      propProxy(handler, emitter, prop);
    });
  }

  function propProxy(target, source, prop) {
    target[prop] = function () {
      return source[prop].apply(source, arguments);
    };
  }

  app.on('mount', function (parent, path) {
    app.mountpath = path;
    console.log('mounted at', path);
  });

  function handler(req, res, done) {
    // console.log('incoming request', req.url);

    //FIXME: done === undefined ? req.url : req.path is a bit hackish...
    var routes = stack.filter(function (route) {
      var match;

      if (req.method.toLowerCase() === route.method) {
        match = route.path.exec(done === undefined ? req.url : req.path);

        if (match) {
          if (route.path.keys.length) {
            req.params = {};

            route.path.keys.forEach(function (key, index) {
              req.params[key.name] = match[index + 1];
            });
          }
          return true;
        }
      }

      if (route.method === null) {
        if (route.callback.mountpath === req.url && req.url[req.url.length - 1] !== '/') {
          req.url = req.url + '/';
        }
        match = route.path.exec(done === undefined ? req.url : req.path);
        // console.log('*** next route is router', !!route.callback.use);
        // console.log('in app', done === undefined, match);
        // console.log('match use', route.path, req.url, req.path);
        // console.log('mounted router', route.callback.mountpath);

        if (match) {
          if (route.callback.mountpath) {
            req.path = match[1] ? match[1] : '/';
          }
          return true;
        }
      }
    });

    if (routes.length === 0) {
      notFound(req, res);
    } else {
      var index = 0;

      routes[0].callback(req, res, next);
    }

    function next(err) {
      if (err) {
        if (done === undefined) {
          return res.status(500).send(err).end();
        } else {
          return done(err);
        }
      }

      if (index === routes.length) {
        return done && done();
      } else {
        index++;
        if (routes[index] === undefined) {
          notFound(req, res);
        } else {
          routes[index].callback(req, res, next);
        }
      }
    }
  }

  function notFound(req, res) {
    res.status(404).end('Not Found');
  }

  function addRoute(method, path, callback) {
    // console.log('>>> path', path);
    stack.push({
      path: pathRegexp(path),
      callback: callback,
      method: method
    });
  }

  methods.forEach(function (method) {
    app[method] = function(path, callback) {
      addRoute(method, path, callback);
    };
  });

  app.all = function all(path, callback) {
    methods.forEach(function (method) {
      addRoute(method, path, callback);
    });
  };

  app.use = function use() {
    var path, fn;

    switch (arguments.length) {
    case 1: // middleware
      if (typeof arguments[0] === 'function') {
        // path = '/';
        fn = arguments[0];

        stack.push({
          path: new RegExp('.*'),
          callback: fn,
          method: null
        });
      }
      break;
    case 2: // router
      if (typeof arguments[0] === 'string' && typeof arguments[1] === 'function') {
        path = arguments[0];
        fn = arguments[1];
      }

      stack.push({
        // path: new RegExp('^\\' + path + '(\\/.*)(?=\\/|$)'),
        path: new RegExp('^\\' + path + '(\\/.*)'),
        callback: fn,
        method: null
      });

      // fn.mountpath = path;
      fn.emit('mount', app, path);
      break;
    default:

    }

    return this;
  };

  return app;
}
<|endoftext|>


<commit_before>var path = require("path");
var config = require("./data/config.json");
var debug = require("./debug");

var BASE_DIR = path.join(__dirname + "/../../../");
var PUBLIC_DIR = BASE_DIR + "public/";
var ROUTER_DIR = BASE_DIR + "router/";
var TEMP_VIEW_DIR = path.join(__dirname + "");

var options = {
    root: PUBLIC_DIR,
    dotfiles: 'deny',
    headers: {
        'x-timestamp': Date.now(),
        'x-sent': true
    }
}

function processRoute(req, res) {

    // Cache the file
    var file = req.path.substring(1, req.path.indexOf(".html"));

    // Try getting the router module
    var route = require(ROUTER_DIR + file + ".js");

    // Run the router module
    route(req, res, function (data) {

        // And run the renderer
        res.render(file, data, function (err, html) {

            // Check if there's renderer error
            if (err) {

                // The renderer has error
                debug.log("Render Error: \n" + err);
                res.error(500, "Internal Server Error");
            }
            else {

                // Send the rendered html
                debug.log(file + ".html successfully rendered");
                res.send(html);
            }
        });
    });
}

function sendStaticHtml(req, res) {

    // Cache the file
    var file = req.path.substring(1, req.path.indexOf(".html"));

    // Try sending the static html
    res.render(file, {}, function (err, html) {

        // Check if there's an error rendering the static file
        if (err) {

            //
            debug.log("Static html not found. Redirecting to 404");

            // Avoid infinity redirecting
            if (file === "error") {
                res.send("
Error 404: Page not found.
");
            }
            else {
                res.error(404, "Page not found");
            }
        }
        else {

            // Directly send the rendered html
            res.send(html);
            debug.log("Directly sent static html " + file);
        }
    });
}

module.exports = {
    preprocess: function (req, res, next) {

        // Wrap error function for response
        res.error = function (code, msg) {
            res.redirect("/" + config.error_page + ".html?code=" + code + "&msg=" + msg);
        };

        // Pass to next middleware
        next();
    },
    router: function (req, res) {

        // Try to process the router
        try {
            processRoute(req, res);
        }
        catch (err) {

            // Check if the error is module not found
            if (err.code === "MODULE_NOT_FOUND") {

                // Send static html if the module not found
                sendStaticHtml(req, res);
            }
            else {

                // Then the router file might have error
                debug.log("Router " + file + " Error: \n" + err);
                res.error(500, "Internal Server Error");
            }
        }
    }
}
<commit_msg>Fixed router file reference bug<commit_after>var path = require("path");
var config = require("./data/config.json");
var debug = require("./debug");

var BASE_DIR = path.join(__dirname + "/../../../");
var PUBLIC_DIR = BASE_DIR + "public/";
var ROUTER_DIR = BASE_DIR + "router/";
var TEMP_VIEW_DIR = path.join(__dirname + "");

var options = {
    root: PUBLIC_DIR,
    dotfiles: 'deny',
    headers: {
        'x-timestamp': Date.now(),
        'x-sent': true
    }
}

function processRoute(req, res) {

    // Cache the file
    var file = req.path.substring(1, req.path.indexOf(".html"));

    // Try getting the router module
    var route = require(ROUTER_DIR + file + ".js");

    // Run the router module
    route(req, res, function (data) {

        // And run the renderer
        res.render(file, data, function (err, html) {

            // Check if there's renderer error
            if (err) {

                // The renderer has error
                debug.log("Render Error: \n" + err);
                res.error(500, "Internal Server Error");
            }
            else {

                // Send the rendered html
                debug.log(file + ".html successfully rendered");
                res.send(html);
            }
        });
    });
}

function sendStaticHtml(req, res) {

    // Cache the file
    var file = req.path.substring(1, req.path.indexOf(".html"));

    // Try sending the static html
    res.render(file, {}, function (err, html) {

        // Check if there's an error rendering the static file
        if (err) {

            //
            debug.log("Static html not found. Redirecting to 404");

            // Avoid infinity redirecting
            if (file === "error") {
                res.send("
Error 404: Page not found.
");
            }
            else {
                res.error(404, "Page not found");
            }
        }
        else {

            // Directly send the rendered html
            res.send(html);
            debug.log("Directly sent static html " + file);
        }
    });
}

module.exports = {
    preprocess: function (req, res, next) {

        // Wrap error function for response
        res.error = function (code, msg) {
            res.redirect("/" + config.error_page + ".html?code=" + code + "&msg=" + msg);
        };

        // Pass to next middleware
        next();
    },
    router: function (req, res) {

        // Cache the file
        var file = req.path.substring(1, req.path.indexOf(".html"));

        // Try to process the router
        try {
            processRoute(req, res);
        }
        catch (err) {

            // Check if the error is module not found
            if (err.code === "MODULE_NOT_FOUND") {

                // Send static html if the module not found
                sendStaticHtml(req, res);
            }
            else {

                // Then the router file might have error
                debug.log("Router " + file + " Error: \n" + err);
                res.error(500, "Internal Server Error");
            }
        }
    }
}
<|endoftext|>


<commit_before>Router.configure({
  layoutTemplate: 'layout',
  loadingTemplate: 'loading',
  onBeforeAction: function(){
    //validacoes de userId
    if((!Meteor.userId()
      && !localStorage.getItem('Meteor.emailId')
      && !localStorage.getItem('Meteor.facebookId')
      && !localStorage.getItem('Meteor.googleId'))
      || (localStorage.getItem('Meteor.facebookId') && localStorage.getItem('Meteor.googleId'))){

      if(localStorage.getItem('Meteor.facebookId') && localStorage.getItem('Meteor.googleId')){
        console.log('Êêpa.. Tentado se logar em duas contas?');
      }

      localStorage.clear();
      Router.go('authentication');
    }else if(localStorage.getItem('Meteor.userServerId') !== Meteor.userId){
      Meteor.subscribe('users');
      var userId = User.findOne(
        {
          email: localStorage.getItem('Meteor.emailId'),

            $or: [
              {facebook_id: localStorage.getItem('Meteor.facebookId')},
              {google_id: localStorage.getItem('Meteor.googleId')}
            ]

        }
      );

      if(userId !== undefined){
        localStorage.setItem('Meteor.userId', userId._id);
      }
    }
    IonNavigation.skipTransitions = true;
    this.next();
  }
});

Router.map(function() {

  // Raiz ################################### Rota primária
  this.route('index', {
    path: '/',
    onBeforeAction: function () {
      document.querySelector('body').classList.add('home-page');
      this.next();
    }
  });

  // // Autenticação
  // this.route('index.editProfile', {
  //   path: '/editar-perfil',
  //   template: '_editProfile'
  // });

  // Autenticação
  this.route('authentication', {
    path: '/login',
    onBeforeAction: function () {
      document.querySelector('body').classList.add('authentication-page');
      this.next();
    }
  });

  // Programação da TV
  this.route('notify', {
    path: '/notificacoes',
    onBeforeAction: function () {
    document.querySelector('body').classList.add('notify-page');
      this.next();
    }
  });

  // TV ################################ Lista de Programas
  this.route('television', {
    path: '/rede-meionorte/:_idTv',
    fastRender: true,
    onBeforeAction: function () {
      document.querySelector('body').classList.add('television-page');
      this.next();
    }
  });

    // Programação da TV
    this.route('programation', {
      path: '/rede-meionorte/programacao',
      onBeforeAction: function () {
      document.querySelector('body').classList.add('television-page');
        this.next();
      }
    });

    // Timeline Tv
    this.route('tabs.timelineTelevision', {
      path: '/rede-meionorte/:_id/timeline',
      layoutTemplate: 'program',
      fastRender: true
    });
    this.route('tabs.pollsTelevision', {
      path: '/rede-meionorte/:_id/enquete',
      layoutTemplate: 'program',
      fastRender: true
    });

  // Rádios ################################# Timeline Radio
  this.route('tabs.timelineRadio', {
    path: '/radio/:_id/:name/timeline',
    layoutTemplate: 'radio',
    fastRender: true,
    onBeforeAction: function () {
      document.querySelector('body').classList.add('radio-page');
      this.next();
    }
  });
  this.route('tabs.pollsRadio', {
    path: '/radio/:_id/:name/enquete',
    layoutTemplate: 'radio',
    fastRender: true,
    onBeforeAction: function () {
      document.querySelector('body').classList.add('radio-page');
      this.next();
    }
  });

  // PORTAL ################################ Home do Portal
  this.route('indexPortal', {
    path: '/portal-meionorte'
  });

  this.route('indexNewspaper', {
    path: '/jornal-meionorte'
  });

  // this.route('tabs.blogsPortal', {
  //   path: '/portal-meionorte/blogs',
  //   layoutTemplate: 'portal'
  // });

  // this.route('tabs.cityPortal', {
  //   path: '/portal-meionorte/cidades',
  //   layoutTemplate: 'portal'
  // });

  // this.route('tabs.latestPortal', {
  //   path: '/portal-meionorte/ultimas',
  //   layoutTemplate: 'portal'
  // });

  // this.route('tabs.sectionPortal', {
  //   path: '/portal-meionorte/editoria',
  //   layoutTemplate: 'portal'
  // });

  // this.route('tabs.videosPortal', {
  //   path: '/portal-meionorte/videos',
  //   layoutTemplate: 'portal'
  // });

  // this.route('tabs.photosPortal', {
  //   path: '/portal-meionorte/fotos',
  //   layoutTemplate: 'portal'
  // });

  // this.route('tabs.searchPortal', {
  //   path: '/portal-meionorte/busca',
  //   layoutTemplate: 'portal'
  // });

  // Jornal #################################### Capa Jornal
  // this.route('tabs.indexNewspaper', {
  //   path: '/jornal-meionorte/capa',
  //   layoutTemplate: 'newspaper'
  // });

  // this.route('tabs.sectionNewspaper', {
  //   path: '/jornal-meionorte/secao',
  //   layoutTemplate: 'newspaper'
  // });

  // this.route('tabs.columnsNewspaper', {
  //   path: '/jornal-meionorte/colunas',
  //   layoutTemplate: 'newspaper'
  // });

  // // Programação da TV
  // this.route('columnNewspaper', {path: '/jornal-meionorte/colunas/coluna'});

  // this.route('tabs.latestNewspaper', {
  //   path: '/jornal-meionorte/ultimas',
  //   layoutTemplate: 'newspaper'
  // });

  // this.route('tabs.searchNewspaper', {
  //   path: '/jornal-meionorte/busca',
  //   layoutTemplate: 'newspaper'
  // });

  // this.route('tabs.specialsNewspaper', {
  //   path: '/jornal-meionorte/especiais',
  //   layoutTemplate: 'newspaper'
  // });

  // this.route('tabs.photosNewspaper', {
  //   path: '/jornal-meionorte/fotos',
  //   layoutTemplate: 'newspaper'
  // });

  // this.route('tabs.videosNewspaper', {
  //   path: '/jornal-meionorte/videos',
  //   layoutTemplate: 'newspaper'
  // });

});

Meteor.startup(function () {

  if (Meteor.isClient) {
    var location = Iron.Location.get();
    if (location.queryObject.platformOverride) {
      Session.set('platformOverride', location.queryObject.platformOverride);
    }

    FastClick.attach(document.body);

    // var WebFontConfig = {
    //   google: { families: [ 'Roboto:400,300,500,700:latin' ] }
    // };
    // (function() {
    //   var wf = document.createElement('script');
    //   wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
    //   '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
    //   wf.type = 'text/javascript';
    //   wf.async = 'true';
    //   var s = document.getElementsByTagName('script')[0];
    //   s.parentNode.insertBefore(wf, s);
    // })();

  }

});
<commit_msg>router config<commit_after>Router.configure({
  layoutTemplate: 'layout',
  loadingTemplate: 'loading',
  onBeforeAction: function(){
    //valida se os dados do usuario foi salvo no local storage, senao, tera que se logar novamente
    if(!Meteor.userId()
      && !localStorage.getItem('Meteor.emailId')
      && !localStorage.getItem('Meteor.facebookId')
      && !localStorage.getItem('Meteor.googleId')){
      IonLoading.hide(); // remove o loading
      localStorage.clear(); // limpa os dados do localstorage
      Router.go('authentication'); // envia para a tela de login

    //valida se o usuario tentou se logar tando no facebook quanto no google, nao eh possivel ainda logar em duas contas ao mesmo tempo
    }else if(localStorage.getItem('Meteor.facebookId') && localStorage.getItem('Meteor.googleId')){
      toastr.info(
        "Êêpa.. Tentado se logar em duas contas?",
        '',
        {
          "positionClass": "toast-top-center",
          "tapToDismiss": true,
          "timeOut": 3000
        }
      );
      IonLoading.hide(); // remove o loading
      localStorage.clear(); // limpa os dados do localstorage
      Router.go('authentication'); // envia para a tela de login

    // verifica se o id do usuario no servidor é o mesmo do cliente, se nao for deixa os dois iguais, alterando somente o id do cliente
    }else if(localStorage.getItem('Meteor.userServerId') !== Meteor.userId){
      IonLoading.show({
        customTemplate: 'Aguarde...'
      });

      Meteor.subscribe('users');
      var userId = User.findOne(
        {
          email: localStorage.getItem('Meteor.emailId'),

            $or: [
              {facebook_id: localStorage.getItem('Meteor.facebookId')},
              {google_id: localStorage.getItem('Meteor.googleId')}
            ]

        }
      );

      if(userId !== undefined){
        localStorage.setItem('Meteor.userId', userId._id);
        IonLoading.hide(); // remove o loading
      }
    }
    IonNavigation.skipTransitions = true;
    this.next();
  }
});

Router.map(function() {

  // Raiz ################################### Rota primária
  this.route('index', {
    path: '/',
    onBeforeAction: function () {
      document.querySelector('body').classList.add('home-page');
      this.next();
    }
  });

  // // Autenticação
  // this.route('index.editProfile', {
  //   path: '/editar-perfil',
  //   template: '_editProfile'
  // });

  // Autenticação
  this.route('authentication', {
    path: '/login',
    onBeforeAction: function () {
      document.querySelector('body').classList.add('authentication-page');
      this.next();
    }
  });

  // Programação da TV
  this.route('notify', {
    path: '/notificacoes',
    onBeforeAction: function () {
    document.querySelector('body').classList.add('notify-page');
      this.next();
    }
  });

  // TV ################################ Lista de Programas
  this.route('television', {
    path: '/rede-meionorte/:_idTv',
    fastRender: true,
    onBeforeAction: function () {
      document.querySelector('body').classList.add('television-page');
      this.next();
    }
  });

    // Programação da TV
    this.route('programation', {
      path: '/rede-meionorte/programacao',
      onBeforeAction: function () {
      document.querySelector('body').classList.add('television-page');
        this.next();
      }
    });

    // Timeline Tv
    this.route('tabs.timelineTelevision', {
      path: '/rede-meionorte/:_id/timeline',
      layoutTemplate: 'program',
      fastRender: true
    });
    this.route('tabs.pollsTelevision', {
      path: '/rede-meionorte/:_id/enquete',
      layoutTemplate: 'program',
      fastRender: true
    });

  // Rádios ################################# Timeline Radio
  this.route('tabs.timelineRadio', {
    path: '/radio/:_id/:name/timeline',
    layoutTemplate: 'radio',
    fastRender: true,
    onBeforeAction: function () {
      document.querySelector('body').classList.add('radio-page');
      this.next();
    }
  });
  this.route('tabs.pollsRadio', {
    path: '/radio/:_id/:name/enquete',
    layoutTemplate: 'radio',
    fastRender: true,
    onBeforeAction: function () {
      document.querySelector('body').classList.add('radio-page');
      this.next();
    }
  });

  // PORTAL ################################ Home do Portal
  this.route('indexPortal', {
    path: '/portal-meionorte'
  });

  this.route('indexNewspaper', {
    path: '/jornal-meionorte'
  });

  // this.route('tabs.blogsPortal', {
  //   path: '/portal-meionorte/blogs',
  //   layoutTemplate: 'portal'
  // });

  // this.route('tabs.cityPortal', {
  //   path: '/portal-meionorte/cidades',
  //   layoutTemplate: 'portal'
  // });

  // this.route('tabs.latestPortal', {
  //   path: '/portal-meionorte/ultimas',
  //   layoutTemplate: 'portal'
  // });

  // this.route('tabs.sectionPortal', {
  //   path: '/portal-meionorte/editoria',
  //   layoutTemplate: 'portal'
  // });

  // this.route('tabs.videosPortal', {
  //   path: '/portal-meionorte/videos',
  //   layoutTemplate: 'portal'
  // });

  // this.route('tabs.photosPortal', {
  //   path: '/portal-meionorte/fotos',
  //   layoutTemplate: 'portal'
  // });

  // this.route('tabs.searchPortal', {
  //   path: '/portal-meionorte/busca',
  //   layoutTemplate: 'portal'
  // });

  // Jornal #################################### Capa Jornal
  // this.route('tabs.indexNewspaper', {
  //   path: '/jornal-meionorte/capa',
  //   layoutTemplate: 'newspaper'
  // });

  // this.route('tabs.sectionNewspaper', {
  //   path: '/jornal-meionorte/secao',
  //   layoutTemplate: 'newspaper'
  // });

  // this.route('tabs.columnsNewspaper', {
  //   path: '/jornal-meionorte/colunas',
  //   layoutTemplate: 'newspaper'
  // });

  // // Programação da TV
  // this.route('columnNewspaper', {path: '/jornal-meionorte/colunas/coluna'});

  // this.route('tabs.latestNewspaper', {
  //   path: '/jornal-meionorte/ultimas',
  //   layoutTemplate: 'newspaper'
  // });

  // this.route('tabs.searchNewspaper', {
  //   path: '/jornal-meionorte/busca',
  //   layoutTemplate: 'newspaper'
  // });

  // this.route('tabs.specialsNewspaper', {
  //   path: '/jornal-meionorte/especiais',
  //   layoutTemplate: 'newspaper'
  // });

  // this.route('tabs.photosNewspaper', {
  //   path: '/jornal-meionorte/fotos',
  //   layoutTemplate: 'newspaper'
  // });

  // this.route('tabs.videosNewspaper', {
  //   path: '/jornal-meionorte/videos',
  //   layoutTemplate: 'newspaper'
  // });

});

Meteor.startup(function () {

  if (Meteor.isClient) {
    var location = Iron.Location.get();
    if (location.queryObject.platformOverride) {
      Session.set('platformOverride', location.queryObject.platformOverride);
    }

    FastClick.attach(document.body);

    // var WebFontConfig = {
    //   google: { families: [ 'Roboto:400,300,500,700:latin' ] }
    // };
    // (function() {
    //   var wf = document.createElement('script');
    //   wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
    //   '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
    //   wf.type = 'text/javascript';
    //   wf.async = 'true';
    //   var s = document.getElementsByTagName('script')[0];
    //   s.parentNode.insertBefore(wf, s);
    // })();

  }

});
<|endoftext|>


<commit_before>var subscriptions = new SubsManager();

Router.configure({
	layoutTemplate: 'layout',
	loadingTemplate: 'loading',
	notFoundTemplate: 'notFound'
});

Router.route('/', {
	name: 'home',
	waitOn: function() {
		return [subscriptions.subscribe('lastGames'), subscriptions.subscribe('allUsers')];
	},
	fastRender: true
});

Router.route('/ranking', {
	name: 'ranking',
	/*waitOn: function() {
		return subscriptions.subscribe('');
	},*/
	fastRender: true
});

Router.route('/championship', {
	name: 'ChampionshipWrapper',
	/*waitOn: function() {
		return subscriptions.subscribe('');
	},*/
	fastRender: true
});

Router.route('/search', {
	name: 'search',
	/*waitOn: function() {
		return subscriptions.subscribe('');
	},*/
	fastRender: true
});

Router.route('/account', {
	name: 'accountWrapper',
	fastRender: true
});
<commit_msg>Change template for the ranking route<commit_after>var subscriptions = new SubsManager();

Router.configure({
	layoutTemplate: 'layout',
	loadingTemplate: 'loading',
	notFoundTemplate: 'notFound'
});

Router.route('/', {
	name: 'home',
	waitOn: function() {
		return [subscriptions.subscribe('lastGames'), subscriptions.subscribe('allUsers')];
	},
	fastRender: true
});

Router.route('/ranking', {
	name: 'rankingWrapper',
	/*waitOn: function() {
		return subscriptions.subscribe('');
	},*/
	fastRender: true
});

Router.route('/championship', {
	name: 'ChampionshipWrapper',
	/*waitOn: function() {
		return subscriptions.subscribe('');
	},*/
	fastRender: true
});

Router.route('/search', {
	name: 'search',
	/*waitOn: function() {
		return subscriptions.subscribe('');
	},*/
	fastRender: true
});

Router.route('/account', {
	name: 'accountWrapper',
	fastRender: true
});
<|endoftext|>


<commit_before>'use strict';

const methods = ['GET', 'POST', 'PUSH', 'PATCH', 'DELETE'];

const Router = function() {
  this.routes =
    { '404': (req, res) => writeRes(res, '404 Not Found', 'text/plain', 404) };
  methods.forEach(method => {
    this.routes[method] = {};
  });
};

Router.prototype.route = function() {
  return (req, res) => {
    const method = req.method;
    const url = req.url;
    const body = JSONparser(req);
    req.body = body;
    const endpoint = this.routes[method][url] || this.routes['404'];
    return endpoint(req, res);
  };
};

methods.forEach(method => {
  Router.prototype[method.toLowerCase()] = function(url, callback) {
    this.routes[method][url] = callback;
    return this;
  };
});

module.exports = exports = Router;

function JSONparser(req) {
  var content = '';
  req.on('data', (data) => {
    content += data.toString();
  });
  req.on('end', () => {
    var parsedContent = JSON.stringify(content);
    req.body = parsedContent;
  });
}

Router.prototype.send = function(res, message) {
  // var types = { //it'd be cool to use an object, but not really practical
  //   'json' : 'application/json',
  //   'html' : 'text/html',
  //   'plain' : 'text/plain'
  // };

  var type;
  if (typeof message == 'object') type = 'application/json' ; //probably need to parse json and send the parsed message
  else if (message.startsWith('<!DOCTYPE html>') ) type = 'text/html';
  else type = 'text/plain';
  writeRes(res, message, type);
};

// Write a message back.
// If not specified the contentType will be application/json and the
// status code will be 200
function writeRes(res, message, contentType, status) {
  contentType = contentType || 'application/json';
  status = status || 200;
  if (typeof message === 'object') message = JSON.stringify(message);
  res.writeHead(status, { 'Content-Type': contentType });
  res.end(message);
}
<commit_msg>complete merge<commit_after>'use strict';

const methods = ['GET', 'POST', 'PUSH', 'PATCH', 'DELETE'];
const fs = require('fs');

const Router = function() {
  this.routes =
    { '404': (req, res) => writeRes(res, '404 Not Found', 'text/plain', 404) };
  methods.forEach(method => {
    this.routes[method] = {};
  });
};

Router.prototype.route = function() {
  return (req, res) => {
    const method = req.method;
    const url = req.url;
    const body = jsonParser(req);
    req.body = body;
    const endpoint = this.routes[method][url] || this.routes['404'];
    return endpoint(req, res);
  };
};

// static prototype serves up files in a specified directory
Router.prototype.static = function(dir) {
  const method = 'GET';
  fs.readdir(dir, (err, data) => {
    if (err) return 'Error reading directory.';
    data.forEach((url) => {
      this.routes[method][url] = (req, res) => {
        fs.readFile(url, (err, file) => {
          if (err) return 'Error reading file.';
          res.writeHead(200, { 'Content-Type': 'text/html' });
          res.write(file);
        });
      };
    });
  });
};

methods.forEach(method => {
  Router.prototype[method.toLowerCase()] = function(url, callback) {
    this.routes[method][url] = callback;
    return this;
  };
});

module.exports = exports = Router;

function jsonParser(req) {
  var content = '';
  req.on('data', (data) => {
    content += data.toString();
  });
  req.on('end', () => {
    var parsedContent = JSON.stringify(content);
    req.body = parsedContent;
  });
}

Router.prototype.send = function(res, message) {
  // var types = { //it'd be cool to use an object, but not really practical
  //   'json' : 'application/json',
  //   'html' : 'text/html',
  //   'plain' : 'text/plain'
  // };

  var type;
  if (typeof message == 'object') type = 'application/json' ; //probably need to parse json and send the parsed message
  else if (message.startsWith('<!DOCTYPE html>') ) type = 'text/html';
  else type = 'text/plain';
  writeRes(res, message, type);
};

// Write a message back.
// If not specified the contentType will be application/json and the
// status code will be 200
function writeRes(res, message, contentType, status) {
  contentType = contentType || 'application/json';
  status = status || 200;
  if (typeof message === 'object') message = JSON.stringify(message);
  res.writeHead(status, { 'Content-Type': contentType });
  res.end(message);
}
<|endoftext|>