<commit_before>define([], function () {
    'use strict';

    function createDownload(url, folderName, fileName, monitorCompletion, imageUrl) {

        return Promise.reject();
    }

    function downloadFile(url, folderName, localItem, imageUrl) {

        var fileName = localItem.LocalPath;

        return createDownload(url, folderName, fileName, true, imageUrl);
    }

    function downloadSubtitles(url, folderName, fileName) {

        return createDownload(url, folderName, fileName, false);
    }

    function downloadImage(url, folderName, fileName) {
        return createDownload(url, folderName, fileName, false);
    }

    function resyncTransfers() {
        return Promise.resolve();
    }

    return {
        downloadFile: downloadFile,
        downloadSubtitles: downloadSubtitles,
        downloadImage: downloadImage,
        resyncTransfers: resyncTransfers
    };
});<commit_msg>sync fixes<commit_after>define([], function () {
    'use strict';

    function createDownload(url, folderName, fileName, monitorCompletion, imageUrl) {

        return Promise.reject();
    }

    function downloadFile(url, folderName, localItem, imageUrl) {

        var fileName = localItem.LocalPath;

        return createDownload(url, folderName, fileName, true, imageUrl);
    }

    function downloadSubtitles(url, folderName, fileName) {

        return createDownload(url, folderName, fileName, false);
    }

    function downloadImage(url, folderName, fileName) {
        return createDownload(url, folderName, fileName, false);
    }

    function resyncTransfers() {
        return Promise.resolve();
    }

    function getItemDownloadCount() {
        return Promise.resolve(0);
    }

    return {
        downloadFile: downloadFile,
        downloadSubtitles: downloadSubtitles,
        downloadImage: downloadImage,
        resyncTransfers: resyncTransfers,
        getItemDownloadCount: getItemDownloadCount
    };
});<|endoftext|>


<commit_before>import _ from 'lodash'
import * as ActionTypes from './actions'

const N = 64

function map2 (arrays, fn) {
  return _.map(arrays, (array, i) =>
    _.map(array, (x, j) =>
      fn(x, i, j)
    )
  )
}

// import
function makeRandomGrid () {
  return _.range(N).map(y =>
    _.range(N).map(x => ({
      density:
        Math.random() < 1 / 4 ? 3 :
        Math.random() < 1 / 3 ? 2 :
        Math.random() < 1 / 2 ? 1 : 0
    }))
  )
}

function getLocalGrid (grid, i, j) {
  let h = grid.length
  let w = grid[0].length
  let inRange = (x, y) => x >= 0 && x < w && y >= 0 && y < h
  return _.map(_.range(-1, 2), y =>
    _.map(_.range(-1, 2), x =>
      inRange(j + x, i + y) ? grid[i + y][j + x] : { density: 255 }
    )
  )
}

function ensureConservationOfMass (grid, nextGrid) {
  let [counts, nextCounts] = _.map([grid, nextGrid], g =>
    _.mapValues(_.groupBy(_.flatten(g), 'density'), dGroup => dGroup.length)
  )
  return _.eq(counts, nextCounts)
}

// function stepDebug (grid, rules) {
//   let g = _.reduce(rules, (prevGrid, rule) => {
//     let x = map2(prevGrid, (cell, i, j) => {
//       let g = getLocalGrid(prevGrid, i, j)
//       return rule(g)
//     })
//     // console.table(map2(x, cell => cell.density))
//     return x
//   }, grid)
//   if (!ensureConservationOfMass(grid, g)) {
//     console.error('mass not conserved:')
//     alert('mass not conserved')
//     console.table(map2(grid, cell => cell.density))
//     console.table(map2(g, cell => cell.density))
//   }
//   return g
// }

function step (grid, rules) {
  return _.reduce(rules, (prevGrid, rule) =>
    map2(prevGrid, (cell, i, j) => {
      let g = getLocalGrid(prevGrid, i, j)
      return rule(g)
    })
  , grid)
}

const INIT = {
  data: {
    width: N,
    height: N,
    grid: makeRandomGrid()
  }
}

import {resetMetaData, gravity, slideDisplace, slide} from './rules'
const rules = [
  resetMetaData,
  gravity(1),
  slideDisplace(1),
  slideDisplace(1, true),
  slide(1),
  slide(1, true),
  gravity(2),
  slideDisplace(2),
  slideDisplace(2, true),
  slide(2),
  slide(2, true),
  gravity(3),
  slideDisplace(3),
  slideDisplace(3, true),
  slide(3),
  slide(3, true)
]

export function data (state = INIT.data, action) {
  switch (action.type) {
    case ActionTypes.STEP:
      return {...state,
        grid: step(state.grid, rules)
      }
    default:
      return state
  }
}
<commit_msg>use for loop to improve performance of getLocalGrid<commit_after>import _ from 'lodash'
import * as ActionTypes from './actions'

const N = 64

function map2 (arrays, fn) {
  return _.map(arrays, (array, i) =>
    _.map(array, (x, j) =>
      fn(x, i, j)
    )
  )
}

// import
function makeRandomGrid () {
  return _.range(N).map(y =>
    _.range(N).map(x => ({
      density:
        Math.random() < 1 / 4 ? 3 :
        Math.random() < 1 / 3 ? 2 :
        Math.random() < 1 / 2 ? 1 : 0
    }))
  )
}

function getLocalGrid (grid, i, j) {
  let h = grid.length
  let w = grid[0].length
  let inRange = (x, y) => x >= 0 && x < w && y >= 0 && y < h
  let localGrid = []
  for (let di = -1; di <= 1; di++) {
    let row = []
    for (let dj = -1; dj <= 1; dj++) {
      row.push(inRange(j + dj, i + di) ? grid[i + di][j + dj] : { density: 255 })
    }
    localGrid.push(row)
  }
  return localGrid
}

function ensureConservationOfMass (grid, nextGrid) {
  let [counts, nextCounts] = _.map([grid, nextGrid], g =>
    _.mapValues(_.groupBy(_.flatten(g), 'density'), dGroup => dGroup.length)
  )
  return _.eq(counts, nextCounts)
}

// function stepDebug (grid, rules) {
//   let g = _.reduce(rules, (prevGrid, rule) => {
//     let x = map2(prevGrid, (cell, i, j) => {
//       let g = getLocalGrid(prevGrid, i, j)
//       return rule(g)
//     })
//     // console.table(map2(x, cell => cell.density))
//     return x
//   }, grid)
//   if (!ensureConservationOfMass(grid, g)) {
//     console.error('mass not conserved:')
//     alert('mass not conserved')
//     console.table(map2(grid, cell => cell.density))
//     console.table(map2(g, cell => cell.density))
//   }
//   return g
// }

function step (grid, rules) {
  return _.reduce(rules, (prevGrid, rule) =>
    map2(prevGrid, (cell, i, j) => {
      let g = getLocalGrid(prevGrid, i, j)
      return rule(g)
    })
  , grid)
}

const INIT = {
  data: {
    width: N,
    height: N,
    grid: makeRandomGrid()
  }
}

import {resetMetaData, gravity, slideDisplace, slide} from './rules'
const rules = [
  resetMetaData,
  gravity(1),
  slideDisplace(1),
  slideDisplace(1, true),
  slide(1),
  slide(1, true),
  gravity(2),
  slideDisplace(2),
  slideDisplace(2, true),
  slide(2),
  slide(2, true),
  gravity(3),
  slideDisplace(3),
  slideDisplace(3, true),
  slide(3),
  slide(3, true)
]

export function data (state = INIT.data, action) {
  switch (action.type) {
    case ActionTypes.STEP:
      return {...state,
        grid: step(state.grid, rules)
      }
    default:
      return state
  }
}
<|endoftext|>


<commit_before>import {CHANGE_SQUARE_COLOR} from './actions'

const initialNumOfRows = 8
const initialNumOfColumns = 8

const initialState = {
  numOfRows: initialNumOfRows,
  numOfColumns: initialNumOfColumns,
  canvas: createCanvas(initialNumOfRows, initialNumOfColumns)
}

function picaApp(state = initialState, action) {
  switch (action.type) {
    case CHANGE_SQUARE_COLOR:
      let newCanvas = JSON.parse(JSON.stringify(state.canvas))
      newCanvas[action.cordinate[0]][action.cordinate[1]] = action.color
      let newState = Object.assign({}, state)
      newState.canvas = newCanvas
      return Object.assign({}, state, newState)
    default:
      return state
  }
}

function createCanvas(numOfRows, numOfColumns) {
  let canvas = new Array(numOfRows)
  for (var i=0; i < numOfRows; i++) {
    canvas[i] = new Array(numOfColumns).fill('blank')
  }
  return canvas
}

export default picaApp
<commit_msg>remove unnecessary variable and its assignment in reducer<commit_after>import {CHANGE_SQUARE_COLOR} from './actions'

const initialNumOfRows = 8
const initialNumOfColumns = 8

const initialState = {
  numOfRows: initialNumOfRows,
  numOfColumns: initialNumOfColumns,
  canvas: createCanvas(initialNumOfRows, initialNumOfColumns)
}

function picaApp(state = initialState, action) {
  switch (action.type) {
    case CHANGE_SQUARE_COLOR:
      let newCanvas = JSON.parse(JSON.stringify(state.canvas))
      newCanvas[action.cordinate[0]][action.cordinate[1]] = action.color
      return Object.assign({}, state, {canvas: newCanvas})
    default:
      return state
  }
}

function createCanvas(numOfRows, numOfColumns) {
  let canvas = new Array(numOfRows)
  for (var i=0; i < numOfRows; i++) {
    canvas[i] = new Array(numOfColumns).fill('blank')
  }
  return canvas
}

export default picaApp
<|endoftext|>


<commit_before>"use strict";

// old /upcomingLectures is now /lectures/upcoming !!!
// old /lecturesForGroups is now /lectures/groups !!!

// import the express router
var router = require("express").Router();

var moment = require("moment");

// create model
var Lecture = require("../models/model_lecture");

// on routes that end in /lectures
router.route("/")

    // get all lectures (GET /$apiBaseUrl/lectures)
    .get(function(req, res) {
        Lecture.find({}).sort({startTime: 1}).limit(100).exec(function(err, lectures) {
            if (err) { res.status(500).send(err); }
            res.status(200).json(lectures);
            res.end();
        });
    });

// on routes that end in /lectures/upcoming
router.route("/upcoming")

    // get upcoming lectures (GET /$apiBaseUrl/lectures/upcoming)
    .get(function(req, res) {

        // today at 0:00
        var today = new Date();
        today.setHours(0,0,0,0);

        // show all lectures for current day and later
        Lecture.find({"endTime": {"$gte": today}}).sort({startTime: 1}).limit(100).exec(function(err, lectures) {
            if (err) { res.status(500).send(err); }
            res.status(200).json(lectures);
            res.end();
        });
    });

// on routes that end in /lectures/groups
router.route("/groups")

    // get lectures for specific groups (POST /$apiBaseUrl/lectures/groups)
    .post(function(req, res) {

        // today at 0:00
        var today = new Date();
        today.setHours(0,0,0,0);

        var reqGroups = JSON.parse(req.body.groups || "[]");
        var query = { groups: { $in: reqGroups }, "endTime": {"$gte": today}};

        // if no reqGroups provided, return all lectures
        if (reqGroups.length === 0) {
            delete query.groups;
        }

        // check if we got a proper array
        if (reqGroups) {
            Lecture.find(query).sort({startTime: 1}).limit(100).exec(function(err, lectures) {
                if (err) { res.status(500).send(err + " - data was: " + reqGroups);  }
                res.status(200).json(lectures);
                res.end();
            });
        } else {
            res.status(400).json({ error: "ohh that query looks wrong to me: " + reqGroups });
            return;
        }
    });

// on routes that end in /lectures/weekly
router.route("/weekly")

    // get lectures for specific groups (POST /$apiBaseUrl/lectures/groups)
    .post(function(req, res) {

        var mon = moment().day(1);
        mon.hour(0);
        mon.minute(0);
        mon.seconds(0);
        var sun = moment().day(7);
        sun.hour(23);
        sun.minute(59);
        sun.seconds(59);

        var reqGroups = JSON.parse(req.body.groups || "[]");
        var query = { groups: { $in: reqGroups }, "startTime": {"$gte": mon}, "endTime": {"$lte": sun}};

        // if no reqGroups provided, return all lectures
        if (reqGroups.length === 0) {
            delete query.groups;
        }

        // check if we got a proper array
        if (reqGroups) {
            Lecture.find(query).sort({startTime: 1}).limit(100).exec(function(err, lectures) {
                if (err) { res.status(500).send(err + " - data was: " + reqGroups);  }
                res.status(200).json(lectures);
                res.end();
            });
        } else {
            res.status(400).json({ error: "ohh that query looks wrong to me: " + reqGroups });
            return;
        }
    });

// on routes that end in /lectures/:lecture_id
router.route("/:lecture_id")

    // get lecture with that id (GET /$apiBaseUrl/lectures/:lecture_id)
    .get(function(req, res) {
        Lecture.findById(req.params.lecture_id, function(err, lecture) {
            if (err) { res.status(500).send(err); }
            res.status(200).json(lecture);
            res.end();
        });
    });

module.exports = router;
<commit_msg>Upcoming route now returns all lectures since monday of the current week. closes #15<commit_after>"use strict";

// old /upcomingLectures is now /lectures/upcoming !!!
// old /lecturesForGroups is now /lectures/groups !!!

// import the express router
var router = require("express").Router();

var moment = require("moment");

// create model
var Lecture = require("../models/model_lecture");

// on routes that end in /lectures
router.route("/")

    // get all lectures (GET /$apiBaseUrl/lectures)
    .get(function(req, res) {
        Lecture.find({}).sort({startTime: 1}).limit(100).exec(function(err, lectures) {
            if (err) { res.status(500).send(err); }
            res.status(200).json(lectures);
            res.end();
        });
    });

// on routes that end in /lectures/upcoming
// this returns all lectures since monday of the current week
router.route("/upcoming")

    // get upcoming lectures (GET /$apiBaseUrl/lectures/upcoming)
    .post(function(req, res) {
        var mon = moment().day(1);
        mon.hour(0);
        mon.minute(0);
        mon.seconds(0);

        var reqGroups = JSON.parse(req.body.groups || "[]");
        var query = { groups: { $in: reqGroups }, "startTime": {"$gte": mon}};

        // if no reqGroups provided, return all lectures
        if (reqGroups.length === 0) {
            delete query.groups;
        }

        // check if we got a proper array
        if (reqGroups) {
            Lecture.find(query).sort({startTime: 1}).limit(100).exec(function(err, lectures) {
                if (err) { res.status(500).send(err + " - data was: " + reqGroups);  }
                res.status(200).json(lectures);
                res.end();
            });
        } else {
            res.status(400).json({ error: "ohh that query looks wrong to me: " + reqGroups });
            return;
        }
    });

// on routes that end in /lectures/groups
router.route("/groups")

    // get lectures for specific groups (POST /$apiBaseUrl/lectures/groups)
    .post(function(req, res) {

        // today at 0:00
        var today = new Date();
        today.setHours(0,0,0,0);

        var reqGroups = JSON.parse(req.body.groups || "[]");
        var query = { groups: { $in: reqGroups }, "endTime": {"$gte": today}};

        // if no reqGroups provided, return all lectures
        if (reqGroups.length === 0) {
            delete query.groups;
        }

        // check if we got a proper array
        if (reqGroups) {
            Lecture.find(query).sort({startTime: 1}).limit(100).exec(function(err, lectures) {
                if (err) { res.status(500).send(err + " - data was: " + reqGroups);  }
                res.status(200).json(lectures);
                res.end();
            });
        } else {
            res.status(400).json({ error: "ohh that query looks wrong to me: " + reqGroups });
            return;
        }
    });

// on routes that end in /lectures/weekly
router.route("/weekly")

    // get lectures for specific groups (POST /$apiBaseUrl/lectures/groups)
    .post(function(req, res) {

        var mon = moment().day(1);
        mon.hour(0);
        mon.minute(0);
        mon.seconds(0);
        var sun = moment().day(7);
        sun.hour(23);
        sun.minute(59);
        sun.seconds(59);

        var reqGroups = JSON.parse(req.body.groups || "[]");
        var query = { groups: { $in: reqGroups }, "startTime": {"$gte": mon}, "endTime": {"$lte": sun}};

        // if no reqGroups provided, return all lectures
        if (reqGroups.length === 0) {
            delete query.groups;
        }

        // check if we got a proper array
        if (reqGroups) {
            Lecture.find(query).sort({startTime: 1}).limit(100).exec(function(err, lectures) {
                if (err) { res.status(500).send(err + " - data was: " + reqGroups);  }
                res.status(200).json(lectures);
                res.end();
            });
        } else {
            res.status(400).json({ error: "ohh that query looks wrong to me: " + reqGroups });
            return;
        }
    });

// on routes that end in /lectures/:lecture_id
router.route("/:lecture_id")

    // get lecture with that id (GET /$apiBaseUrl/lectures/:lecture_id)
    .get(function(req, res) {
        Lecture.findById(req.params.lecture_id, function(err, lecture) {
            if (err) { res.status(500).send(err); }
            res.status(200).json(lecture);
            res.end();
        });
    });

module.exports = router;
<|endoftext|>


<commit_before>const discord = require('discord.js');
const Command = require('./command');
const CommandGroup = require('./command-group');
const CommandBuilder = require('./command-builder');
const CommandMessage = require('./command-message');

/** Handles registration and searching of commands and groups */
class CommandRegistry {
	/** @param {CommandoClient} [client] - Client to use  */
	constructor(client) {
		/**
		 * The client this registry is for
		 * @type {CommandoClient}
		 */
		this.client = client;

		/**
		 * Registered commands
		 * @type {Collection<string, Command>}
		 */
		this.commands = new discord.Collection();

		/**
		 * Registered command groups
		 * @type {Collection<string, Command>}
		 */
		this.groups = new discord.Collection();

		/**
		 * Registered objects for the eval command
		 * @type {Object}
		 */
		this.evalObjects = {};

		/**
		 * Fully resolved path to the bot's commands directory
		 * @type {?string}
		 */
		this.commandsPath = null;
	}

	/**
	 * Registers a single group
	 * @param {CommandGroup|function|string[]|string} group - A CommandGroup instance, a constructor,
	 * an array of [ID, Name], or the group ID
	 * @param {string} [name] name - Name for the group (if the first argument is the group ID)
	 * @return {CommandRegistry}
	 * @see {@link CommandRegistry#registerGroups}
	 */
	registerGroup(group, name) {
		if(typeof group === 'string') return this.registerGroups([[group, name]]);
		return this.registerGroups([group]);
	}

	/**
	 * Registers multiple groups
	 * @param {CommandGroup[]|function[]|Array<Array<string>>} groups - An array of CommandGroup instances, constructors,
	 * or arrays of [ID, Name]
	 * @return {CommandRegistry}
	 */
	registerGroups(groups) {
		if(!Array.isArray(groups)) throw new TypeError('Groups must be an array.');
		for(let group of groups) {
			if(typeof group === 'function') group = new CommandGroup(this.client);
			else if(Array.isArray(group)) group = new CommandGroup(this.client, ...group);
			else if(!(group instanceof CommandGroup)) group = new CommandGroup(this, group.id, group.name, group.commands);

			const existing = this.groups.find(grp => grp.id === group.id);
			if(existing) {
				existing.name = group.name;
				this.client.emit('debug', `Group ${group.id} is already registered; renamed it to "${group.name}".`);
			} else {
				this.groups.set(group.id, group);
				/**
				 * Emitted when a group is registered
				 * @event CommandoClient#groupRegister
				 * @param {CommandGroup} group - Group that was registered
				 * @param {CommandRegistry} registry - Registry that the group was registered to
				 */
				this.client.emit('groupRegister', group, this);
				this.client.emit('debug', `Registered group ${group.id}.`);
			}
		}
		return this;
	}

	/**
	 * Registers a single command
	 * @param {Command|CommandBuilder|function} command - Either a Command instance, or a constructor for one
	 * @return {CommandRegistry}
	 * @see {@link CommandRegistry#registerCommands}
	 */
	registerCommand(command) {
		return this.registerCommands([command]);
	}

	/**
	 * Registers multiple commands
	 * @param {Command[]|CommandBuilder[]|function[]} commands - An array of Command instances or constructors
	 * @return {CommandRegistry}
	 */
	registerCommands(commands) {
		if(!Array.isArray(commands)) throw new TypeError('Commands must be an array.');
		for(let command of commands) {
			if(typeof command === 'function') command = new command(this.client); // eslint-disable-line new-cap
			else if(command instanceof CommandBuilder) command = command.command;

			// Verify that it's an actual command
			if(!command || !(command instanceof Command)) {
				this.client.emit('warn', 'Attempting to register an invalid command object: ${command}; skipping.');
				continue;
			}

			// Make sure there aren't any conflicts
			if(this.commands.some(cmd => cmd.name === command.name || cmd.aliases.includes(command.name))) {
				throw new Error(`A command with the name/alias "${command.name}" is already registered.`);
			}
			for(const alias of command.aliases) {
				if(this.commands.some(cmd => cmd.name === alias || cmd.aliases.some(ali => ali === alias))) {
					throw new Error(`A command with the name/alias "${alias}" is already registered.`);
				}
			}
			const group = this.groups.find(grp => grp.id === command.groupID);
			if(!group) throw new Error(`Group "${command.groupID}" is not registered.`);
			if(group.commands.some(cmd => cmd.memberName === command.memberName)) {
				throw new Error(`A command with the member name "${command.memberName}" is already registered in ${group.id}`);
			}

			// Add the command
			command.group = group;
			group.commands.set(command.name, command);
			this.commands.set(command.name, command);
			/**
			 * Emitted when a command is registered
			 * @event CommandoClient#commandRegister
			 * @param {CommandGroup} command - Command that was registered
			 * @param {CommandRegistry} registry - Registry that the command was registered to
			 */
			this.client.emit('commandRegister', command, this);
			this.client.emit('debug', `Registered command ${group.id}:${command.memberName}.`);
		}

		return this;
	}

	/**
	 * Registers all commands in a given directory. The files must export a Command class constructor or instance,
	 * or a CommandBuilder instance.
	 * @param {string|RequireAllOptions} options - The path to the directory, or a require-all options object
	 * @return {CommandRegistry}
	 */
	registerCommandsIn(options) {
		const obj = require('require-all')(options);
		const commands = [];
		for(const group of Object.values(obj)) {
			for(const command of Object.values(group)) commands.push(command);
		}
		if(typeof options === 'string' && !this.commandsPath) this.commandsPath = options;
		return this.registerCommands(commands);
	}

	/**
	 * Registers both the default groups and commands
	 * @return {CommandRegistry}
	 */
	registerDefaults() {
		this.registerDefaultGroups();
		this.registerDefaultCommands();
		return this;
	}

	/**
	 * Registers the default groups
	 * @return {CommandRegistry}
	 */
	registerDefaultGroups() {
		return this.registerGroups([
			['commands', 'Commands', true],
			['util', 'Utility']
		]);
	}

	/**
	 * Registers the default commands to the registry
	 * @param {Object} [options] - Object specifying what commands to register
	 * @param {boolean} [options.help=true] - Whether or not to register the built-in help command
	 * @param {boolean} [options.prefix=true] - Whether or not to register the built-in prefix command
	 * @param {boolean} [options.eval_=true] - Whether or not to register the built-in eval command
	 * @param {boolean} [options.ping=true] - Whether or not to register the built-in ping command
	 * @param {boolean} [options.commandState=true] - Whether or not to register the built-in command state commands
	 * (enable, disable, reload, list groups)
	 * @return {CommandRegistry}
	 */
	registerDefaultCommands({ help = true, prefix = true, ping = true, eval_ = true, commandState = true } = {}) {
		if(help) this.registerCommand(require('./commands/util/help'));
		if(prefix) this.registerCommand(require('./commands/util/prefix'));
		if(ping) this.registerCommand(require('./commands/util/ping'));
		if(eval_) this.registerCommand(require('./commands/util/eval'));
		if(commandState) {
			this.registerCommands([
				require('./commands/commands/groups'),
				require('./commands/commands/enable'),
				require('./commands/commands/disable'),
				require('./commands/commands/reload'),
				require('./commands/commands/load'),
				require('./commands/commands/unload')
			]);
		}
		return this;
	}

	/**
	 * Reregisters a command (does not support changing name, group, or memberName)
	 * @param {Command|CommandBuilder|function} command - New command
	 * @param {Command} oldCommand - Old command
	 */
	reregisterCommand(command, oldCommand) {
		if(typeof command === 'function') command = new command(this.client); // eslint-disable-line new-cap
		else if(command instanceof CommandBuilder) command = command.command;
		if(command.name !== oldCommand.name) throw new Error('Command name cannot change.');
		if(command.groupID !== oldCommand.groupID) throw new Error('Command group cannot change.');
		if(command.memberName !== oldCommand.memberName) throw new Error('Command memberName cannot change.');
		command.group = this.resolveGroup(command.groupID);
		command.group.commands.set(command.name, command);
		this.commands.set(command.name, command);
		/**
		 * Emitted when a command is reregistered
		 * @event CommandoClient#commandReregister
		 * @param {Command} newCommand - New command
		 * @param {Command} oldCommand - Old command
		 */
		this.client.emit('commandReregister', command, oldCommand);
		this.client.emit('debug', `Reregistered command ${command.groupID}:${command.memberName}.`);
	}

	/**
	 * Unregisters a command
	 * @param {Command} command - Command to unregister
	 */
	unregisterCommand(command) {
		this.commands.delete(command.name);
		command.group.commands.delete(command.name);
		/**
		 * Emitted when a command is unregistered
		 * @event CommandoClient#commandUnregister
		 * @param {Command} command - Command that was unregistered
		 */
		this.client.emit('commandUnregister', command);
		this.client.emit('debug', `Unregistered command ${command.groupID}:${command.memberName}.`);
	}

	/**
	 * Registers a single object to be usable by the eval command
	 * @param {string} key - The key for the object
	 * @param {Object} obj - The object
	 * @return {CommandRegistry}
	 * @see {@link CommandRegistry#registerEvalObjects}
	 */
	registerEvalObject(key, obj) {
		const registerObj = {};
		registerObj[key] = obj;
		return this.registerEvalObjects(registerObj);
	}

	/**
	 * Registers multiple objects to be usable by the eval command
	 * @param {Object} obj - An object of keys: values
	 * @return {CommandRegistry}
	 */
	registerEvalObjects(obj) {
		Object.assign(this.evalObjects, obj);
		return this;
	}

	/**
	 * Create a command builder
	 * @param {CommandInfo} [info] - The command information
	 * @param {CommandBuilderFunctions} [funcs] - The command functions to set
	 * @return {CommandBuilder} The builder
	 */
	buildCommand(info = null, funcs = null) {
		return new CommandBuilder(this, info, funcs);
	}

	/**
	 * Finds all groups that match the search string
	 * @param {string} [searchString] - The string to search for
	 * @param {boolean} [exact=false] - Whether the search should be exact
	 * @return {CommandGroup[]} All groups that are found
	 */
	findGroups(searchString = null, exact = false) {
		if(!searchString) return this.groups;

		// Find all matches
		const lcSearch = searchString.toLowerCase();
		const matchedGroups = this.groups.filterArray(
			exact ? groupFilterExact(lcSearch) : groupFilterInexact(lcSearch)
		);
		if(exact) return matchedGroups;

		// See if there's an exact match
		for(const group of matchedGroups) {
			if(group.name.toLowerCase() === lcSearch || group.id === lcSearch) return [group];
		}
		return matchedGroups;
	}

	/**
	 * A CommandGroupResolvable can be:
	 * * A CommandGroup
	 * * A group ID
	 * @typedef {CommandGroup|string} CommandGroupResolvable
	 */

	/**
	 * Resolves a CommandGroupResolvable to a CommandGroup object
	 * @param {CommandGroup|string} group - The group to resolve
	 * @return {CommandGroup} The resolved CommandGroup
	 */
	resolveGroup(group) {
		if(group instanceof CommandGroup) return group;
		if(typeof group === 'string') {
			const groups = this.findGroups(group, true);
			if(groups.length === 1) return groups[0];
		}
		throw new Error('Unable to resolve group.');
	}

	/**
	 * Finds all commands that match the search string
	 * @param {string} [searchString] - The string to search for
	 * @param {boolean} [exact=false] - Whether the search should be exact
	 * @param {Message} [message] - The message to check usability against
	 * @return {Command[]} All commands that are found
	 */
	findCommands(searchString = null, exact = false, message = null) {
		if(!searchString) return message ? this.commands.filterArray(cmd => cmd.isUsable(message)) : this.commands;

		// Find all matches
		const lcSearch = searchString.toLowerCase();
		const matchedCommands = this.commands.filterArray(
			exact ? commandFilterExact(lcSearch) : commandFilterInexact(lcSearch)
		);
		if(exact) return matchedCommands;

		// See if there's an exact match
		for(const command of matchedCommands) {
			if(command.name === lcSearch || (command.aliases && command.aliases.some(ali => ali === lcSearch))) {
				return [command];
			}
		}

		return matchedCommands;
	}

	/**
	 * A CommandResolvable can be:
	 * * A Command
	 * * A command name
	 * * A CommandMessage
	 * @typedef {Command|string} CommandResolvable
	 */

	/**
	 * Resolves a CommandResolvable to a Command object
	 * @param {Command|string} command - The command to resolve
	 * @return {Command} The resolved Command
	 */
	resolveCommand(command) {
		if(command instanceof Command) return command;
		if(command instanceof CommandMessage) return command.command;
		if(typeof command === 'string') {
			const commands = this.findCommands(command, true);
			if(commands.length === 1) return commands[0];
		}
		throw new Error('Unable to resolve command.');
	}
}

function groupFilterExact(search) {
	return grp => grp.id === search || grp.name.toLowerCase() === search;
}

function groupFilterInexact(search) {
	return grp => grp.id.includes(search) || grp.name.toLowerCase().includes(search);
}

function commandFilterExact(search) {
	return cmd => cmd.name === search ||
		(cmd.aliases && cmd.aliases.some(ali => ali === search)) ||
		`${cmd.groupID}:${cmd.memberName}` === search;
}

function commandFilterInexact(search) {
	return cmd => cmd.name.includes(search) ||
		`${cmd.groupID}:${cmd.memberName}` === search ||
		(cmd.aliases && cmd.aliases.some(ali => ali.includes(search)));
}

module.exports = CommandRegistry;
<commit_msg>Fixed two more docs<commit_after>const discord = require('discord.js');
const Command = require('./command');
const CommandGroup = require('./command-group');
const CommandBuilder = require('./command-builder');
const CommandMessage = require('./command-message');

/** Handles registration and searching of commands and groups */
class CommandRegistry {
	/** @param {CommandoClient} [client] - Client to use  */
	constructor(client) {
		/**
		 * The client this registry is for
		 * @type {CommandoClient}
		 */
		this.client = client;

		/**
		 * Registered commands
		 * @type {Collection<string, Command>}
		 */
		this.commands = new discord.Collection();

		/**
		 * Registered command groups
		 * @type {Collection<string, Command>}
		 */
		this.groups = new discord.Collection();

		/**
		 * Registered objects for the eval command
		 * @type {Object}
		 */
		this.evalObjects = {};

		/**
		 * Fully resolved path to the bot's commands directory
		 * @type {?string}
		 */
		this.commandsPath = null;
	}

	/**
	 * Registers a single group
	 * @param {CommandGroup|function|string[]|string} group - A CommandGroup instance, a constructor,
	 * an array of [ID, Name], or the group ID
	 * @param {string} [name] name - Name for the group (if the first argument is the group ID)
	 * @return {CommandRegistry}
	 * @see {@link CommandRegistry#registerGroups}
	 */
	registerGroup(group, name) {
		if(typeof group === 'string') return this.registerGroups([[group, name]]);
		return this.registerGroups([group]);
	}

	/**
	 * Registers multiple groups
	 * @param {CommandGroup[]|function[]|Array<Array<string>>} groups - An array of CommandGroup instances, constructors,
	 * or arrays of [ID, Name]
	 * @return {CommandRegistry}
	 */
	registerGroups(groups) {
		if(!Array.isArray(groups)) throw new TypeError('Groups must be an array.');
		for(let group of groups) {
			if(typeof group === 'function') group = new CommandGroup(this.client);
			else if(Array.isArray(group)) group = new CommandGroup(this.client, ...group);
			else if(!(group instanceof CommandGroup)) group = new CommandGroup(this, group.id, group.name, group.commands);

			const existing = this.groups.find(grp => grp.id === group.id);
			if(existing) {
				existing.name = group.name;
				this.client.emit('debug', `Group ${group.id} is already registered; renamed it to "${group.name}".`);
			} else {
				this.groups.set(group.id, group);
				/**
				 * Emitted when a group is registered
				 * @event CommandoClient#groupRegister
				 * @param {CommandGroup} group - Group that was registered
				 * @param {CommandRegistry} registry - Registry that the group was registered to
				 */
				this.client.emit('groupRegister', group, this);
				this.client.emit('debug', `Registered group ${group.id}.`);
			}
		}
		return this;
	}

	/**
	 * Registers a single command
	 * @param {Command|CommandBuilder|function} command - Either a Command instance, or a constructor for one
	 * @return {CommandRegistry}
	 * @see {@link CommandRegistry#registerCommands}
	 */
	registerCommand(command) {
		return this.registerCommands([command]);
	}

	/**
	 * Registers multiple commands
	 * @param {Command[]|CommandBuilder[]|function[]} commands - An array of Command instances or constructors
	 * @return {CommandRegistry}
	 */
	registerCommands(commands) {
		if(!Array.isArray(commands)) throw new TypeError('Commands must be an array.');
		for(let command of commands) {
			if(typeof command === 'function') command = new command(this.client); // eslint-disable-line new-cap
			else if(command instanceof CommandBuilder) command = command.command;

			// Verify that it's an actual command
			if(!command || !(command instanceof Command)) {
				this.client.emit('warn', 'Attempting to register an invalid command object: ${command}; skipping.');
				continue;
			}

			// Make sure there aren't any conflicts
			if(this.commands.some(cmd => cmd.name === command.name || cmd.aliases.includes(command.name))) {
				throw new Error(`A command with the name/alias "${command.name}" is already registered.`);
			}
			for(const alias of command.aliases) {
				if(this.commands.some(cmd => cmd.name === alias || cmd.aliases.some(ali => ali === alias))) {
					throw new Error(`A command with the name/alias "${alias}" is already registered.`);
				}
			}
			const group = this.groups.find(grp => grp.id === command.groupID);
			if(!group) throw new Error(`Group "${command.groupID}" is not registered.`);
			if(group.commands.some(cmd => cmd.memberName === command.memberName)) {
				throw new Error(`A command with the member name "${command.memberName}" is already registered in ${group.id}`);
			}

			// Add the command
			command.group = group;
			group.commands.set(command.name, command);
			this.commands.set(command.name, command);
			/**
			 * Emitted when a command is registered
			 * @event CommandoClient#commandRegister
			 * @param {CommandGroup} command - Command that was registered
			 * @param {CommandRegistry} registry - Registry that the command was registered to
			 */
			this.client.emit('commandRegister', command, this);
			this.client.emit('debug', `Registered command ${group.id}:${command.memberName}.`);
		}

		return this;
	}

	/**
	 * Registers all commands in a given directory. The files must export a Command class constructor or instance,
	 * or a CommandBuilder instance.
	 * @param {string|RequireAllOptions} options - The path to the directory, or a require-all options object
	 * @return {CommandRegistry}
	 */
	registerCommandsIn(options) {
		const obj = require('require-all')(options);
		const commands = [];
		for(const group of Object.values(obj)) {
			for(const command of Object.values(group)) commands.push(command);
		}
		if(typeof options === 'string' && !this.commandsPath) this.commandsPath = options;
		return this.registerCommands(commands);
	}

	/**
	 * Registers both the default groups and commands
	 * @return {CommandRegistry}
	 */
	registerDefaults() {
		this.registerDefaultGroups();
		this.registerDefaultCommands();
		return this;
	}

	/**
	 * Registers the default groups
	 * @return {CommandRegistry}
	 */
	registerDefaultGroups() {
		return this.registerGroups([
			['commands', 'Commands', true],
			['util', 'Utility']
		]);
	}

	/**
	 * Registers the default commands to the registry
	 * @param {Object} [options] - Object specifying what commands to register
	 * @param {boolean} [options.help=true] - Whether or not to register the built-in help command
	 * @param {boolean} [options.prefix=true] - Whether or not to register the built-in prefix command
	 * @param {boolean} [options.eval_=true] - Whether or not to register the built-in eval command
	 * @param {boolean} [options.ping=true] - Whether or not to register the built-in ping command
	 * @param {boolean} [options.commandState=true] - Whether or not to register the built-in command state commands
	 * (enable, disable, reload, list groups)
	 * @return {CommandRegistry}
	 */
	registerDefaultCommands({ help = true, prefix = true, ping = true, eval_ = true, commandState = true } = {}) {
		if(help) this.registerCommand(require('./commands/util/help'));
		if(prefix) this.registerCommand(require('./commands/util/prefix'));
		if(ping) this.registerCommand(require('./commands/util/ping'));
		if(eval_) this.registerCommand(require('./commands/util/eval'));
		if(commandState) {
			this.registerCommands([
				require('./commands/commands/groups'),
				require('./commands/commands/enable'),
				require('./commands/commands/disable'),
				require('./commands/commands/reload'),
				require('./commands/commands/load'),
				require('./commands/commands/unload')
			]);
		}
		return this;
	}

	/**
	 * Reregisters a command (does not support changing name, group, or memberName)
	 * @param {Command|CommandBuilder|function} command - New command
	 * @param {Command} oldCommand - Old command
	 */
	reregisterCommand(command, oldCommand) {
		if(typeof command === 'function') command = new command(this.client); // eslint-disable-line new-cap
		else if(command instanceof CommandBuilder) command = command.command;
		if(command.name !== oldCommand.name) throw new Error('Command name cannot change.');
		if(command.groupID !== oldCommand.groupID) throw new Error('Command group cannot change.');
		if(command.memberName !== oldCommand.memberName) throw new Error('Command memberName cannot change.');
		command.group = this.resolveGroup(command.groupID);
		command.group.commands.set(command.name, command);
		this.commands.set(command.name, command);
		/**
		 * Emitted when a command is reregistered
		 * @event CommandoClient#commandReregister
		 * @param {Command} newCommand - New command
		 * @param {Command} oldCommand - Old command
		 */
		this.client.emit('commandReregister', command, oldCommand);
		this.client.emit('debug', `Reregistered command ${command.groupID}:${command.memberName}.`);
	}

	/**
	 * Unregisters a command
	 * @param {Command} command - Command to unregister
	 */
	unregisterCommand(command) {
		this.commands.delete(command.name);
		command.group.commands.delete(command.name);
		/**
		 * Emitted when a command is unregistered
		 * @event CommandoClient#commandUnregister
		 * @param {Command} command - Command that was unregistered
		 */
		this.client.emit('commandUnregister', command);
		this.client.emit('debug', `Unregistered command ${command.groupID}:${command.memberName}.`);
	}

	/**
	 * Registers a single object to be usable by the eval command
	 * @param {string} key - The key for the object
	 * @param {Object} obj - The object
	 * @return {CommandRegistry}
	 * @see {@link CommandRegistry#registerEvalObjects}
	 */
	registerEvalObject(key, obj) {
		const registerObj = {};
		registerObj[key] = obj;
		return this.registerEvalObjects(registerObj);
	}

	/**
	 * Registers multiple objects to be usable by the eval command
	 * @param {Object} obj - An object of keys: values
	 * @return {CommandRegistry}
	 */
	registerEvalObjects(obj) {
		Object.assign(this.evalObjects, obj);
		return this;
	}

	/**
	 * Create a command builder
	 * @param {CommandInfo} [info] - The command information
	 * @param {CommandBuilderFunctions} [funcs] - The command functions to set
	 * @return {CommandBuilder} The builder
	 */
	buildCommand(info = null, funcs = null) {
		return new CommandBuilder(this, info, funcs);
	}

	/**
	 * Finds all groups that match the search string
	 * @param {string} [searchString] - The string to search for
	 * @param {boolean} [exact=false] - Whether the search should be exact
	 * @return {CommandGroup[]} All groups that are found
	 */
	findGroups(searchString = null, exact = false) {
		if(!searchString) return this.groups;

		// Find all matches
		const lcSearch = searchString.toLowerCase();
		const matchedGroups = this.groups.filterArray(
			exact ? groupFilterExact(lcSearch) : groupFilterInexact(lcSearch)
		);
		if(exact) return matchedGroups;

		// See if there's an exact match
		for(const group of matchedGroups) {
			if(group.name.toLowerCase() === lcSearch || group.id === lcSearch) return [group];
		}
		return matchedGroups;
	}

	/**
	 * A CommandGroupResolvable can be:
	 * * A CommandGroup
	 * * A group ID
	 * @typedef {CommandGroup|string} CommandGroupResolvable
	 */

	/**
	 * Resolves a CommandGroupResolvable to a CommandGroup object
	 * @param {CommandGroupResolvable} group - The group to resolve
	 * @return {CommandGroup} The resolved CommandGroup
	 */
	resolveGroup(group) {
		if(group instanceof CommandGroup) return group;
		if(typeof group === 'string') {
			const groups = this.findGroups(group, true);
			if(groups.length === 1) return groups[0];
		}
		throw new Error('Unable to resolve group.');
	}

	/**
	 * Finds all commands that match the search string
	 * @param {string} [searchString] - The string to search for
	 * @param {boolean} [exact=false] - Whether the search should be exact
	 * @param {Message} [message] - The message to check usability against
	 * @return {Command[]} All commands that are found
	 */
	findCommands(searchString = null, exact = false, message = null) {
		if(!searchString) return message ? this.commands.filterArray(cmd => cmd.isUsable(message)) : this.commands;

		// Find all matches
		const lcSearch = searchString.toLowerCase();
		const matchedCommands = this.commands.filterArray(
			exact ? commandFilterExact(lcSearch) : commandFilterInexact(lcSearch)
		);
		if(exact) return matchedCommands;

		// See if there's an exact match
		for(const command of matchedCommands) {
			if(command.name === lcSearch || (command.aliases && command.aliases.some(ali => ali === lcSearch))) {
				return [command];
			}
		}

		return matchedCommands;
	}

	/**
	 * A CommandResolvable can be:
	 * * A Command
	 * * A command name
	 * * A CommandMessage
	 * @typedef {Command|string} CommandResolvable
	 */

	/**
	 * Resolves a CommandResolvable to a Command object
	 * @param {CommandResolvable} command - The command to resolve
	 * @return {Command} The resolved Command
	 */
	resolveCommand(command) {
		if(command instanceof Command) return command;
		if(command instanceof CommandMessage) return command.command;
		if(typeof command === 'string') {
			const commands = this.findCommands(command, true);
			if(commands.length === 1) return commands[0];
		}
		throw new Error('Unable to resolve command.');
	}
}

function groupFilterExact(search) {
	return grp => grp.id === search || grp.name.toLowerCase() === search;
}

function groupFilterInexact(search) {
	return grp => grp.id.includes(search) || grp.name.toLowerCase().includes(search);
}

function commandFilterExact(search) {
	return cmd => cmd.name === search ||
		(cmd.aliases && cmd.aliases.some(ali => ali === search)) ||
		`${cmd.groupID}:${cmd.memberName}` === search;
}

function commandFilterInexact(search) {
	return cmd => cmd.name.includes(search) ||
		`${cmd.groupID}:${cmd.memberName}` === search ||
		(cmd.aliases && cmd.aliases.some(ali => ali.includes(search)));
}

module.exports = CommandRegistry;
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var depts = require('../bin/departments');
var postgresModel = require('../models/postgres.js');
var hbs = require('hbs');
var paginate = require('handlebars-paginate');
var ua = require('universal-analytics');
var queryString = require('querystring');

hbs.registerHelper('paginate', paginate);
hbs.registerHelper('paginate-link', function(url, pageNum) {
  //important - page number parameter must be last in url for this to work
  if (url.indexOf('?') > -1) { //contains params
    if (url.indexOf('?p=') > -1) { // already contains page number param
      return url.substring(0, url.indexOf('?p=')) + "?p=" + pageNum.toString();
    } else if (url.indexOf('&p=') > -1){  // already contains page number and other params
      return url.substring(0, url.indexOf('&p=')) + "&p=" + pageNum.toString();
    } else {
      return url + "&p=" + pageNum.toString();
    }
  } else {
    return url + "?p=" + pageNum.toString();
  }
});
var deptBreaker = '';
hbs.registerHelper('split-depts', function(str) {
  str = hbs.Utils.escapeExpression(str);
  for (var i = 0; i < str.length; i++) {
    str = str.replace(';', deptBreaker);
  }
  return new hbs.SafeString(str);
});
hbs.registerHelper('json', function(context) {
  return JSON.stringify(context);
});

function listAll(req, res) {

  console.log(req.session);

  if (req.session.loggedin == false || !(req.session.loggedin)) res.redirect('/users'); //if user info not loaded, redirect to users route

  if (req.query){
    req.session.lastquery = queryString.stringify(req.query);
    console.log(req.session.lastquery);
  }

  var callback = function(listings) {

  res.render('listings', {
      userID: req.session.cas_user,
      title: 'Listings',
      searchPlaceholder: req.query.search || '',
      deptPlaceholder: req.query.departments || 'Departments',
      depts: depts,
      isListings: true,
      listings: listings.slice((req.query.p - 1) * resultsPerPage || 0, req.query.p * resultsPerPage || resultsPerPage), //gets entries for current page
      numberOfResults: listings.length,
      url: req.url,
      pagination: {
        page: req.query.p || 1,
        pageCount: Math.ceil(listings.length / resultsPerPage),
      }
    });
  };

  var resultsPerPage = req.query.limit || 10;
  var maxresultsPerPage = 50;
  //set max resultsPerPage to 50
  if (req.query.limit > maxresultsPerPage) {
    resultsPerPage = maxresultsPerPage;
  }
  if (req.query.search) {
    if (req.query.departments && req.query.departments != "Departments") {
      postgresModel.searchANDfilter(req.query.search.trim(), req.query.departments, req.session.cas_user, callback);
    } else {
      postgresModel.searchListings(req.query.search.trim(), req.session.cas_user, callback);
    }
  } else {
    if (req.query.departments && req.query.departments != "Departments") {
      postgresModel.filterDepts(req.query.departments, req.session.cas_user, callback);
    } else {
      postgresModel.getAllListings(req.session.cas_user, callback);
    }
  }
}

//GET home page.
router.get('/listings', listAll);

router.post('/listings/addFavorite/:listingid/',function(req,res){
  postgresModel.addFavorite(req.session.cas_user, req.params.listingid, function(log) {
    console.log('Entry  '+ req.params.listingid.toString() +' Added To Favorites');
    if (req.session.lastquery){
      res.redirect('/listings?'+req.session.lastquery);
    } else{
      res.redirect('/listings');
    }
  });
});

router.post('/listings/removeFavorite/:listingid',function(req,res){
  console.log(req.params.listingid);
  postgresModel.removeFavorite(req.session.cas_user, req.params.listingid, function(log) {
    console.log('Entry '+ req.params.listingid.toString() +' Removed From Favorites');
    if (req.session.lastquery){
      res.redirect('/listings?'+req.session.lastquery);
    } else{
      res.redirect('/listings');
    }
  });
});

module.exports = router;
<commit_msg>some bug in replacement<commit_after>var express = require('express');
var router = express.Router();
var depts = require('../bin/departments');
var postgresModel = require('../models/postgres.js');
var hbs = require('hbs');
var paginate = require('handlebars-paginate');
var ua = require('universal-analytics');
var queryString = require('querystring');

hbs.registerHelper('paginate', paginate);
hbs.registerHelper('paginate-link', function(url, pageNum) {
  //important - page number parameter must be last in url for this to work
  if (url.indexOf('?') > -1) { //contains params
    if (url.indexOf('?p=') > -1) { // already contains page number param
      return url.substring(0, url.indexOf('?p=')) + "?p=" + pageNum.toString();
    } else if (url.indexOf('&p=') > -1){  // already contains page number and other params
      return url.substring(0, url.indexOf('&p=')) + "&p=" + pageNum.toString();
    } else {
      return url + "&p=" + pageNum.toString();
    }
  } else {
    return url + "?p=" + pageNum.toString();
  }
});
var deptBreaker = '';
hbs.registerHelper('split-depts', function(str) {
  str = hbs.Utils.escapeExpression(str);
  for (var i = 0; i < str.length; i++) {
    str = str.replace(/;/g, deptBreaker);
  }
  return new hbs.SafeString(str);
});
hbs.registerHelper('json', function(context) {
  return JSON.stringify(context);
});

function listAll(req, res) {

  console.log(req.session);

  if (req.session.loggedin == false || !(req.session.loggedin)) res.redirect('/users'); //if user info not loaded, redirect to users route

  if (req.query){
    req.session.lastquery = queryString.stringify(req.query);
    console.log(req.session.lastquery);
  }

  var callback = function(listings) {

  res.render('listings', {
      userID: req.session.cas_user,
      title: 'Listings',
      searchPlaceholder: req.query.search || '',
      deptPlaceholder: req.query.departments || 'Departments',
      depts: depts,
      isListings: true,
      listings: listings.slice((req.query.p - 1) * resultsPerPage || 0, req.query.p * resultsPerPage || resultsPerPage), //gets entries for current page
      numberOfResults: listings.length,
      url: req.url,
      pagination: {
        page: req.query.p || 1,
        pageCount: Math.ceil(listings.length / resultsPerPage),
      }
    });
  };

  var resultsPerPage = req.query.limit || 10;
  var maxresultsPerPage = 50;
  //set max resultsPerPage to 50
  if (req.query.limit > maxresultsPerPage) {
    resultsPerPage = maxresultsPerPage;
  }
  if (req.query.search) {
    if (req.query.departments && req.query.departments != "Departments") {
      postgresModel.searchANDfilter(req.query.search.trim(), req.query.departments, req.session.cas_user, callback);
    } else {
      postgresModel.searchListings(req.query.search.trim(), req.session.cas_user, callback);
    }
  } else {
    if (req.query.departments && req.query.departments != "Departments") {
      postgresModel.filterDepts(req.query.departments, req.session.cas_user, callback);
    } else {
      postgresModel.getAllListings(req.session.cas_user, callback);
    }
  }
}

//GET home page.
router.get('/listings', listAll);

router.post('/listings/addFavorite/:listingid/',function(req,res){
  postgresModel.addFavorite(req.session.cas_user, req.params.listingid, function(log) {
    console.log('Entry  '+ req.params.listingid.toString() +' Added To Favorites');
    if (req.session.lastquery){
      res.redirect('/listings?'+req.session.lastquery);
    } else{
      res.redirect('/listings');
    }
  });
});

router.post('/listings/removeFavorite/:listingid',function(req,res){
  console.log(req.params.listingid);
  postgresModel.removeFavorite(req.session.cas_user, req.params.listingid, function(log) {
    console.log('Entry '+ req.params.listingid.toString() +' Removed From Favorites');
    if (req.session.lastquery){
      res.redirect('/listings?'+req.session.lastquery);
    } else{
      res.redirect('/listings');
    }
  });
});

module.exports = router;
<|endoftext|>


<commit_before>/**
 *

 * POST /messages/:project_id	{@link Message.createMessage}

 * GET /messages/:project_id	{@link Message.getMessages}

 * GET /messages/:message_id	{@link Message.getMessage}

 * PUT /messages/:message_id	{@link Message.editMessage}

 * DELETE /messages/:message_id	{@link Message.deleteMessage}

 *

 * @namespace Message
 * @author Florian Kauder
 */

var Project = require('../models/project');
var User = require('../models/user');
var Message = require('../models/message');
var Response = require('../modules/response');

var express = require('express');
var async = require('async');
var calls = [];

var router = express.Router();

router.route('/messages/:project_id').post(createMessage);
router.route('/messages/:project_id').get(getMessages);
router.route('/message/:message_id').get(getMessage);
router.route('/message/:message_id').put(editMessage);
router.route('/message/:message_id').delete(deleteMessage);

module.exports = router;

/**
 * Create a new message

 * Level needed : 1 - Member
 * @memberof Message
 * @param {Express.Request} req - request send
 * @param {String} req.body.content - content of message
 * @param {String} req.body.authorUsername - username of author
 * @param {ObjectID} req.params.project_id - id of project
 * @param {Express.Response} res - variable to send the response
 */
function createMessage(req, res) {
    var message = new Message();

    var projectFound = true;

    // Check if variables are send
    if (!("content" in req.body)) {
        Response(res, "Error : No content given", null, 0);
        return;
    } else if (req.session.userId == undefined) {
        Response(res, "Error : Not logged", null, 0);
        return;
    } else if (req.session.level < 1) {
        Response(res, "Error : You don't have rights to create message", null, 0);
        return;
    }

    // Setting message fields
    message.content = req.body.content;
    message.author = req.session.userId;

    calls.push(function checkProject(callback) {
        Project.findById(req.params.project_id, function (err, project) {
            if (err || project == null) projectFound = false;
            else message.project = project._id;
            callback();
        });
    });

    // Wait response, and send result
    async.parallel(calls, function () {
        if (!projectFound) Response(res, "Error : Project not found", null, 0);
        else {
            message.save(function (err) {
                if (err)
                    Response(res, "Error", err, 0);
                else Response(res, 'Message created', message, 1);
            });
        }
    });
}

/**
 * Get all messages from a project

 * Level needed : 0 - Guest
 * @memberof Message
 * @param {Express.Request} req - request send
 * @param {ObjectID} req.params.project_id - id of project
 * @param {Express.Response} res - variable to send the response
 */
function getMessages(req, res) {
    Message.find({
        thread: req.params.project_id
    }, function (err, messages) {
        if (err) Response(res, "Error", err, 0);
        else if (messages == null)
            Response(res, "Error : No messages found", messages, 0);
        else Response(res, "Messages found", messages, 1);
    });
}

/**
 * Get a specific message

 * Level needed : 0 - Guest
 * @memberof Message
 * @param {Express.Request} req - request send
 * @param {ObjectID} req.params.message_id - id of message
 * @param {Express.Response} res - variable to send the response
 */
function getMessage(req, res) {
    Message.findById(req.params.message_id, function (err, message) {
        if (err) Response(res, "Error", err, 0);
        else if (message == null)
            Response(res, "Error : Message not found", message, 0);
        else Response(res, "Message found", message, 1);
    });
}

/**
 * Edit a message

 * Level needed : Owner | 3 - Admin
 * @memberof Message
 * @param {Express.Request} req - request send
 * @param {ObjectID} req.params.message_id - id of message
 * @param {String} [req.body.content] - new content
 * @param {Express.Response} res - variable to send the response
 */
function editMessage(req, res) {
    Message.findById(req.params.message_id, function (err, message) {
        if (err) {
            Response(res, "Error", err, 0);
            return;
        } else if (message == null) {
            Response(res, "Error : Message not found", message, 0);
            return;
        } else if ((message.author != req.session.userId) && (req.session.level < 3)) {
            Response(res, "Error : You're not the owner of this message", null, 0);
            return;
        }

        // Edit content if exists in request
        if ("content" in req.body) message.content = req.body.content;
        // Edit the lastEdited time
        message.lastEdited = Date.now();

        message.save(function (err) {
            if (err) Response(res, "Error", err, 0);
            else Response(res, 'Message edited', message, 1);
        });

    });
}

/**
 * Delete a message

 * Level needed : Owner | 3 - Admin
 * @memberof Message
 * @param {Express.Request} req - request send
 * @param {ObjectID} req.params.message_id - id of message
 * @param {Express.Response} res - variable to send the response
 */
function deleteMessage(req, res) {
    Message.findById(req.params.message_id, function (err, message) {
        if (err) {
            Response(res, "Error", err, 0);
            return;
        } else if (message == null) {
            Response(res, "Error : Message not found", message, 0);
            return;
        } else if ((message.author != req.session.userId) && (req.session.level < 3)) {
            Response(res, "Error : You're not the owner of this message", null, 0);
            return;
        }

        Message.remove({
            _id: req.params.message_id
        }, function (err, obj) {
            if (err) Response(res, "Error", err, 0);
            else Response(res, 'Message deleted', obj, 1);
        });
    });
}<commit_msg>Modify guest level<commit_after>/**
 *

 * POST /messages/:project_id	{@link Message.createMessage}

 * GET /messages/:project_id	{@link Message.getMessages}

 * GET /messages/:message_id	{@link Message.getMessage}

 * PUT /messages/:message_id	{@link Message.editMessage}

 * DELETE /messages/:message_id	{@link Message.deleteMessage}

 *

 * @namespace Message
 * @author Florian Kauder
 */

var Project = require('../models/project');
var User = require('../models/user');
var Message = require('../models/message');
var Response = require('../modules/response');

var express = require('express');
var async = require('async');
var calls = [];

var router = express.Router();

router.route('/messages/:project_id').post(createMessage);
router.route('/messages/:project_id').get(getMessages);
router.route('/message/:message_id').get(getMessage);
router.route('/message/:message_id').put(editMessage);
router.route('/message/:message_id').delete(deleteMessage);

module.exports = router;

/**
 * Create a new message

 * Level needed : 1 - Member
 * @memberof Message
 * @param {Express.Request} req - request send
 * @param {String} req.body.content - content of message
 * @param {String} req.body.authorUsername - username of author
 * @param {ObjectID} req.params.project_id - id of project
 * @param {Express.Response} res - variable to send the response
 */
function createMessage(req, res) {
    var message = new Message();

    var projectFound = true;

    // Check if variables are send
    if (!("content" in req.body)) {
        Response(res, "Error : No content given", null, 0);
        return;
    } else if (req.session.userId == undefined) {
        Response(res, "Error : Not logged", null, 0);
        return;
    } else if (req.session.level < 1) {
        Response(res, "Error : You don't have rights to create message", null, 0);
        return;
    }

    // Setting message fields
    message.content = req.body.content;
    message.author = req.session.userId;

    calls.push(function checkProject(callback) {
        Project.findById(req.params.project_id, function (err, project) {
            if (err || project == null) projectFound = false;
            else message.project = project._id;
            callback();
        });
    });

    // Wait response, and send result
    async.parallel(calls, function () {
        if (!projectFound) Response(res, "Error : Project not found", null, 0);
        else {
            message.save(function (err) {
                if (err)
                    Response(res, "Error", err, 0);
                else Response(res, 'Message created', message, 1);
            });
        }
    });
}

/**
 * Get all messages from a project

 * Level needed : -1 - Guest
 * @memberof Message
 * @param {Express.Request} req - request send
 * @param {ObjectID} req.params.project_id - id of project
 * @param {Express.Response} res - variable to send the response
 */
function getMessages(req, res) {
    Message.find({
        thread: req.params.project_id
    }, function (err, messages) {
        if (err) Response(res, "Error", err, 0);
        else if (messages == null)
            Response(res, "Error : No messages found", messages, 0);
        else Response(res, "Messages found", messages, 1);
    });
}

/**
 * Get a specific message

 * Level needed : -1 - Guest
 * @memberof Message
 * @param {Express.Request} req - request send
 * @param {ObjectID} req.params.message_id - id of message
 * @param {Express.Response} res - variable to send the response
 */
function getMessage(req, res) {
    Message.findById(req.params.message_id, function (err, message) {
        if (err) Response(res, "Error", err, 0);
        else if (message == null)
            Response(res, "Error : Message not found", message, 0);
        else Response(res, "Message found", message, 1);
    });
}

/**
 * Edit a message

 * Level needed : Owner | 3 - Admin
 * @memberof Message
 * @param {Express.Request} req - request send
 * @param {ObjectID} req.params.message_id - id of message
 * @param {String} [req.body.content] - new content
 * @param {Express.Response} res - variable to send the response
 */
function editMessage(req, res) {
    Message.findById(req.params.message_id, function (err, message) {
        if (err) {
            Response(res, "Error", err, 0);
            return;
        } else if (message == null) {
            Response(res, "Error : Message not found", message, 0);
            return;
        } else if ((message.author != req.session.userId) && (req.session.level < 3)) {
            Response(res, "Error : You're not the owner of this message", null, 0);
            return;
        }

        // Edit content if exists in request
        if ("content" in req.body) message.content = req.body.content;
        // Edit the lastEdited time
        message.lastEdited = Date.now();

        message.save(function (err) {
            if (err) Response(res, "Error", err, 0);
            else Response(res, 'Message edited', message, 1);
        });

    });
}

/**
 * Delete a message

 * Level needed : Owner | 3 - Admin
 * @memberof Message
 * @param {Express.Request} req - request send
 * @param {ObjectID} req.params.message_id - id of message
 * @param {Express.Response} res - variable to send the response
 */
function deleteMessage(req, res) {
    Message.findById(req.params.message_id, function (err, message) {
        if (err) {
            Response(res, "Error", err, 0);
            return;
        } else if (message == null) {
            Response(res, "Error : Message not found", message, 0);
            return;
        } else if ((message.author != req.session.userId) && (req.session.level < 3)) {
            Response(res, "Error : You're not the owner of this message", null, 0);
            return;
        }

        Message.remove({
            _id: req.params.message_id
        }, function (err, obj) {
            if (err) Response(res, "Error", err, 0);
            else Response(res, 'Message deleted', obj, 1);
        });
    });
}<|endoftext|>


<commit_before>var express = require('express');
var requests = express.Router();
var pg = require('pg');
var db = require('../db');
var Users = require('../models/User');
var api = require('../models/api');

requests.route('/')
  .get(function(req, res) {
    pg.connect(db, function(err, client, done) {
      if (err) {
        return res.json(500, {error: err});
      }

      Users.getAllFriendRequests(client, function(err, result) {
        done();

        if (err) {
          res.json(500, {error: err});
        } else {
          res.json(200, {friend_requests: result});
        }

        client.end();
      }); //  end Users.getAllFR
    }); //  end pg.connect
  })  //  end .get
  .post(function(req, res) {
    pg.connect(db, function(err, client, done) {
      if (err) {
        return res.json(500, {error: err});
      }

      var user_id = req.body.user_id;
      var requested_id = req.body.requested_id;

      //  verify that the user exists
      api.get('/users/' + user_id, function(err, result, statusCode) {
        if (!err && result && statusCode === 200) {

          //  verify that the requested friend exists
          api.get('/users/' + requested_id, function(err, result, statusCode) {
            if (!err && result && statusCode === 200) {

              //  verify that the users aren't already friends
              api.getWithParams('/friends/' + user_id, {friend_id: requested_id}, function(err, result, statusCode) {
                if (!err && result && statusCode === 404) {

                  Users.requestFriend(client, user_id, requested_id, function(err, result) {
                    done();

                    if (err) {
                      res.json(500, {error: err});
                    } else {
                      res.json(201, {result: "User " + user_id + " has requested " + requested_id});
                    }

                    client.end();
                  }); //  end Users.request

                } else if (!err) {
                  return res.json(statusCode, {error: "users are already friends!"});
                } else {
                  return res.json(statusCode, {error: err});
                }
              }); //  end api.get friends/;id

            } else if (!err) {
              return res.json(statusCode, result);
            } else {
              return res.json(statusCode, {error: err});
            }
          }); //  end api.get requested id

        } else if (!err) {
          return res.json(statusCode, result);
        } else {
          return res.json(statusCode, {error: err})
        }
      }); //  end api.get user id

    }); //  end pg.connect
  })  //  end .post

requests.route('/:requested_id')
  .get(function(req, res) {
    pg.connect(db, function(err, client, done) {
      if (err) {
        return res.json(500, {error: err});
      }

      var user_id = req.body.user_id;
      var requested_id = req.params.requested_id;
      Users.getFriendRequest(client, user_id, requested_id, function(err, result) {
        done();

        if (!err && result.length > 0) {
          res.json(200, {request: result});
        } else if (!err) {
          res.json(404, {error: "user " + user_id + " has not requested " + requested_id});
        } else {
          res.json(500, {error: err});
        }

        client.end();
      }); //  end .getFriendReq
    }); //  end pg.connect
  });

module.exports = requests;

<commit_msg>add get all requests for user route<commit_after>var express = require('express');
var requests = express.Router();
var pg = require('pg');
var db = require('../db');
var Users = require('../models/User');
var api = require('../models/api');

requests.route('/')
  .get(function(req, res) {
    pg.connect(db, function(err, client, done) {
      if (err) {
        return res.json(500, {error: err});
      }

      Users.getAllFriendRequests(client, function(err, result) {
        done();

        if (err) {
          res.json(500, {error: err});
        } else {
          res.json(200, {friend_requests: result});
        }

        client.end();
      }); //  end Users.getAllFR
    }); //  end pg.connect
  })  //  end .get
  .post(function(req, res) {
    pg.connect(db, function(err, client, done) {
      if (err) {
        return res.json(500, {error: err});
      }

      var user_id = req.body.user_id;
      var requested_id = req.body.requested_id;

      //  verify that the user exists
      api.get('/users/' + user_id, function(err, result, statusCode) {
        if (!err && result && statusCode === 200) {

          //  verify that the requested friend exists
          api.get('/users/' + requested_id, function(err, result, statusCode) {
            if (!err && result && statusCode === 200) {

              //  verify that the users aren't already friends
              api.getWithParams('/friends/' + user_id, {friend_id: requested_id}, function(err, result, statusCode) {
                if (!err && result && statusCode === 404) {

                  Users.requestFriend(client, user_id, requested_id, function(err, result) {
                    done();

                    if (err) {
                      res.json(500, {error: err});
                    } else {
                      res.json(201, {result: "User " + user_id + " has requested " + requested_id});
                    }

                    client.end();
                  }); //  end Users.request

                } else if (!err) {
                  return res.json(statusCode, {error: "users are already friends!"});
                } else {
                  return res.json(statusCode, {error: err});
                }
              }); //  end api.get friends/;id

            } else if (!err) {
              return res.json(statusCode, result);
            } else {
              return res.json(statusCode, {error: err});
            }
          }); //  end api.get requested id

        } else if (!err) {
          return res.json(statusCode, result);
        } else {
          return res.json(statusCode, {error: err})
        }
      }); //  end api.get user id

    }); //  end pg.connect
  })  //  end .post

requests.route('/:requested_id')
  .get(function(req, res) {
    pg.connect(db, function(err, client, done) {
      if (err) {
        return res.json(500, {error: err});
      }

      var requested_id = req.params.requested_id;

      if (req.body.user_id) {
        user_id = req.body.user_id;
        Users.getFriendRequest(client, user_id, requested_id, function(err, result) {
          done();

          if (!err && result.length > 0) {
            res.json(200, {pending_requests: result});
          } else if (!err) {
            res.json(404, {error: "user " + user_id + " has not requested " + requested_id});
          } else {
            res.json(500, {error: err});
          }

          client.end();
        }); //  end .getFriendReq
      } else {
        Users.getPendingRequestsForUser(client, requested_id, function(err, result) {
          done();

          if (!err && result.length > 0) {
            res.json(200, {pending_requests: result});
          } else if (!err) {
            res.json(404, {error: "user " + requested_id + " has not been requested"});
          } else {
            res.json(500, {error: err});
          }

          client.end();
        })
      }

    }); //  end pg.connect
  });

module.exports = requests;

<|endoftext|>


<commit_before>var config = require('config');
const tokenizer = require('string-tokenizer')

var genUUID = function () {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
};

Slack = require('node-slackr');

var postDynamoDB = function (data) {
  var awsCredentials = config.get('timeburn.aws.credentials');
  var ddb = {
    tableName: config.get('timeburn.aws.dynamo.tablename')
  };
  var DynamoDB = require('aws-dynamodb')(awsCredentials);

  DynamoDB
    .table(ddb.tableName)
    .insert({
      ID: data.ID,
      UserName: data.userName,
      Thing: data.text,
      Duration: data.duration,
      CreatedDateTime: data.isodate
    }, function (err, data) {
      console.log(err, data)
    });
};

var postGDoc = function (data) {

  var Spreadsheet = require('edit-google-spreadsheet');

  Spreadsheet.load({
    debug: true,
    spreadsheetId: config.get('timeburn.google.spreadsheetId'),
    worksheetId: config.get('timeburn.google.worksheetId'),

    "oauth2": config.get('timeburn.google.oauth2')

  }, function sheetReady(err, spreadsheet) {
    if (err) throw err;

    spreadsheet.receive(function (err, rows, info) {
      if (err) throw err;
      var rowNum = info.lastRow + 1;
      console.log('Next Row Num is: ' + rowNum);

      var obj = {};
      obj[rowNum] = [[data.userName, data.text, data.duration, data.gdocDate, data.ID]];
      console.log(obj);
      spreadsheet.add(obj);
      spreadsheet.send(function (err) {
        if (err) throw err;
      });
    });
  });
};

const commandParser = function (commandText) {
  const tokens = tokenizer()
    .input(commandText)
    .token('duration', /[1-9][0-9]*/)
    .resolve();

  return {
    thing: commandText.substr(0, commandText.length-tokens.duration.length),
    duration: tokens.duration
  }
}

module.exports = function (router) {
  router.post('/timeburn', function (req, res) {

    var slackWebhookUrl = config.get('timeburn.slack.url');
    var slackToken = config.get('timeburn.slack.token');
    var originChannelName = req.body.channel_name;
    //console.log("REQUEST: \n" + JSON.stringify(req.body));
    //console.log("Origin Channel: " + originChannelName);

    var format = require('date-format');
    var timestamp = new Date();

    const { thing, duration } = commandParser(req.body.text);

    var data = {
      token: req.body.token,
      ID: genUUID(),
      userName: req.body.user_name,
      cmd: req.body.command,
      text: thing,
      duration: duration,
      isodate: timestamp.toISOString(),
      gdocDate: format.asString('MM/dd/yyyy hh:mm:ss', timestamp)
    };

    //console.log("TOKEN: " + token);
    //console.log("USER: " + userName);
    //console.log("CMD: " + cmd);
    //console.log("TEXT: " + text);

    // Check that the slack token is valid.
    if (data.token != slackToken) {
      res.sendStatus(403);
      res.end();
    }

    // Check for empty string passed in.
    if (!data.text || data.text.trim().length === 0) {
      res.send('Your timeburn thing appears to be empty. Be timeburn and try again.');
      res.end();
    } else {

      // get the channel where the command was called from.
      var postOriginChannel = '';
      if (originChannelName != 'privategroup') {
        postOriginChannel = ['#', originChannelName].join('');
      }

      // Get the target channel name
      var channels = config.get('timeburn.slack.post_channel');
      // If the name of the target channel is different than the origin, post to both channels.
      if (postOriginChannel != channels) {
        channels = [config.get('timeburn.slack.post_channel'), postOriginChannel];
      }

      slack = new Slack(slackWebhookUrl, {
        username: config.get('timeburn.slack.post_username'),
        channel: channels,
        icon_emoji: config.get('timeburn.slack.post_emoji')
      });

      var message = {
        text: "*TimeBurn | " + data.userName + "*\n" + data.text
      };

      if (data.cmd === '/timeburn') {

        if (config.timeburn.aws.enabled) {
          postDynamoDB(data);
        }
        if (config.timeburn.google.enabled) {
          postGDoc(data);
        }

        slack.notify(message);
        res.send('Sucessfully recorded that you spent ${data.duration} minutes on ${data.text}.');
      } else {
        res.end();
      }
    }
  });
};

<commit_msg>fixed string formatting<commit_after>var config = require('config');
const tokenizer = require('string-tokenizer')

var genUUID = function () {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
};

Slack = require('node-slackr');

var postDynamoDB = function (data) {
  var awsCredentials = config.get('timeburn.aws.credentials');
  var ddb = {
    tableName: config.get('timeburn.aws.dynamo.tablename')
  };
  var DynamoDB = require('aws-dynamodb')(awsCredentials);

  DynamoDB
    .table(ddb.tableName)
    .insert({
      ID: data.ID,
      UserName: data.userName,
      Thing: data.text,
      Duration: data.duration,
      CreatedDateTime: data.isodate
    }, function (err, data) {
      console.log(err, data)
    });
};

var postGDoc = function (data) {

  var Spreadsheet = require('edit-google-spreadsheet');

  Spreadsheet.load({
    debug: true,
    spreadsheetId: config.get('timeburn.google.spreadsheetId'),
    worksheetId: config.get('timeburn.google.worksheetId'),

    "oauth2": config.get('timeburn.google.oauth2')

  }, function sheetReady(err, spreadsheet) {
    if (err) throw err;

    spreadsheet.receive(function (err, rows, info) {
      if (err) throw err;
      var rowNum = info.lastRow + 1;
      console.log('Next Row Num is: ' + rowNum);

      var obj = {};
      obj[rowNum] = [[data.userName, data.text, data.duration, data.gdocDate, data.ID]];
      console.log(obj);
      spreadsheet.add(obj);
      spreadsheet.send(function (err) {
        if (err) throw err;
      });
    });
  });
};

const commandParser = function (commandText) {
  const tokens = tokenizer()
    .input(commandText)
    .token('duration', /[1-9][0-9]*/)
    .resolve();

  return {
    thing: commandText.substr(0, commandText.length-tokens.duration.length),
    duration: tokens.duration
  }
}

module.exports = function (router) {
  router.post('/timeburn', function (req, res) {

    var slackWebhookUrl = config.get('timeburn.slack.url');
    var slackToken = config.get('timeburn.slack.token');
    var originChannelName = req.body.channel_name;
    //console.log("REQUEST: \n" + JSON.stringify(req.body));
    //console.log("Origin Channel: " + originChannelName);

    var format = require('date-format');
    var timestamp = new Date();

    const { thing, duration } = commandParser(req.body.text);

    var data = {
      token: req.body.token,
      ID: genUUID(),
      userName: req.body.user_name,
      cmd: req.body.command,
      text: thing,
      duration: duration,
      isodate: timestamp.toISOString(),
      gdocDate: format.asString('MM/dd/yyyy hh:mm:ss', timestamp)
    };

    // console.log("TOKEN: " + data.token);
    // console.log("USER: " + data.userName);
    // console.log("CMD: " + data.cmd);
    // console.log("THING: " + data.text);
    // console.log("DURATION: " + data.duration);

    // Check that the slack token is valid.
    if (data.token != slackToken) {
      res.sendStatus(403);
      res.end();
    }

    // Check for empty string passed in.
    if (!data.text || data.text.trim().length === 0) {
      res.send('Your timeburn thing appears to be empty. Be timeburn and try again.');
      res.end();
    } else {

      // get the channel where the command was called from.
      var postOriginChannel = '';
      if (originChannelName != 'privategroup') {
        postOriginChannel = ['#', originChannelName].join('');
      }

      // Get the target channel name
      var channels = config.get('timeburn.slack.post_channel');
      // If the name of the target channel is different than the origin, post to both channels.
      if (postOriginChannel != channels) {
        channels = [config.get('timeburn.slack.post_channel'), postOriginChannel];
      }

      slack = new Slack(slackWebhookUrl, {
        username: config.get('timeburn.slack.post_username'),
        channel: channels,
        icon_emoji: config.get('timeburn.slack.post_emoji')
      });

      var message = {
        text: "*TimeBurn | " + data.userName + "*\n" + data.text
      };

      if (data.cmd === '/timeburn') {

        if (config.timeburn.aws.enabled) {
          postDynamoDB(data);
        }
        if (config.timeburn.google.enabled) {
          postGDoc(data);
        }

        slack.notify(message);
        res.send('Successfully recorded that you spent ' + data.duration + ' minutes on ' + data.text + '.');
      } else {
        res.end();
      }
    }
  });
};

<|endoftext|>


<commit_before>import Ember from 'ember';

const {
  run,
  RSVP
} = Ember;

export default function makePromise(settings) {
  return new RSVP.Promise(function(resolve, reject) {
    settings.success = makeSuccess(resolve);
    settings.error = makeError(reject);
    Ember.$.ajax(settings);
  }, 'ember-ajax: ' + (settings.type || 'GET') + ' to ' + settings.url);
};

function makeSuccess(resolve) {
  return function(response, textStatus, jqXHR) {
    run(null, resolve, {
      response: response,
      textStatus: textStatus,
      jqXHR: jqXHR
    });
  }
}

function makeError(reject) {
  return function(jqXHR, textStatus, errorThrown) {
    run(null, reject, {
      jqXHR: jqXHR,
      textStatus: textStatus,
      errorThrown: errorThrown
    });
  };
}
<commit_msg>Minor style fixes<commit_after>import Ember from 'ember';

const {
  run,
  RSVP
} = Ember;

export default function makePromise(settings) {
  return new RSVP.Promise(function(resolve, reject) {
    settings.success = makeSuccess(resolve);
    settings.error = makeError(reject);
    Ember.$.ajax(settings);
  }, 'ember-ajax: ' + (settings.type || 'GET') + ' to ' + settings.url);
}

function makeSuccess(resolve) {
  return function(response, textStatus, jqXHR) {
    run(null, resolve, {
      response: response,
      textStatus: textStatus,
      jqXHR: jqXHR
    });
  };
}

function makeError(reject) {
  return function(jqXHR, textStatus, errorThrown) {
    run(null, reject, {
      jqXHR: jqXHR,
      textStatus: textStatus,
      errorThrown: errorThrown
    });
  };
}
<|endoftext|>


<commit_before>var db = require('../db.js');
var async = require('async');
var ObjectID = require('mongodb').ObjectID;

var getTrackerCollection = function() {
   return db.getDb().collection('tracker');
};

var insertTracker = function(tracker, userId, callback) {
    tracker.owner = userId;
    getTrackerCollection().insert(tracker, callback);
};

var updateTracker = function(trackerId, tracker, userId, callback) {
    tracker.owner = userId;
    getTrackerCollection().update({_id: trackerId}, { $set: tracker }, { upsert : true}, callback);
}

var isTrackerOwnedByUser = function(trackerId, userId, callback) {
    var cursor = getTrackerCollection().find({_id: trackerId, owner:userId});
    cursor.count(function(err, count) {
       callback(err, count > 0);
    });
}

var findTrackersByOwner = function(owner, callback) {
    var cursor = getTrackerCollection().find({owner: owner});
    cursor.sort(['name']).toArray(function(err, docs) {
        callback(err, docs);
    });
};

var findTrackersById = function(id, callback) {
    var cursor = getTrackerCollection().find({_id: id});
    cursor.nextObject(function(err, object) {
        callback(err, object);
    });
};

var deleteTrackersById = function(id, callback) {
    getTrackerCollection().remove({_id: id}, function(err, count) {
        callback(err, count);
    });
};

var deleteTrackersByOwner = function(owner, callback) {
    getTrackerCollection().remove({owner: owner}, function(err, count) {
        callback(err, count);
    });
};

module.exports = {
  trackers: {
    use: function (req, res, next) {
        if (req.isAuthenticated()) {
            next();
        } else {
            res.json(401, {message: 'not logged in'});
        }
    },
    get: function (req, res) {
        // delete entire collection associated with user

        findTrackersByOwner(req.user._id, function(err, trackers) {
            if (err) {
                res.json(500, "error: database error");
            } else {
                res.json(trackers);
            }
        });
    },
    put: function (req, res) {
        // replace entire collection of trackers associated with user

        async.series([
           function(callback) {
               deleteTrackersByOwner(req.user._id, callback);
        }, function(callback) {
            async.each(req.body, function(item, callback) {
                insertTracker(item, req.user._id, callback);
            }, function(err) {
                callback(err);
            });
        }], function(err) {
            if (err) {
                res.json(500, {message: "could not store trackers"})
            } else {
                res.json({});
            }
        });

    },
    post: function (req, res) {
        // create a new tracker and associated it with user
        insertTracker(req.body, req.user._id, function(err, tracker) {
            if (err) {
                res.json(500, {message: "could not store tracker"});
            } else {
                res.json(200, tracker);
            }
        });
    },
    delete : function (req, res) {
        // delete entire collection associated with user
        deleteTrackersByOwner(req.user._id, function(err, trackers) {
            if (err) {
                res.json(500, "error: database error");
            } else {
                res.json({});
            }
        });
    },
    ":id": {
      get: function (req, res) {
          findTrackersById(req.params.id, function(err, tracker) {
            if (err) {
                 res.json(500, {message: "could not get tracker"});
             } else {
                 if (tracker == null) {
                     res.json(404, { message: "tracker not found"});
                 } else {
                     if (req.user._id.equals(tracker.owner)) {
                         res.json(tracker);
                     } else {
                         res.json(401, { message: "permission denied"});
                     }
                 }
             }
          });
      },
      put: function (req, res) {
          // Replace " + req.params.id + ", or if it doesn't exist, create it.
          findTrackersById(req.params.id, function(err, tracker) {
              if (err) {
                  res.json(500, {message: "could not get tracker"});
              } else {
                  if (tracker === null || req.user._id.equals(tracker.owner)) {
                      updateTracker(req.params.id, req.body, req.user._id, function(err) {
                          if (err) {
                              res.json(500, {message: "could not update tracker"});
                          } else {
                              res.json({});
                          }
                      });
                  } else {
                      res.json(401, { message: "permission denied"});
                  }
              }
          });

      },
      delete: {
        handler: function (req, res) {
            // Delete " + req.params.id
            findTrackersById(req.params.id, function(err, tracker) {
                if (err) {
                    res.json(500, { message: "could not get tracker"} );
                } else {
                    if (tracker === null) {
                        res.json(404, { message: "tracker not found"});
                    } else if (req.user._id.equals(tracker.owner)) {
                        deleteTrackersById(tracker._id, function(err) {
                           if (err) {
                               res.json(500, { message: "could not delete tracker"} );
                           } else {
                               res.json({});
                           }
                        });
                    } else {
                        res.json(401, { message: "permission denied"});
                    }
                }
            });
        }
      }
    }
  }

};
<commit_msg>Rename owner to user<commit_after>var db = require('../db.js');
var async = require('async');
var ObjectID = require('mongodb').ObjectID;

var getTrackerCollection = function() {
   return db.getDb().collection('tracker');
};

var insertTracker = function(tracker, userId, callback) {
    tracker.user = userId;
    getTrackerCollection().insert(tracker, callback);
};

var updateTracker = function(trackerId, tracker, userId, callback) {
    tracker.user = userId;
    getTrackerCollection().update({_id: trackerId}, { $set: tracker }, { upsert : true}, callback);
}

var isTrackerOwnedByUser = function(trackerId, userId, callback) {
    var cursor = getTrackerCollection().find({_id: trackerId, user:userId});
    cursor.count(function(err, count) {
       callback(err, count > 0);
    });
}

var findTrackersByUser = function(user, callback) {
    var cursor = getTrackerCollection().find({user: user});
    cursor.sort(['name']).toArray(function(err, docs) {
        callback(err, docs);
    });
};

var findTrackersById = function(id, callback) {
    var cursor = getTrackerCollection().find({_id: id});
    cursor.nextObject(function(err, object) {
        callback(err, object);
    });
};

var deleteTrackersById = function(id, callback) {
    getTrackerCollection().remove({_id: id}, function(err, count) {
        callback(err, count);
    });
};

var deleteTrackersByUser = function(user, callback) {
    getTrackerCollection().remove({user: user}, function(err, count) {
        callback(err, count);
    });
};

module.exports = {
  trackers: {
    use: function (req, res, next) {
        if (req.isAuthenticated()) {
            next();
        } else {
            res.json(401, {message: 'not logged in'});
        }
    },
    get: function (req, res) {
        // delete entire collection associated with user

        findTrackersByUser(req.user._id, function(err, trackers) {
            if (err) {
                res.json(500, "error: database error");
            } else {
                res.json(trackers);
            }
        });
    },
    put: function (req, res) {
        // replace entire collection of trackers associated with user

        async.series([
           function(callback) {
               deleteTrackersByUser(req.user._id, callback);
        }, function(callback) {
            async.each(req.body, function(item, callback) {
                insertTracker(item, req.user._id, callback);
            }, function(err) {
                callback(err);
            });
        }], function(err) {
            if (err) {
                res.json(500, {message: "could not store trackers"})
            } else {
                res.json({});
            }
        });

    },
    post: function (req, res) {
        // create a new tracker and associated it with user
        insertTracker(req.body, req.user._id, function(err, tracker) {
            if (err) {
                res.json(500, {message: "could not store tracker"});
            } else {
                res.json(200, tracker);
            }
        });
    },
    delete : function (req, res) {
        // delete entire collection associated with user
        deleteTrackersByUser(req.user._id, function(err, trackers) {
            if (err) {
                res.json(500, "error: database error");
            } else {
                res.json({});
            }
        });
    },
    ":id": {
      get: function (req, res) {
          findTrackersById(req.params.id, function(err, tracker) {
            if (err) {
                 res.json(500, {message: "could not get tracker"});
             } else {
                 if (tracker == null) {
                     res.json(404, { message: "tracker not found"});
                 } else {
                     if (req.user._id.equals(tracker.user)) {
                         res.json(tracker);
                     } else {
                         res.json(401, { message: "permission denied"});
                     }
                 }
             }
          });
      },
      put: function (req, res) {
          // Replace " + req.params.id + ", or if it doesn't exist, create it.
          findTrackersById(req.params.id, function(err, tracker) {
              if (err) {
                  res.json(500, {message: "could not get tracker"});
              } else {
                  if (tracker === null || req.user._id.equals(tracker.user)) {
                      updateTracker(req.params.id, req.body, req.user._id, function(err) {
                          if (err) {
                              res.json(500, {message: "could not update tracker"});
                          } else {
                              res.json({});
                          }
                      });
                  } else {
                      res.json(401, { message: "permission denied"});
                  }
              }
          });

      },
      delete: {
        handler: function (req, res) {
            // Delete " + req.params.id
            findTrackersById(req.params.id, function(err, tracker) {
                if (err) {
                    res.json(500, { message: "could not get tracker"} );
                } else {
                    if (tracker === null) {
                        res.json(404, { message: "tracker not found"});
                    } else if (req.user._id.equals(tracker.user)) {
                        deleteTrackersById(tracker._id, function(err) {
                           if (err) {
                               res.json(500, { message: "could not delete tracker"} );
                           } else {
                               res.json({});
                           }
                        });
                    } else {
                        res.json(401, { message: "permission denied"});
                    }
                }
            });
        }
      }
    }
  }

};
<|endoftext|>