<commit_before>'use strict';

// # Cellar storage module for Ghost blog http://ghost.org/
const fs = require('fs');
const path = require('path');
const Bluebird = require('bluebird');
const AWS = require('aws-sdk-promise');
const moment = require('moment');
const readFileAsync = Bluebird.promisify(fs.readFile);
let options = {};
let client = null;

function CellarStore(config) {
    options = config;
    if(validOptions(config)){
        client =  new AWS.S3({
            accessKeyId: config.accessKeyId,
            secretAccessKey: config.secretAccessKey,
            bucket: config.bucket,
            signatureVersion: 'v2',
            endpoint: new AWS.Endpoint(config.host)
        })
    }
}

function validOptions(opts) {
    return (opts.accessKeyId &&
        opts.secretAccessKey &&
        opts.bucket &&
        opts.host);
}

 /**
 * Return the URL where image assets can be read.
 * @param  {String} bucket [Cellar bucket name]
 * @return {String}        [path-style URL of the Cellar bucket]
 */
function getCellarPath(bucket) {
    var cellarPath = 'https://' + options.bucket + '.' + options.host + '/';
    return cellarPath;
}

function logError(error) {
    console.log('error in ghost-cellar', error);
};

function logInfo(info) {
    console.log('info in ghost-cellar', info);
};

function getTargetDir() {
    var now = moment();
    return now.format('YYYY/MM/');
};

function getTargetName(image, targetDir) {
    var ext = path.extname(image.name);
    var name = path.basename(image.name, ext).replace(/\W/g, '_');

    return targetDir + name + '-' + Date.now() + ext;
};

CellarStore.prototype.save = function(image) {
    if (client === null) {
      return Bluebird.reject('ghost-cellar is not configured');
    }

    var targetDir = getTargetDir();
    var targetFilename = getTargetName(image, targetDir);

    return readFileAsync(image.path)
        .then(function(buffer) {
            var params = {
                ACL: 'public-read',
                Bucket: options.bucket,
                Key: targetFilename,
                Body: buffer,
                ContentType: image.type,
                CacheControl: 'max-age=' + (1000 * 365 * 24 * 60 * 60) // 365 days
            };

            return client.putObject(params).promise();
        })
        .tap(function() {
            logInfo('ghost-cellar', 'Temp uploaded file path: ' + image.path);
        })
        .then(function(results) {
            var cellarPath = getCellarPath(options.bucket);
            return Bluebird.resolve(cellarPath + targetFilename);
        })
        .catch(function(err) {
            logError(err);
            throw err;
        });
};

// middleware for serving the files
CellarStore.prototype.serve = function() {

    return function (req, res, next) {
        var params = {
            Bucket: options.bucket,
            Key: req.path.replace(/^\//, '')
        };

        client.getObject(params)
            .on('httpHeaders', function(statusCode, headers, response) {
                res.set(headers);
            })
            .createReadStream()
            .on('error', function(err) {
                logError(err);
                res.status(404);
                next();
            })
            .pipe(res);
    };
};

module.exports = CellarStore;
<commit_msg>Migrate cellar storage driver to ghost@0.10 compat<commit_after>'use strict';

// # Cellar storage module for Ghost blog http://ghost.org/
const fs = require('fs');
const path = require('path');
const Bluebird = require('bluebird');
const AWS = require('aws-sdk-promise');
const moment = require('moment');
const util = require('util');
const baseStore = require('ghost/core/server/storage/base');

const readFileAsync = Bluebird.promisify(fs.readFile);
let options = {};
let client = null;

function CellarStore(config) {
    options = config;
    if(validOptions(config)){
        client =  new AWS.S3({
            accessKeyId: config.accessKeyId,
            secretAccessKey: config.secretAccessKey,
            bucket: config.bucket,
            signatureVersion: 'v2',
            endpoint: new AWS.Endpoint(config.host)
        })
    }
}

util.inherits(HTTPStore, baseStore);

function validOptions(opts) {
    return (opts.accessKeyId &&
        opts.secretAccessKey &&
        opts.bucket &&
        opts.host);
}

 /**
 * Return the URL where image assets can be read.
 * @param  {String} bucket [Cellar bucket name]
 * @return {String}        [path-style URL of the Cellar bucket]
 */
function getCellarPath(bucket) {
    var cellarPath = 'https://' + options.bucket + '.' + options.host + '/';
    return cellarPath;
}

function logError(error) {
    console.log('error in ghost-cellar', error);
};

function logInfo(info) {
    console.log('info in ghost-cellar', info);
};

function getTargetDir() {
    var now = moment();
    return now.format('YYYY/MM/');
};

function getTargetName(image, targetDir) {
    var ext = path.extname(image.name);
    var name = path.basename(image.name, ext).replace(/\W/g, '_');

    return targetDir + name + '-' + Date.now() + ext;
};

CellarStore.prototype.save = function(image) {
    if (client === null) {
      return Bluebird.reject('ghost-cellar is not configured');
    }

    var targetDir = getTargetDir();
    var targetFilename = getTargetName(image, targetDir);

    return readFileAsync(image.path)
        .then(function(buffer) {
            var params = {
                ACL: 'public-read',
                Bucket: options.bucket,
                Key: targetFilename,
                Body: buffer,
                ContentType: image.type,
                CacheControl: 'max-age=' + (1000 * 365 * 24 * 60 * 60) // 365 days
            };

            return client.putObject(params).promise();
        })
        .tap(function() {
            logInfo('ghost-cellar', 'Temp uploaded file path: ' + image.path);
        })
        .then(function(results) {
            var cellarPath = getCellarPath(options.bucket);
            return Bluebird.resolve(cellarPath + targetFilename);
        })
        .catch(function(err) {
            logError(err);
            throw err;
        });
};

// middleware for serving the files
CellarStore.prototype.serve = function() {

    return function (req, res, next) {
        var params = {
            Bucket: options.bucket,
            Key: req.path.replace(/^\//, '')
        };

        client.getObject(params)
            .on('httpHeaders', function(statusCode, headers, response) {
                res.set(headers);
            })
            .createReadStream()
            .on('error', function(err) {
                logError(err);
                res.status(404);
                next();
            })
            .pipe(res);
    };
};

module.exports = CellarStore;
<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

const pck = require('./package');
const path = require('path');
const SERVER_NAME = 'highcharts-convert';
const SERVER_SCRIPT_PATH = path.join(__dirname, 'lib', SERVER_NAME + '.js');
const DEFAULT_HOSTNAME = '127.0.0.1';
const DEFAULT_PORT = 3030;

var args = require('yargs')
  .usage(`Usage: ${pck.name} start [-h HOST][-p PORT] -- [options]`)
  .command('start', 'Starts highcharts-convert HTTP server')
  .alias('h', 'hostname')
  .alias('h', 'host')
  .describe('h', 'Hostname of the server')
  .alias('p', 'port')
  .describe('p', 'Port the server will listen on')
  .default({
    p: DEFAULT_PORT,
    h: DEFAULT_HOSTNAME
  })
  .check((argv) => {
    if (!argv._[0] || !argv._[0].match(/start/)) {
      throw new Error('Missing or invalid <command>');
    }
    return true;
  })
  .help('help')
  .showHelpOnFail(false, `Try ${SERVER_NAME} --help for available options`)
  .version(() => pck.version).argv;

const winston = require('winston');
const spawn = require('child_process').spawn;
const phantomjs = require('phantomjs-prebuilt');

var logger = new winston.Logger({
  transports: [
    new winston.transports.Console({
      colorize: true,
      label: SERVER_NAME
    })
  ]
});
logger.cli();

function exitProcess(signal) {
  return () => {
    server.kill(signal);
    logger.warn('Terminating converter (received %s)', signal);
    return process.exit(0);
  };
}

var childArgs = [SERVER_SCRIPT_PATH]
  .concat(['-port', args.p, '-host', args.h])
  .concat(args._);

var server = spawn(phantomjs.path, childArgs, { stdio: 'inherit' });
logger.info('Started converter on %s:%s (PID: %s)', args.h, args.p, server.pid);

server.on('error', (err) => logger.error('Failed to start [%s]', SERVER_NAME, err));

server.on('close', (code) => logger.info('Converter exited successfully (code: %s)', code || server.exitCode || 0));

process.once('SIGINT', exitProcess('SIGINT'));
process.once('SIGTERM', exitProcess('SIGTERM'));
<commit_msg>Made a version of server.js that doesn't require a start argument, so that I can use it with pm2 on a server and have it daemonized and running in the background with log rotation and all that good stuff.<commit_after>#!/usr/bin/env node

'use strict';

const pck = require('./package');
const path = require('path');
const SERVER_NAME = 'highcharts-convert';
const SERVER_SCRIPT_PATH = path.join(__dirname, 'lib', SERVER_NAME + '.js');
const DEFAULT_HOSTNAME = '127.0.0.1';
const DEFAULT_PORT = 3030;

var args = require('yargs')
  .usage(`Usage: ${pck.name} start [-h HOST][-p PORT] -- [options]`)
  .command('start', 'Starts highcharts-convert HTTP server')
  .alias('h', 'hostname')
  .alias('h', 'host')
  .describe('h', 'Hostname of the server')
  .alias('p', 'port')
  .describe('p', 'Port the server will listen on')
  .default({
    p: DEFAULT_PORT,
    h: DEFAULT_HOSTNAME
  })
  .check((argv) => {
    if (!argv._[0] || !argv._[0].match(/start/)) {
      argv._[0] = 'start'
}
    return true;
  })
  .help('help')
  .showHelpOnFail(false, `Try ${SERVER_NAME} --help for available options`)
  .version(() => pck.version).argv;

const winston = require('winston');
const spawn = require('child_process').spawn;
const phantomjs = require('phantomjs-prebuilt');

var logger = new winston.Logger({
  transports: [
    new winston.transports.Console({
      colorize: true,
      label: SERVER_NAME
    })
  ]
});
logger.cli();

function exitProcess(signal) {
  return () => {
    server.kill(signal);
    logger.warn('Terminating converter (received %s)', signal);
    return process.exit(0);
  };
}

var childArgs = [SERVER_SCRIPT_PATH]
  .concat(['-port', args.p, '-host', args.h])
  .concat(args._);

var server = spawn(phantomjs.path, childArgs, { stdio: 'inherit' });
logger.info('Started converter on %s:%s (PID: %s)', args.h, args.p, server.pid);

server.on('error', (err) => logger.error('Failed to start [%s]', SERVER_NAME, err));

server.on('close', (code) => logger.info('Converter exited successfully (code: %s)', code || server.exitCode || 0));

process.once('SIGINT', exitProcess('SIGINT'));
process.once('SIGTERM', exitProcess('SIGTERM'));
<|endoftext|>


<commit_before>import Koa from 'koa'
import Router from 'koa-router'
import render from 'koa-ejs'
import logger from 'koa-logger'
import parser from 'koa-bodyparser'
import path from 'path'
import co from 'co'
import authsvc from './authsvc/transport.js'
import mongoose from './common/database.js'
import errors from './modules/errors.js'

const PORT = process.env.PORT
const app = new Koa()

render(app, {
  root: path.join(__dirname, 'view'),
  layout: 'template',
  viewExt: 'html',
  cache: false,
  debug: true
})
app.context.render = co.wrap(app.context.render)

app
.use(errors())
.use(logger())
.use(parser())
.use(authsvc.routes())
.use(authsvc.allowedMethods())

// Catch-All Route
app.use(async (ctx, next) => {
  await ctx.render('home', {
    title: 'Hello'
  })
})

app.listen(PORT, () => {
  console.log(`listening to port *:${PORT}.\npress ctrl + c to cancel.`)
})

export default app
<commit_msg>Update server.js<commit_after>import Koa from 'koa'
import Router from 'koa-router'
import render from 'koa-ejs'
import logger from 'koa-logger'
import parser from 'koa-bodyparser'
import path from 'path'
import co from 'co'
import authService from './authService/transport.js'
import mongoose from './common/database.js'
import errors from './modules/errors.js'

const PORT = process.env.PORT
const app = new Koa()

render(app, {
  root: path.join(__dirname, 'view'),
  layout: 'template',
  viewExt: 'html',
  cache: false,
  debug: true
})
app.context.render = co.wrap(app.context.render)

app
.use(errors())
.use(logger())
.use(parser())
.use(authService.routes())
.use(authService.allowedMethods())

// Catch-All Route
app.use(async (ctx, next) => {
  await ctx.render('home', {
    title: 'Hello'
  })
})

app.listen(PORT, () => {
  console.log(`listening to port *:${PORT}.\npress ctrl + c to cancel.`)
})

export default app
<|endoftext|>


<commit_before>'use strict'

const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')

var rules = require('./rules')

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000

var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

slapp.message('start', ['mention', 'direct_message'], (msg) => {
  msg.say(rules.start_text)
})

slapp.message('^read <([^>]+)>', (msg, text, entry) => {
  // text = 'play artist spotify:track:1yJiE307EBIzOB9kqH1deb'
  // type = 'artist'
  // toplay = 'spotify:track:1yJiE307EBIzOB9kqH1deb'
  msg.say('You want to read ${entry}')
})

// var HELP_TEXT = `
// I will respond to the following messages:
// \`help\` - to see this message.
// \`hi\` - to demonstrate a conversation that tracks state.
// \`thanks\` - to demonstrate a simple response.
// \`<type-any-other-text>\` - to demonstrate a random emoticon response, some of the time :wink:.
// \`attachment\` - to see a Slack attachment message.
// `

// //*********************************************
// // Setup different handlers for messages
// //*********************************************

// // response to the user typing "help"
// slapp.message('help', ['mention', 'direct_message'], (msg) => {
//   msg.say(HELP_TEXT)
// })

// // "Conversation" flow that tracks state - kicks off when user says hi, hello or hey
// slapp
//   .message('^(hi|hello|hey)$', ['direct_mention', 'direct_message'], (msg, text) => {
//     msg
//       .say(`${text}, how are you?`)
//       // sends next event from user to this route, passing along state
//       .route('how-are-you', { greeting: text })
//   })
//   .route('how-are-you', (msg, state) => {
//     var text = (msg.body.event && msg.body.event.text) || ''

//     // user may not have typed text as their next action, ask again and re-route
//     if (!text) {
//       return msg
//         .say("Whoops, I'm still waiting to hear how you're doing.")
//         .say('How are you?')
//         .route('how-are-you', state)
//     }

//     // add their response to state
//     state.status = text

//     msg
//       .say(`Ok then. What's your favorite color?`)
//       .route('color', state)
//   })
//   .route('color', (msg, state) => {
//     var text = (msg.body.event && msg.body.event.text) || ''

//     // user may not have typed text as their next action, ask again and re-route
//     if (!text) {
//       return msg
//         .say("I'm eagerly awaiting to hear your favorite color.")
//         .route('color', state)
//     }

//     // add their response to state
//     state.color = text

//     msg
//       .say('Thanks for sharing.')
//       .say(`Here's what you've told me so far: \`\`\`${JSON.stringify(state)}\`\`\``)
//     // At this point, since we don't route anywhere, the "conversation" is over
//   })

// // Can use a regex as well
// slapp.message(/^(thanks|thank you)/i, ['mention', 'direct_message'], (msg) => {
//   // You can provide a list of responses, and a random one will be chosen
//   // You can also include slack emoji in your responses
//   msg.say([
//     "You're welcome :smile:",
//     'You bet',
//     ':+1: Of course',
//     'Anytime :sun_with_face: :full_moon_with_face:'
//   ])
// })

// // demonstrate returning an attachment...
// slapp.message('attachment', ['mention', 'direct_message'], (msg) => {
//   msg.say({
//     text: 'Check out this amazing attachment! :confetti_ball: ',
//     attachments: [{
//       text: 'Slapp is a robust open source library that sits on top of the Slack APIs',
//       title: 'Slapp Library - Open Source',
//       image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
//       title_link: 'https://beepboophq.com/',
//       color: '#7CD197'
//     }]
//   })
// })

// // Catch-all for any other responses not handled above
// slapp.message('.*', ['direct_mention', 'direct_message'], (msg) => {
//   // respond only 40% of the time
//   if (Math.random() < 0.4) {
//     msg.say([':wave:', ':pray:', ':raised_hands:'])
//   }
// })

// slapp.command('/choose', '(.*)', (msg, choice) => {
//   // `respond` is used for actions or commands and uses the `response_url` provided by the
//   // incoming request from Slack
//   msg.respond(choice)
// })

// attach Slapp to express server
var server = slapp.attachToExpress(express())

// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})
<commit_msg>Adding type to params.<commit_after>'use strict'

const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')

var rules = require('./rules')

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000

var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

slapp.message('start', ['mention', 'direct_message'], (msg) => {
  msg.say(rules.start_text)
})

slapp.message('^read <([^>]+)>', (msg, text, type, entry) => {
  // text = 'play artist spotify:track:1yJiE307EBIzOB9kqH1deb'
  // type = 'artist'
  // toplay = 'spotify:track:1yJiE307EBIzOB9kqH1deb'
  msg.say('You want to read ${entry}')
})

// var HELP_TEXT = `
// I will respond to the following messages:
// \`help\` - to see this message.
// \`hi\` - to demonstrate a conversation that tracks state.
// \`thanks\` - to demonstrate a simple response.
// \`<type-any-other-text>\` - to demonstrate a random emoticon response, some of the time :wink:.
// \`attachment\` - to see a Slack attachment message.
// `

// //*********************************************
// // Setup different handlers for messages
// //*********************************************

// // response to the user typing "help"
// slapp.message('help', ['mention', 'direct_message'], (msg) => {
//   msg.say(HELP_TEXT)
// })

// // "Conversation" flow that tracks state - kicks off when user says hi, hello or hey
// slapp
//   .message('^(hi|hello|hey)$', ['direct_mention', 'direct_message'], (msg, text) => {
//     msg
//       .say(`${text}, how are you?`)
//       // sends next event from user to this route, passing along state
//       .route('how-are-you', { greeting: text })
//   })
//   .route('how-are-you', (msg, state) => {
//     var text = (msg.body.event && msg.body.event.text) || ''

//     // user may not have typed text as their next action, ask again and re-route
//     if (!text) {
//       return msg
//         .say("Whoops, I'm still waiting to hear how you're doing.")
//         .say('How are you?')
//         .route('how-are-you', state)
//     }

//     // add their response to state
//     state.status = text

//     msg
//       .say(`Ok then. What's your favorite color?`)
//       .route('color', state)
//   })
//   .route('color', (msg, state) => {
//     var text = (msg.body.event && msg.body.event.text) || ''

//     // user may not have typed text as their next action, ask again and re-route
//     if (!text) {
//       return msg
//         .say("I'm eagerly awaiting to hear your favorite color.")
//         .route('color', state)
//     }

//     // add their response to state
//     state.color = text

//     msg
//       .say('Thanks for sharing.')
//       .say(`Here's what you've told me so far: \`\`\`${JSON.stringify(state)}\`\`\``)
//     // At this point, since we don't route anywhere, the "conversation" is over
//   })

// // Can use a regex as well
// slapp.message(/^(thanks|thank you)/i, ['mention', 'direct_message'], (msg) => {
//   // You can provide a list of responses, and a random one will be chosen
//   // You can also include slack emoji in your responses
//   msg.say([
//     "You're welcome :smile:",
//     'You bet',
//     ':+1: Of course',
//     'Anytime :sun_with_face: :full_moon_with_face:'
//   ])
// })

// // demonstrate returning an attachment...
// slapp.message('attachment', ['mention', 'direct_message'], (msg) => {
//   msg.say({
//     text: 'Check out this amazing attachment! :confetti_ball: ',
//     attachments: [{
//       text: 'Slapp is a robust open source library that sits on top of the Slack APIs',
//       title: 'Slapp Library - Open Source',
//       image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
//       title_link: 'https://beepboophq.com/',
//       color: '#7CD197'
//     }]
//   })
// })

// // Catch-all for any other responses not handled above
// slapp.message('.*', ['direct_mention', 'direct_message'], (msg) => {
//   // respond only 40% of the time
//   if (Math.random() < 0.4) {
//     msg.say([':wave:', ':pray:', ':raised_hands:'])
//   }
// })

// slapp.command('/choose', '(.*)', (msg, choice) => {
//   // `respond` is used for actions or commands and uses the `response_url` provided by the
//   // incoming request from Slack
//   msg.respond(choice)
// })

// attach Slapp to express server
var server = slapp.attachToExpress(express())

// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})
<|endoftext|>


<commit_before>// .env[h
require('dotenv').config();

var express = require('express');
var app = express();
var Discord = require('discord.io');
var request = require('sync-request');

var bot = new Discord.Client({
	token: process.env.DISCORD_TOKEN,
	autorun: true
});

var targetUserList = ['ookamiwatari', 'whitebaku'];
var targetReportList = [];

// discordɐڑ
var discordReady = false;

// |[gXg擾郋[v
setInterval(getReportList, 5000);

app.get('/', function (req, res) {
  res.send('Hello, World!');
});

app.listen(process.env.PORT || 3000);

bot.on('ready', function() {
	console.log('Logged in as %s - %s\n', bot.username, bot.id);
	discordReady = true;
});

bot.on('message', function(user, userID, channelID, message, event) {

	if (channelID !== process.env.DISCORD_TARGET_CHANNEL) {
		return;
	}

	var messageArray = message.split(' ');

	if (messageArray.length < 2 || messageArray[0] !== 'logs') {
		return;
	}

	// user list̖߂ǉ
	// ToDo: 킩₷`悳
	if (messageArray[1] === 'user' && messageArray[2] === 'list' && messageArray.length == 3 ) {
		sendDiscord(targetUserList.join('\n'));
	}

	// user add *̖߂ǉ
	if (messageArray[1] === 'user' && messageArray[2] === 'add' && messageArray.length == 4 ) {

		// ̖O݂邩mF
		var url = 'https://www.fflogs.com/v1/reports/user/' + messageArray[3] + '?api_key=' + process.env.FFLOGS_PUBLIC_KEY;
		var response = request('GET', url);
		if (response.statusCode == 400) {
			var message = 'User \'' + messageArray[3] + '\' cannot be found.'
			sendDiscord(message);
			return;
		}

		// ɒǉĂꍇ
		if (targetUserList.indexOf(messageArray[3]) >=0 ) {
			var message = 'User \'' + messageArray[3] + '\' already exists.'
			sendDiscord(message);
			return;
		}

		// Xgɒǉ
		var message = 'User \'' + messageArray[3] + '\' was added successfully.'
		sendDiscord(message);
		targetUserList.push(messageArray[3]);
	}

	// user delete *̖߂ǉ
	if (messageArray[1] === 'user' && messageArray[2] === 'delete' && messageArray.length == 4 ) {

		// ̖O݂邩mF
		var index = targetUserList.indexOf(messageArray[3]);
		if (index >=0 ) {
			targetUserList.splice(index,1);
			var message = 'User \'' + messageArray[3] + '\' was deleted successfully.'
			sendDiscord(message);
			return;

		} else {
			// ݂Ȃꍇ
			var message = 'User \'' + messageArray[3] + '\' is undefined.'
			sendDiscord(message);
			return;
		}
	}

	// user delete ̖߂ǉ
	if (messageArray[1] === 'user' && messageArray[2] === 'delete' && messageArray.length == 3 ) {
		targetUserList = [];
		var message = 'UserList delete successfully.'
		sendDiscord(message);
		return;
	}

	// user list̖߂ǉ
	// ToDo: 킩₷`悳
	if (messageArray[1] === 'report' && messageArray[2] === 'list' && messageArray.length == 3 ) {
		sendDiscord(targetReportList.join('\n'));
	}

	// user add *̖߂ǉ
	if (messageArray[1] === 'report' && messageArray[2] === 'add' && messageArray.length == 4 ) {

		// ̖O݂邩mF
		var url = 'https://www.fflogs.com/v1/report/fights/' + messageArray[3] + '?api_key=' + process.env.FFLOGS_PUBLIC_KEY;
		var response = request('GET', url);
		if (response.statusCode == 400) {
			var message = 'Report \'' + messageArray[3] + '\' cannot be found.'
			sendDiscord(message);
			return;
		}

		// ɒǉĂꍇ
		if (targetReportList.indexOf(messageArray[3]) >=0 ) {
			var message = 'Report \'' + messageArray[3] + '\' already exists.'
			sendDiscord(message);
			return;
		}

		// Xgɒǉ
		var message = 'Report \'' + messageArray[3] + '\' was added successfully.'
		sendDiscord(message);
		targetReportList.push(messageArray[3]);
	}

	// user delete *̖߂ǉ
	if (messageArray[1] === 'report' && messageArray[2] === 'delete' && messageArray.length == 4 ) {

		// ̖O݂邩mF
		var index = targetReportList.indexOf(messageArray[3]);
		if (index >=0 ) {
			targetReportList.splice(index,1);
			var message = 'Report \'' + messageArray[3] + '\' was deleted successfully.'
			sendDiscord(message);
			return;

		} else {
			// ݂Ȃꍇ
			var message = 'Report \'' + messageArray[3] + '\' is undefined.'
			sendDiscord(message);
			return;
		}
	}

	// user delete ̖߂ǉ
	if (messageArray[1] === 'report' && messageArray[2] === 'delete' && messageArray.length == 3 ) {
		targetReportList = [];
		var message = 'ReportList delete successfully.'
		sendDiscord(message);
		return;
	}

});

function getReportList() {

	targetUserList.forEach(function(userName) {

		var url = 'https://www.fflogs.com/v1/reports/user/' + userName + '?api_key=' + process.env.FFLOGS_PUBLIC_KEY;
		var response = request('GET', url);
		var body = JSON.parse(response.body.toString());

		var lastReport = body[0];
		body.forEach(function(report) {
			if(lastReport.end < report.end) {
				lastReport = report;
			}
		});

		var index = targetReportList.indexOf(lastReport.id);
		if (index == -1) {
			targetReportList.push(lastReport.id);
			var message = 'Automatically added new report:\nhttps://ja.fflogs.com/reports/' + lastReport.id;
			sendDiscord(message);
		}

	});

}

function sendDiscord( message, channel){

	if(!discordReady) return;

	if(channel == undefined) channel = process.env.DISCORD_TARGET_CHANNEL
	bot.sendMessage({
		to: channel,
		message: message
	});
}<commit_msg>Add: envからユーザリストとレポートリストを取得するように変更<commit_after>// .env[h
require('dotenv').config();

var express = require('express');
var app = express();
var Discord = require('discord.io');
var request = require('sync-request');

var bot = new Discord.Client({
	token: process.env.DISCORD_TOKEN,
	autorun: true
});

// ϐ烆[UXg[h
var targetUserList = [];
if( process.env.DEFAULT_TARGET_USER_LIST ) targetUserList = (process.env.DEFAULT_TARGET_USER_LIST).split(",");

// ϐ烌|[gXg[h
var targetReportList = [];
if( process.env.DEFAULT_TARGET_REPORT_LIST ) targetReportList = (process.env.DEFAULT_TARGET_REPORT_LIST).split(",");

// discordɐڑ
var discordReady = false;

// |[gXg擾郋[v
setInterval(getReportList, 5000);

app.get('/', function (req, res) {
  res.send('Hello, World!');
});

app.listen(process.env.PORT || 3000);

bot.on('ready', function() {
	console.log('Logged in as %s - %s\n', bot.username, bot.id);
	discordReady = true;
});

bot.on('message', function(user, userID, channelID, message, event) {

	if (channelID !== process.env.DISCORD_TARGET_CHANNEL) {
		return;
	}

	var messageArray = message.split(' ');

	if (messageArray.length < 2 || messageArray[0] !== 'logs') {
		return;
	}

	// user list̖߂ǉ
	// ToDo: 킩₷`悳
	if (messageArray[1] === 'user' && messageArray[2] === 'list' && messageArray.length == 3 ) {
		sendDiscord(targetUserList.join('\n'));
	}

	// user add *̖߂ǉ
	if (messageArray[1] === 'user' && messageArray[2] === 'add' && messageArray.length == 4 ) {

		// ̖O݂邩mF
		var url = 'https://www.fflogs.com/v1/reports/user/' + messageArray[3] + '?api_key=' + process.env.FFLOGS_PUBLIC_KEY;
		var response = request('GET', url);
		if (response.statusCode == 400) {
			var message = 'User \'' + messageArray[3] + '\' cannot be found.'
			sendDiscord(message);
			return;
		}

		// ɒǉĂꍇ
		if (targetUserList.indexOf(messageArray[3]) >=0 ) {
			var message = 'User \'' + messageArray[3] + '\' already exists.'
			sendDiscord(message);
			return;
		}

		// Xgɒǉ
		var message = 'User \'' + messageArray[3] + '\' was added successfully.'
		sendDiscord(message);
		targetUserList.push(messageArray[3]);
	}

	// user delete *̖߂ǉ
	if (messageArray[1] === 'user' && messageArray[2] === 'delete' && messageArray.length == 4 ) {

		// ̖O݂邩mF
		var index = targetUserList.indexOf(messageArray[3]);
		if (index >=0 ) {
			targetUserList.splice(index,1);
			var message = 'User \'' + messageArray[3] + '\' was deleted successfully.'
			sendDiscord(message);
			return;

		} else {
			// ݂Ȃꍇ
			var message = 'User \'' + messageArray[3] + '\' is undefined.'
			sendDiscord(message);
			return;
		}
	}

	// user delete ̖߂ǉ
	if (messageArray[1] === 'user' && messageArray[2] === 'delete' && messageArray.length == 3 ) {
		targetUserList = [];
		var message = 'UserList delete successfully.'
		sendDiscord(message);
		return;
	}

	// user list̖߂ǉ
	// ToDo: 킩₷`悳
	if (messageArray[1] === 'report' && messageArray[2] === 'list' && messageArray.length == 3 ) {
		sendDiscord(targetReportList.join('\n'));
	}

	// user add *̖߂ǉ
	if (messageArray[1] === 'report' && messageArray[2] === 'add' && messageArray.length == 4 ) {

		// ̖O݂邩mF
		var url = 'https://www.fflogs.com/v1/report/fights/' + messageArray[3] + '?api_key=' + process.env.FFLOGS_PUBLIC_KEY;
		var response = request('GET', url);
		if (response.statusCode == 400) {
			var message = 'Report \'' + messageArray[3] + '\' cannot be found.'
			sendDiscord(message);
			return;
		}

		// ɒǉĂꍇ
		if (targetReportList.indexOf(messageArray[3]) >=0 ) {
			var message = 'Report \'' + messageArray[3] + '\' already exists.'
			sendDiscord(message);
			return;
		}

		// Xgɒǉ
		var message = 'Report \'' + messageArray[3] + '\' was added successfully.'
		sendDiscord(message);
		targetReportList.push(messageArray[3]);
	}

	// user delete *̖߂ǉ
	if (messageArray[1] === 'report' && messageArray[2] === 'delete' && messageArray.length == 4 ) {

		// ̖O݂邩mF
		var index = targetReportList.indexOf(messageArray[3]);
		if (index >=0 ) {
			targetReportList.splice(index,1);
			var message = 'Report \'' + messageArray[3] + '\' was deleted successfully.'
			sendDiscord(message);
			return;

		} else {
			// ݂Ȃꍇ
			var message = 'Report \'' + messageArray[3] + '\' is undefined.'
			sendDiscord(message);
			return;
		}
	}

	// user delete ̖߂ǉ
	if (messageArray[1] === 'report' && messageArray[2] === 'delete' && messageArray.length == 3 ) {
		targetReportList = [];
		var message = 'ReportList delete successfully.'
		sendDiscord(message);
		return;
	}

});

function getReportList() {

	targetUserList.forEach(function(userName) {

		var url = 'https://www.fflogs.com/v1/reports/user/' + userName + '?api_key=' + process.env.FFLOGS_PUBLIC_KEY;
		var response = request('GET', url);
		var body = JSON.parse(response.body.toString());

		var lastReport = body[0];
		body.forEach(function(report) {
			if(lastReport.end < report.end) {
				lastReport = report;
			}
		});

		var index = targetReportList.indexOf(lastReport.id);
		if (index == -1) {
			targetReportList.push(lastReport.id);
			var message = 'Automatically added new report:\nhttps://ja.fflogs.com/reports/' + lastReport.id;
			sendDiscord(message);
		}

	});

}

function sendDiscord( message, channel){

	if(!discordReady) return;

	if(channel == undefined) channel = process.env.DISCORD_TARGET_CHANNEL
	bot.sendMessage({
		to: channel,
		message: message
	});
}<|endoftext|>


<commit_before>#!/bin/env node
//  OpenShift sample Node application
var express = require('express');
var fs      = require('fs');

/**
 *  Define the sample application.
 */
var SampleApp = function() {

    //  Scope.
    var self = this;

    /*  ================================================================  */
    /*  Helper functions.                                                 */
    /*  ================================================================  */

    /**
     *  Set up server IP address and port # using env variables/defaults.
     */
    self.setupVariables = function() {
        //  Set the environment variables we need.
        self.ipaddress = process.env.OPENSHIFT_NODEJS_IP;
        self.port      = process.env.OPENSHIFT_NODEJS_PORT || 8080;

        if (typeof self.ipaddress === "undefined") {
            //  Log errors on OpenShift but continue w/ 127.0.0.1 - this
            //  allows us to run/test the app locally.
            console.warn('No OPENSHIFT_NODEJS_IP var, using 127.0.0.1');
            self.ipaddress = "127.0.0.1";
        };
    };

    /**
     *  Populate the cache.
     */
    self.populateCache = function() {
        if (typeof self.zcache === "undefined") {
            self.zcache = { 'index.html': '' };
        }

        //  Local cache for static content.
        self.zcache['index.html'] = fs.readFileSync('./index.html');
    };

    /**
     *  Retrieve entry (content) from cache.
     *  @param {string} key  Key identifying content to retrieve from cache.
     */
    self.cache_get = function(key) { return self.zcache[key]; };

    /**
     *  terminator === the termination handler
     *  Terminate server on receipt of the specified signal.
     *  @param {string} sig  Signal to terminate on.
     */
    self.terminator = function(sig){
        if (typeof sig === "string") {
           console.log('%s: Received %s - terminating sample app ...',
                       Date(Date.now()), sig);
           process.exit(1);
        }
        console.log('%s: Node server stopped.', Date(Date.now()) );
    };

    /**
     *  Setup termination handlers (for exit and a list of signals).
     */
    self.setupTerminationHandlers = function(){
        //  Process on exit and signals.
        process.on('exit', function() { self.terminator(); });

        // Removed 'SIGPIPE' from the list - bugz 852598.
        ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
         'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
        ].forEach(function(element, index, array) {
            process.on(element, function() { self.terminator(element); });
        });
    };

    /*  ================================================================  */
    /*  App server functions (main app logic here).                       */
    /*  ================================================================  */

    /**
     *  Create the routing table entries + handlers for the application.
     */
    self.createRoutes = function() {
        self.routes = { };

        self.routes['/asciimo'] = function(req, res) {
            var link = "http://i.imgur.com/kmbjB.png";
            res.send("");
        };

        self.routes['/'] = function(req, res) {
            res.setHeader('Content-Type', 'text/html');
            res.send(self.cache_get('index.html') );
        };

        self.routes['/dev.html'] = function(req, res) {
            res.setHeader('Content-Type', 'text/html');
            res.send(self.cache_get('dev.html') );
        };
    };

    /**
     *  Initialize the server (express) and create the routes and register
     *  the handlers.
     */
    self.initializeServer = function() {
        self.createRoutes();
        //self.app = express.createServer();
        // var express = require("express");
        var app = express();

        //  Add handlers for the app (from the routes).
        for (var r in self.routes) {
            self.app.get(r, self.routes[r]);
        }
    };

    /**
     *  Initializes the sample application.
     */
    self.initialize = function() {
        self.setupVariables();
        self.populateCache();
        self.setupTerminationHandlers();

        // Create the express server and routes.
        self.initializeServer();
    };

    /**
     *  Start the server (starts up the sample application).
     */
    self.start = function() {
        //  Start the app on the specific interface (and port).
        self.app.listen(self.port, self.ipaddress, function() {
            console.log('%s: Node server started on %s:%d ...',
                        Date(Date.now() ), self.ipaddress, self.port);
        });
    };

};   /*  Sample Application.  */

/**
 *  main():  Main code.
 */
var zapp = new SampleApp();
zapp.initialize();
zapp.start();

<commit_msg>worked on routes and server creation<commit_after>#!/bin/env node
//  OpenShift sample Node application
var express = require('express');
var fs      = require('fs');

/**
 *  Define the sample application.
 */
var SampleApp = function() {

    //  Scope.
    var self = this;

    /*  ================================================================  */
    /*  Helper functions.                                                 */
    /*  ================================================================  */

    /**
     *  Set up server IP address and port # using env variables/defaults.
     */
    self.setupVariables = function() {
        //  Set the environment variables we need.
        self.ipaddress = process.env.OPENSHIFT_NODEJS_IP;
        self.port      = process.env.OPENSHIFT_NODEJS_PORT || 8080;

        if (typeof self.ipaddress === "undefined") {
            //  Log errors on OpenShift but continue w/ 127.0.0.1 - this
            //  allows us to run/test the app locally.
            console.warn('No OPENSHIFT_NODEJS_IP var, using 127.0.0.1');
            self.ipaddress = "127.0.0.1";
        };
    };

    /**
     *  Populate the cache.
     */
    self.populateCache = function() {
        if (typeof self.zcache === "undefined") {
            self.zcache = { 'index.html': '' };
        }

        //  Local cache for static content.
        self.zcache['index.html'] = fs.readFileSync('./index.html');
    };

    /**
     *  Retrieve entry (content) from cache.
     *  @param {string} key  Key identifying content to retrieve from cache.
     */
    self.cache_get = function(key) { return self.zcache[key]; };

    /**
     *  terminator === the termination handler
     *  Terminate server on receipt of the specified signal.
     *  @param {string} sig  Signal to terminate on.
     */
    self.terminator = function(sig){
        if (typeof sig === "string") {
           console.log('%s: Received %s - terminating sample app ...',
                       Date(Date.now()), sig);
           process.exit(1);
        }
        console.log('%s: Node server stopped.', Date(Date.now()) );
    };

    /**
     *  Setup termination handlers (for exit and a list of signals).
     */
    self.setupTerminationHandlers = function(){
        //  Process on exit and signals.
        process.on('exit', function() { self.terminator(); });

        // Removed 'SIGPIPE' from the list - bugz 852598.
        ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
         'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
        ].forEach(function(element, index, array) {
            process.on(element, function() { self.terminator(element); });
        });
    };

    /*  ================================================================  */
    /*  App server functions (main app logic here).                       */
    /*  ================================================================  */

    /**
     *  Create the routing table entries + handlers for the application.
     */
    self.createRoutes = function() {
        self.routes = { };

        self.routes['/asciimo'] = function(req, res) {
            var link = "http://i.imgur.com/kmbjB.png";
            res.send("");
        };

        self.routes['/'] = function(req, res) {
            res.setHeader('Content-Type', 'text/html');
            res.send(self.cache_get('index.html') );
        };

        self.routes['/dev.html'] = function(req, res) {
            res.setHeader('Content-Type', 'text/html');
            res.send(self.cache_get('dev.html') );
        };
    };

    /**
     *  Initialize the server (express) and create the routes and register
     *  the handlers.
     */
    self.initializeServer = function() {
        self.createRoutes();
        //self.app = express.createServer();
        // var express = require("express");
        var self.app = express();

        //  Add handlers for the app (from the routes).
        for (var r in self.routes) {
            self.app.get(r, self.routes[r]);
        }
    };

    /**
     *  Initializes the sample application.
     */
    self.initialize = function() {
        self.setupVariables();
        self.populateCache();
        self.setupTerminationHandlers();

        // Create the express server and routes.
        self.initializeServer();
    };

    /**
     *  Start the server (starts up the sample application).
     */
    self.start = function() {
        //  Start the app on the specific interface (and port).
        self.app.listen(self.port, self.ipaddress, function() {
            console.log('%s: Node server started on %s:%d ...',
                        Date(Date.now() ), self.ipaddress, self.port);
        });
    };

};   /*  Sample Application.  */

/**
 *  main():  Main code.
 */
var zapp = new SampleApp();
zapp.initialize();
zapp.start();

<|endoftext|>


<commit_before>var express = require('express'),
    routes = require(__dirname + '/routes.js'),
    app = express(),
    port = (process.env.PORT || 3000);

// Application settings
app.engine('html', require(__dirname + '/lib/template-engine.js').__express);
app.set('view engine', 'html');
app.set('vendorViews', __dirname + '/govuk/views');
app.set('views', __dirname + '/app/views');

// Middleware to serve static assets
app.use('/public', express.static(__dirname + '/public'));
app.use('/public', express.static(__dirname + '/govuk/public'));

// routes (found in routes.js)

var assetPath = '/public/';

routes.bind(app, assetPath);

// auto render any view that exists

app.get(/^\/(.+)/, function (req, res) {

	var path = (req.params[0]);

	res.render(path, {'assetPath' : assetPath }, function(err, html) {
		if (err) {
			console.log(err);
			res.send(404);
		} else {
			res.end(html);
		}
	});

});

// start the app

app.listen(port);
console.log('');
console.log('Listening on port ' + port);
console.log('');
<commit_msg>Update references to ./routes.js in ./server.js<commit_after>var express = require('express'),
    routes = require(__dirname + '/app/routes.js'),
    app = express(),
    port = (process.env.PORT || 3000);

// Application settings
app.engine('html', require(__dirname + '/lib/template-engine.js').__express);
app.set('view engine', 'html');
app.set('vendorViews', __dirname + '/govuk/views');
app.set('views', __dirname + '/app/views');

// Middleware to serve static assets
app.use('/public', express.static(__dirname + '/public'));
app.use('/public', express.static(__dirname + '/govuk/public'));

// routes (found in routes.js)

var assetPath = '/public/';

routes.bind(app, assetPath);

// auto render any view that exists

app.get(/^\/(.+)/, function (req, res) {

	var path = (req.params[0]);

	res.render(path, {'assetPath' : assetPath }, function(err, html) {
		if (err) {
			console.log(err);
			res.send(404);
		} else {
			res.end(html);
		}
	});

});

// start the app

app.listen(port);
console.log('');
console.log('Listening on port ' + port);
console.log('');
<|endoftext|>


<commit_before>(function (DISPLAY_TIMEOUT, ANSWER_TIMEOUT, SHORT_DISPLAY_TIMEOUT, HTTP_PORT, NUMBER_QUESTION) {
    var games = [];
    var players = [];
    var playerIdGenerator = 0;
    var lies = undefined;

    require('./array.js');

    var express = require('express');
    var app = express();
    var server = null;

    try {
        app.use(express.static(__dirname + '/client'));
        app.get('/', function (req, res) {
            res.sendfile(__dirname + '/client/index.html');
        });
        server = app.listen(HTTP_PORT);
        console.log("Ready & listening to requests. Ctrl-C to stop.")
    } catch (e) {
        console.log("Error in server: " + e);
    }

    try {
        var io = require('socket.io').listen(server);
        console.log("WSServer lancé");
    } catch (e) {
        console.log("Problème WSServer" + e);
    }

    console.log("Listening to port: " + HTTP_PORT);

    io.sockets.on('connection', function (socket) {
        socket.on('iam:presenter', function (data) {
            var game = new Game(socket);
            games.push(game);

            game.presenterSocket.emit('display:code', game.code);
            console.log("New Game: Presenter: " + game.code);
        });

        socket.on('iam:player', function (data) {
            var game = getGameByCode(data.code);
            if (game == undefined) {
                socket.emit('wrong:code');
            } else {
                var player = game.getPlayerByName(data.name);
                if (player !== undefined) {
                    player.disconnected = false;
                    player.socket = socket;
                } else {
                    game.createPlayer(data.name, socket);
                    game.presenterSocket.emit('display:player', {"name": data.name, "id": getPlayerBySocket(socket).id});
                    console.log("[Game" + game.code + "] New Player: " + data.name);
                }
            }

        });

        socket.on('start', function (data) {
            var game = getGameByCode(data.code).start();
            console.log("[Game" + game.code + "] Game Start !");
        });

        socket.on('play:lie', function (data) {
            var player = getPlayerById(data.id);
            if (player != undefined) {
                if (data.lie.trim() === player.game.questions[0].truth) {
                    socket.emit('lie:truth');
                    console.log("[Game" + player.game.code + "] Player found truth !");
                } else {
                    player.actualLie = data.lie.toUpperCase().trim();
                    player.socket.emit('lie:ok');
                    player.game.presenterSocket.emit('song:player', player.id);
                    console.log("[Game" + player.game.code + "] Player " + player.name + " lied [" + player.actualLie + "]");

                    player.game.presenterSocket.emit('player:lied', player.name);

                    if (player.game.allLiesEntered()) {
                        player.game.endLie();
                        console.log("[Game" + player.game.code + "] All players lied !");
                    }
                }
            } else {
                console.log("Wrong lier " + JSON.stringify(data));
            }
        });

        socket.on('play:answer', function (data) {
            var player = getPlayerById(data.id);
            if (player != undefined) {
                player.actualAnswer = data.answer.toUpperCase().trim();
                console.log("[Game" + player.game.code + "] Player " + player.name + " answered [" + player.actualAnswer + "]");
                player.game.presenterSocket.emit('song:player', player.id);

                if (player.game.allAnswersEntered()) {
                    console.log("[Game" + player.game.code + "] All players Answered !");
                    player.game.endAnswer();
                }
            } else {
                console.log("Wrong answerer " + JSON.stringify(data));
            }
        });

        socket.on('disconnect', function () {
            socket.emit('disconnected');
            var player = getPlayerBySocket(socket);
            if (player != undefined) {
                player.disconnected = true;
            }
        });
    });

    function Game(socket) {
        this.code = this.generateCode();
        this.presenterSocket = socket;
        this.players = [];
        this.questions = randomQuestions(NUMBER_QUESTION);
    }

    var fs = require('fs');

    function randomQuestions(nb) {
        var buffer = fs.readFileSync('./questions.json', "utf8");
        var possibleQuestions = JSON.parse(buffer);
        return possibleQuestions.shuffle().splice(0, nb);
    }

    function randomLies() {
        if (lies === undefined) {
            var buffer = fs.readFileSync('./questions.json', "utf8");
            lies = JSON.parse(buffer)
                .filter(function (obj) {
                    return obj !== undefined;
                })
                .map(function (obj) {
                    return obj.truth;
                })
                .unique();
        }
        return lies;
    }

    function getGameByCode(code) {
        return games.filter(function (game) {
            return game.code === code;
        })[0];
    }

    Game.prototype.generateCode = function () {
        var valid = false;
        while (!valid) {
            var candidate = randomString(5, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
            valid = games.filter(function (game) {
                    return game.code === candidate;
                }).length === 0;
        }
        return candidate;
    };

    function randomString(length, chars) {
        var result = '';
        for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
        return result;
    }

    Game.prototype.createPlayer = function (name, socket) {
        var player = new Player(name, socket, this);
        this.players.push(player);
        players.push(player);
        socket.emit('identify', {"id": player.id});
    };

    Game.prototype.getPlayerByName = function (name) {
        return this.players.filter(function (player) {
            return name === player.name;
        })[0];
    };

    Game.prototype.start = function () {
        this.state = "lying";
        this.players.forEach(function (player) {
            player.actualLie = undefined;
            player.actualAnswer = undefined;
        });
        var game = this;
        if (this.questions.length > 0) {
            console.log("[Game" + this.code + "] Question n°" + ( NUMBER_QUESTION - this.questions.length) + " started");
            this.broadcast('display:lie', this.questions[0]);
            this.endLieTimeout = setTimeout(function () {
                game.endLie();
            }, ANSWER_TIMEOUT);
        } else {
            console.log("[Game" + this.code + "] Game terminated !");
            this.end = Date.now();
            this.questions = randomQuestions(NUMBER_QUESTION);
            this.broadcast('end');
        }
        return this;
    };

    Game.prototype.endLie = function () {
        var game = this;
        clearTimeout(this.endLieTimeout);
        if (this.state == "lying") {
            console.log("[Game" + game.code + "] Starting choosing answers");
            this.state = "answering";

            this.broadcast("display:answer", {
                question: this.questions[0],
                lies    : this.players
                    .filter(function (player) {
                        return player.actualLie != undefined && player.actualLie != null;
                    })
                    .map(function (player) {
                        return player.actualLie;
                    })
                    .concat(this.questions[0].truth.toUpperCase())
                    .unique()
                    .completeWith(randomLies(), this.players.length + 1 > 4 ? this.players.length + 1 : 4)
                    .shuffle()
            });

            this.endAnswerTimeout = setTimeout(function () {
                game.endAnswer();
            }, ANSWER_TIMEOUT);
        }
    };

    Game.prototype.broadcast = function (evt, obj) {
        this.presenterSocket.emit(evt, obj);
        this.players.forEach(function (player) {
            player.socket.emit(evt, obj);
        });
    };

    Game.prototype.allLiesEntered = function () {
        var allLied = true;
        this.players.forEach(function (player) {
            allLied = allLied && (player.actualLie !== undefined);
        });
        return allLied;
    };

    Game.prototype.allAnswersEntered = function () {
        var allAnswers = true;
        this.players.forEach(function (player) {
            allAnswers = allAnswers && (player.actualAnswer !== undefined);
        });
        return allAnswers;
    };

    Game.prototype.endAnswer = function () {
        var game = this;
        clearTimeout(this.endAnswerTimeout);
        if (this.state == "answering") {
            console.log("[Game" + game.code + "] Starting displaying results");
            this.state = "calculating";
            this.presenterSocket.emit("clear:message", {});
            this.resultMessages = [];

            var points = 500;
            if ((NUMBER_QUESTION / 2) > this.questions.length) {
                points = 1000;
            }
            if (this.questions.length == 1) {
                points = 1500;
            }

            /* L'ordi a menti */
            randomLies()
                .filter(function (lie) {
                    /* Un utilisateur a entré ce même mensonge */
                    var entered = false;
                    game.players.forEach(function (player, idx, arr) {
                        if (lie.toUpperCase() === player.actualLie) {
                            entered = true;
                        }
                    });
                    return !entered;
                })
                .filter(function (lie) {
                    /* On ignore la vérité */
                    return lie.toUpperCase() !== game.questions[0].truth.toUpperCase();
                })
                .forEach(function (lie) {
                    var liedWorkedOn = "";
                    game.players.forEach(function (player, idx, arr) {
                        if (lie.toUpperCase() === player.actualAnswer) {
                            liedWorkedOn += player.name + " ";
                            player.score -= points;
                        }
                    });
                    if (liedWorkedOn.length > 0) {
                        game.resultMessages.push({msg: "La réponse " + lie, time: SHORT_DISPLAY_TIMEOUT});
                        game.resultMessages.push({msg: "Etait un MENSONGE de la MATRICE !!!", time: SHORT_DISPLAY_TIMEOUT * 2});
                        game.resultMessages.push({msg: "qui a trompé " + liedWorkedOn, time: SHORT_DISPLAY_TIMEOUT * 2});
                    }
                });

            /* A menti */
            this.players.forEach(function (player, idx, arr) {
                var liedTo = "";
                arr.forEach(function (potentialLiedTo) {
                    if (potentialLiedTo.actualAnswer === player.actualLie) {
                        liedTo += potentialLiedTo.name + " ";
                        player.score += points;
                    }
                });
                if (liedTo.length > 0) {
                    game.resultMessages.push({msg: "La réponse " + player.actualLie, time: SHORT_DISPLAY_TIMEOUT});
                    game.resultMessages.push({msg: "Etait un MENSONGE de " + player.name, time: SHORT_DISPLAY_TIMEOUT * 2});
                    game.resultMessages.push({msg: "qui a trompé " + liedTo, time: SHORT_DISPLAY_TIMEOUT * 2});
                }
            });

            /* A trouvé la vérité */
            this.resultMessages.push({msg: "La réponse " + game.questions[0].truth.toUpperCase(), time: SHORT_DISPLAY_TIMEOUT});
            this.resultMessages.push({msg: "Etait la VERITE", time: SHORT_DISPLAY_TIMEOUT});
            var haveFoundTruth = "";
            this.players.forEach(function (player, idx, arr) {
                if (player.actualAnswer === game.questions[0].truth.toUpperCase()) {
                    player.score += points * 2;
                    haveFoundTruth += player.name + " ";
                }
            });
            if (haveFoundTruth.length > 0) {
                this.resultMessages.push({msg: "qui a été trouvée par " + haveFoundTruth, time: SHORT_DISPLAY_TIMEOUT});
            } else {
                this.resultMessages.push({msg: "qui n'a été trouvée par PERSONNE !", time: SHORT_DISPLAY_TIMEOUT});
            }
            game.presenterSocket.emit('song:result');
            game.displayNextMessage();
        }
    };

    Game.prototype.displayNextMessage = function () {
        var game = this;
        if (this.resultMessages.length > 0) {
            var result = this.resultMessages.shift();
            this.presenterSocket.emit("display:message", {question: this.questions[0].question, msg: result});
            setTimeout(function () {
                game.displayNextMessage();
            }, DISPLAY_TIMEOUT);
        } else {
            this.presenterSocket.emit("display:score", {question: this.questions[0].question, scoreTab: game.getScoreTab()});
            setTimeout(function () {
                console.log("[Game" + game.code + "] Next Question !");
                game.questions.shift();
                game.start();
            }, DISPLAY_TIMEOUT);
        }
    };

    Game.prototype.getScoreTab = function () {
        return this.players.map(function (player) {
            return {name: player.name, score: player.score}
        }).sort(function (a, b) {
            return a.score - b.score;
        });
    };

    function Player(name, socket, game) {
        this.name = name.toUpperCase();
        this.socket = socket;
        this.id = playerIdGenerator++;
        this.game = game;
        this.score = 0;
    }

    function getPlayerById(id) {
        return players.filter(function (player) {
            return player.id === id;
        })[0];
    }

    function getPlayerBySocket(socket) {
        return players.filter(function (player) {
            return player.socket === socket;
        })[0];
    }

})(5000, 30000, 1000, 8000, 7);<commit_msg>Correction d'un bug de réponse/mensonge undefined<commit_after>(function (DISPLAY_TIMEOUT, ANSWER_TIMEOUT, SHORT_DISPLAY_TIMEOUT, HTTP_PORT, NUMBER_QUESTION) {
    var games = [];
    var players = [];
    var playerIdGenerator = 0;
    var lies = undefined;

    require('./array.js');

    var express = require('express');
    var app = express();
    var server = null;

    try {
        app.use(express.static(__dirname + '/client'));
        app.get('/', function (req, res) {
            res.sendfile(__dirname + '/client/index.html');
        });
        server = app.listen(HTTP_PORT);
        console.log("Ready & listening to requests. Ctrl-C to stop.")
    } catch (e) {
        console.log("Error in server: " + e);
    }

    try {
        var io = require('socket.io').listen(server);
        console.log("WSServer lancé");
    } catch (e) {
        console.log("Problème WSServer" + e);
    }

    console.log("Listening to port: " + HTTP_PORT);

    io.sockets.on('connection', function (socket) {
        socket.on('iam:presenter', function (data) {
            var game = new Game(socket);
            games.push(game);

            game.presenterSocket.emit('display:code', game.code);
            console.log("New Game: Presenter: " + game.code);
        });

        socket.on('iam:player', function (data) {
            var game = getGameByCode(data.code);
            if (game == undefined) {
                socket.emit('wrong:code');
            } else {
                var player = game.getPlayerByName(data.name);
                if (player !== undefined) {
                    player.disconnected = false;
                    player.socket = socket;
                } else {
                    game.createPlayer(data.name, socket);
                    game.presenterSocket.emit('display:player', {"name": data.name, "id": getPlayerBySocket(socket).id});
                    console.log("[Game" + game.code + "] New Player: " + data.name);
                }
            }

        });

        socket.on('start', function (data) {
            var game = getGameByCode(data.code).start();
            console.log("[Game" + game.code + "] Game Start !");
        });

        socket.on('play:lie', function (data) {
            var player = getPlayerById(data.id);
            if (player != undefined) {
                if (data.lie.trim() === player.game.questions[0].truth) {
                    socket.emit('lie:truth');
                    console.log("[Game" + player.game.code + "] Player found truth !");
                } else {
                    player.actualLie = data.lie.toUpperCase().trim();
                    player.socket.emit('lie:ok');
                    player.game.presenterSocket.emit('song:player', player.id);
                    console.log("[Game" + player.game.code + "] Player " + player.name + " lied [" + player.actualLie + "]");

                    player.game.presenterSocket.emit('player:lied', player.name);

                    if (player.game.allLiesEntered()) {
                        player.game.endLie();
                        console.log("[Game" + player.game.code + "] All players lied !");
                    }
                }
            } else {
                console.log("Wrong lier " + JSON.stringify(data));
            }
        });

        socket.on('play:answer', function (data) {
            var player = getPlayerById(data.id);
            if (player != undefined) {
                player.actualAnswer = data.answer.toUpperCase().trim();
                console.log("[Game" + player.game.code + "] Player " + player.name + " answered [" + player.actualAnswer + "]");
                player.game.presenterSocket.emit('song:player', player.id);

                if (player.game.allAnswersEntered()) {
                    console.log("[Game" + player.game.code + "] All players Answered !");
                    player.game.endAnswer();
                }
            } else {
                console.log("Wrong answerer " + JSON.stringify(data));
            }
        });

        socket.on('disconnect', function () {
            socket.emit('disconnected');
            var player = getPlayerBySocket(socket);
            if (player != undefined) {
                player.disconnected = true;
            }
        });
    });

    function Game(socket) {
        this.code = this.generateCode();
        this.presenterSocket = socket;
        this.players = [];
        this.questions = randomQuestions(NUMBER_QUESTION);
    }

    var fs = require('fs');

    function randomQuestions(nb) {
        var buffer = fs.readFileSync('./questions.json', "utf8");
        var possibleQuestions = JSON.parse(buffer);
        return possibleQuestions.shuffle().splice(0, nb);
    }

    function randomLies() {
        if (lies === undefined) {
            var buffer = fs.readFileSync('./questions.json', "utf8");
            lies = JSON.parse(buffer)
                .filter(function (obj) {
                    return obj !== undefined;
                })
                .map(function (obj) {
                    return obj.truth;
                })
                .unique();
        }
        return lies;
    }

    function getGameByCode(code) {
        return games.filter(function (game) {
            return game.code === code;
        })[0];
    }

    Game.prototype.generateCode = function () {
        var valid = false;
        while (!valid) {
            var candidate = randomString(5, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
            valid = games.filter(function (game) {
                    return game.code === candidate;
                }).length === 0;
        }
        return candidate;
    };

    function randomString(length, chars) {
        var result = '';
        for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
        return result;
    }

    Game.prototype.createPlayer = function (name, socket) {
        var player = new Player(name, socket, this);
        this.players.push(player);
        players.push(player);
        socket.emit('identify', {"id": player.id});
    };

    Game.prototype.getPlayerByName = function (name) {
        return this.players.filter(function (player) {
            return name === player.name;
        })[0];
    };

    Game.prototype.start = function () {
        this.state = "lying";
        this.players.forEach(function (player) {
            player.actualLie = undefined;
            player.actualAnswer = undefined;
        });
        var game = this;
        if (this.questions.length > 0) {
            console.log("[Game" + this.code + "] Question n°" + ( NUMBER_QUESTION - this.questions.length) + " started");
            this.broadcast('display:lie', this.questions[0]);
            this.endLieTimeout = setTimeout(function () {
                game.endLie();
            }, ANSWER_TIMEOUT);
        } else {
            console.log("[Game" + this.code + "] Game terminated !");
            this.end = Date.now();
            this.questions = randomQuestions(NUMBER_QUESTION);
            this.broadcast('end');
        }
        return this;
    };

    Game.prototype.endLie = function () {
        var game = this;
        clearTimeout(this.endLieTimeout);
        if (this.state == "lying") {
            console.log("[Game" + game.code + "] Starting choosing answers");
            this.state = "answering";

            this.broadcast("display:answer", {
                question: this.questions[0],
                lies    : this.players
                    .filter(function (player) {
                        return player.actualLie != undefined && player.actualLie != null;
                    })
                    .map(function (player) {
                        return player.actualLie;
                    })
                    .concat(this.questions[0].truth.toUpperCase())
                    .unique()
                    .completeWith(randomLies(), this.players.length + 1 > 4 ? this.players.length + 1 : 4)
                    .shuffle()
            });

            this.endAnswerTimeout = setTimeout(function () {
                game.endAnswer();
            }, ANSWER_TIMEOUT);
        }
    };

    Game.prototype.broadcast = function (evt, obj) {
        this.presenterSocket.emit(evt, obj);
        this.players.forEach(function (player) {
            player.socket.emit(evt, obj);
        });
    };

    Game.prototype.allLiesEntered = function () {
        var allLied = true;
        this.players.forEach(function (player) {
            allLied = allLied && (player.actualLie !== undefined);
        });
        return allLied;
    };

    Game.prototype.allAnswersEntered = function () {
        var allAnswers = true;
        this.players.forEach(function (player) {
            allAnswers = allAnswers && (player.actualAnswer !== undefined);
        });
        return allAnswers;
    };

    Game.prototype.endAnswer = function () {
        var game = this;
        clearTimeout(this.endAnswerTimeout);
        if (this.state == "answering") {
            console.log("[Game" + game.code + "] Starting displaying results");
            this.state = "calculating";
            this.presenterSocket.emit("clear:message", {});
            this.resultMessages = [];

            var points = 500;
            if ((NUMBER_QUESTION / 2) > this.questions.length) {
                points = 1000;
            }
            if (this.questions.length == 1) {
                points = 1500;
            }

            /* L'ordi a menti */
            randomLies()
                .filter(function (lie) {
                    /* Un utilisateur a entré ce même mensonge */
                    var entered = false;
                    game.players.forEach(function (player, idx, arr) {
                        if (lie.toUpperCase() === player.actualLie) {
                            entered = true;
                        }
                    });
                    return !entered;
                })
                .filter(function (lie) {
                    /* On ignore la vérité */
                    return lie.toUpperCase() !== game.questions[0].truth.toUpperCase();
                })
                .forEach(function (lie) {
                    var liedWorkedOn = "";
                    game.players.forEach(function (player, idx, arr) {
                        if (lie.toUpperCase() === player.actualAnswer) {
                            liedWorkedOn += player.name + " ";
                            player.score -= points;
                        }
                    });
                    if (liedWorkedOn.length > 0) {
                        game.resultMessages.push({msg: "La réponse " + lie, time: SHORT_DISPLAY_TIMEOUT});
                        game.resultMessages.push({msg: "Etait un MENSONGE de la MATRICE !!!", time: SHORT_DISPLAY_TIMEOUT * 2});
                        game.resultMessages.push({msg: "qui a trompé " + liedWorkedOn, time: SHORT_DISPLAY_TIMEOUT * 2});
                    }
                });

            /* A menti */
            this.players
                .filter(function(player){
                    return player.actualLie !== undefined;
                })
                .forEach(function (player, idx, arr) {
                var liedTo = "";
                arr.forEach(function (potentialLiedTo) {
                    if (potentialLiedTo.actualAnswer !== undefined && potentialLiedTo.actualAnswer === player.actualLie) {
                        liedTo += potentialLiedTo.name + " ";
                        player.score += points;
                    }
                });
                if (liedTo.length > 0) {
                    game.resultMessages.push({msg: "La réponse " + player.actualLie, time: SHORT_DISPLAY_TIMEOUT});
                    game.resultMessages.push({msg: "Etait un MENSONGE de " + player.name, time: SHORT_DISPLAY_TIMEOUT * 2});
                    game.resultMessages.push({msg: "qui a trompé " + liedTo, time: SHORT_DISPLAY_TIMEOUT * 2});
                }
            });

            /* A trouvé la vérité */
            this.resultMessages.push({msg: "La réponse " + game.questions[0].truth.toUpperCase(), time: SHORT_DISPLAY_TIMEOUT});
            this.resultMessages.push({msg: "Etait la VERITE", time: SHORT_DISPLAY_TIMEOUT});
            var haveFoundTruth = "";
            this.players.forEach(function (player, idx, arr) {
                if (player.actualAnswer === game.questions[0].truth.toUpperCase()) {
                    player.score += points * 2;
                    haveFoundTruth += player.name + " ";
                }
            });
            if (haveFoundTruth.length > 0) {
                this.resultMessages.push({msg: "qui a été trouvée par " + haveFoundTruth, time: SHORT_DISPLAY_TIMEOUT});
            } else {
                this.resultMessages.push({msg: "qui n'a été trouvée par PERSONNE !", time: SHORT_DISPLAY_TIMEOUT});
            }
            game.presenterSocket.emit('song:result');
            game.displayNextMessage();
        }
    };

    Game.prototype.displayNextMessage = function () {
        var game = this;
        if (this.resultMessages.length > 0) {
            var result = this.resultMessages.shift();
            this.presenterSocket.emit("display:message", {question: this.questions[0].question, msg: result});
            setTimeout(function () {
                game.displayNextMessage();
            }, DISPLAY_TIMEOUT);
        } else {
            this.presenterSocket.emit("display:score", {question: this.questions[0].question, scoreTab: game.getScoreTab()});
            setTimeout(function () {
                console.log("[Game" + game.code + "] Next Question !");
                game.questions.shift();
                game.start();
            }, DISPLAY_TIMEOUT);
        }
    };

    Game.prototype.getScoreTab = function () {
        return this.players.map(function (player) {
            return {name: player.name, score: player.score}
        }).sort(function (a, b) {
            return a.score - b.score;
        });
    };

    function Player(name, socket, game) {
        this.name = name.toUpperCase();
        this.socket = socket;
        this.id = playerIdGenerator++;
        this.game = game;
        this.score = 0;
    }

    function getPlayerById(id) {
        return players.filter(function (player) {
            return player.id === id;
        })[0];
    }

    function getPlayerBySocket(socket) {
        return players.filter(function (player) {
            return player.socket === socket;
        })[0];
    }

})(5000, 30000, 1000, 8000, 7);<|endoftext|>


<commit_before>/* Main application entry file. Please note, the order of loading is important.
 * Configuration loading and booting of controllers and custom error handlers */

var express = require('express')
  , fs = require('fs')
  , passport = require('passport')

require('express-namespace')

// Load configurations
var env = process.env.NODE_ENV || 'development'
  , config = require('./config/config')[env]
  , auth = require('./authorization')

// Bootstrap db connection
var mongoose = require('mongoose')
  , Schema = mongoose.Schema
mongoose.connect(config.db)

// Bootstrap models
var models_path = __dirname + '/app/models'
  , model_files = fs.readdirSync(models_path)
model_files.forEach(function (file) {
  require(models_path+'/'+file)
})

// bootstrap passport config
require('./config/passport')

var app = express()                                       // express app
require('./settings').boot(app, config, passport)         // Bootstrap application settings

// Bootstrap routes
require('./config/routes')(app, passport, auth)

// Start the app by listening on <port>
var port = process.env.PORT || 4000
app.listen(port)
console.log('Express app started on port '+port)
<commit_msg>bootstrap passport<commit_after>/* Main application entry file. Please note, the order of loading is important.
 * Configuration loading and booting of controllers and custom error handlers */

var express = require('express')
  , fs = require('fs')
  , passport = require('passport')

require('express-namespace')

// Load configurations
var env = process.env.NODE_ENV || 'development'
  , config = require('./config/config')[env]
  , auth = require('./authorization')

// Bootstrap db connection
var mongoose = require('mongoose')
  , Schema = mongoose.Schema
mongoose.connect(config.db)

// Bootstrap models
var models_path = __dirname + '/app/models'
  , model_files = fs.readdirSync(models_path)
model_files.forEach(function (file) {
  require(models_path+'/'+file)
})

// bootstrap passport config
require('./config/passport').boot(passport, config)

var app = express()                                       // express app
require('./settings').boot(app, config, passport)         // Bootstrap application settings

// Bootstrap routes
require('./config/routes')(app, passport, auth)

// Start the app by listening on <port>
var port = process.env.PORT || 4000
app.listen(port)
console.log('Express app started on port '+port)
<|endoftext|>


<commit_before>// server.js

// Import packages
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

// Import models
var user = require('./app/models/user');

// Connect to a local Mongo database
mongoose.connect('mongodb://localhost/usersTest');

// Configure app to use bodyParser() - allows us to get data from POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// Set our port
var port = process.env.PORT || 8080;

// ROUTES FOR API
// -------------------------------------------------------------------
// Get instance of express router
var router = express.Router();

// Middleware for all requests
router.use(function (req, res, next) {

    // Perform logging here
    console.log("Cool routing stuff is happening here");

    // Go to next route after this
    next();
});

// Test
router.get('/', function (req, res) {
    res.json({message: "Hello World"});
});

// Additonal routes

// REGISTER ROUTES
// -------------------------------------------------------------------
// All routes will be prefixed with /api

app.use('/api', router);

// START SERVER
// -------------------------------------------------------------------
app.listen(port);
console.log("Server has started on port " + port);

<commit_msg>Starting POST method<commit_after>// server.js

// Import packages
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

// Import models
var user = require('./app/models/user');

// Connect to a local Mongo database
mongoose.connect('mongodb://localhost/usersTest');

// Configure app to use bodyParser() - allows us to get data from POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// Set our port
var port = process.env.PORT || 8080;

// ROUTES FOR API
// -------------------------------------------------------------------
// Get instance of express router
var router = express.Router();

// Middleware for all requests
router.use(function (req, res, next) {

    // Perform logging here
    console.log("Cool routing stuff is happening here");

    // Go to next route after this
    next();
});

// Test
router.get('/', function (req, res) {
    res.json({message: "Hello World"});
});

// Routes that end with /user
router.route('/user')

    // Create a user
    .post(function (req, res) {

        // Create new instance of user model
        var user = new User();

        // Set user's name (comes from the request)
        user.name = req.body.name;
    }

// REGISTER ROUTES
// -------------------------------------------------------------------
// All routes will be prefixed with /api

app.use('/api', router);

// START SERVER
// -------------------------------------------------------------------
app.listen(port);
console.log("Server has started on port " + port);
<|endoftext|>


<commit_before>var app = require('express')();
var bodyParser = require('body-parser');
var Trello = require('node-trello');

var devKey = process.env.DEV_KEY;
var appToken = process.env.APP_TOKEN;
var trello = new Trello(devKey, appToken);

var list = process.env.DESTINATION_LIST;
var branch;
var board;
var cardNumber;
var cardID;
var boardID;
var listID;
var listName;

app.use(bodyParser.json());

var server = app.listen(process.env.PORT, function () {
  console.log('Listening at http://%s:%s', server.address().address, server.address().port);
});

app.post('/', function (req, res) {
  //res.send({status: 'Received'});

  var pullRequestTitle = req.body.pull_request.title;

  // Regex would most likely be best in this situation. Since the naming convention for pull requests is not set,
  // pull request names are inconsistent. All we know is that everything up to and including the first number is
  // a representation of the branch to be merged from.

  var branchRegex = /\D+\d+/g;
  try {
    // Grab everything up until and including the first number
    branch = branchRegex.exec(pullRequestTitle)[0];

    // If we were successful at getting the branch name, go ahead and continue
    if (branch) {

      // Trim the branch name of any possible leading/trailing whitespaces
      branch = branch.trim();

      // If there are any whitespaces in between words, replace the whitespaces in between the words
      // with a hyphen. Ex: 'this   is a    branch 50' will be 'this-is-a-branch-50'
      if (branch.indexOf(' ') >= 0) {
        branch = branch.replace(/\s+/g, '-');
      }

      // Convert it all to lowercase since that's how it most likely will appear on GitHub
      branch = branch.toLowerCase();

      // Next, we'll grab the number out of the branch, which is the card number
      // The card number is also the short ID of the Trello card (attribute is idShort)
      var cardNumberRegex = /\d+/g;
      cardNumber = cardNumberRegex.exec(branch)[0];

      // If we were successful in getting the card number, that means the pull request was named in such
      // a way that we are possibly able to find the corresponding card on Trello
      if (cardNumber) {

        board = branch.slice(0, branch.length - cardNumber.length - 1);
        console.log('Card #' + cardNumber + '\nBranch: ' + branch + '\nBoard: ' + board);
        res.send({status: 'Card #' + cardNumber + '\nBranch: ' + branch + '\nBoard: ' + board});

        var action = req.body.action;
        // Now that we have all the information we can get, update the card on Trello

        switch (action) {
          case 'assigned':
            break;
          case 'unassigned':
            break;
          case 'labeled':
            break;
          case 'unlabeled':
            break;
          case 'opened':
            break;
          case 'closed':
            moveCard();
            break;
          case 'reopened':
            break;
          case 'synchronized':
            break;
          // The created action is for when a pull request review comment event occurs
          case 'created':
            break;
        }
        moveCard();
      }

    }

  } catch (error) {
    console.log('The pull request name is not formatted in a way to be found on Trello');
  }

});

/**
 *
 * Moves the card with the specified ID from its current list to the list with the
 * specified ID.
 *
 * @param {string} cardID - ID of the Trello card
 * @param {string} listID - ID of the Trello list
 */
function putCardInList(cardID, listID) {
  trello.put('/1/cards/' + cardID, {idList: listID}, function (error, data) {
    if (error) {
      console.log(error);
    } else {
      console.log(data);
    }
  });
}

/**
 * Upon certain pull request actions, this will move the card in the request into the
 * list specified by the environment variable DESTINATION_LIST
 *
 */
function moveCard() {
  trello.get('/1/members/me/boards?lists=all', function (error, boardsJSON) {
    if (error) {
      console.log(error);
    } else {
      var foundBoard = false;
      for (var i = 0; i < boardsJSON.length && !foundBoard; i++) {
        var boardJSON = boardsJSON[i];
        if (boardJSON.name === board) {
          foundBoard = true;
          boardID = boardJSON.id;

          var foundList = false;
          var listsJSON = boardJSON.lists;
          for (var j = 0; j < listsJSON.length && !foundList; j++) {
            var listJSON = listsJSON[j];
            if (listJSON.name === list) {
              foundList = true;

              listName = listJSON.name;
              listID = listJSON.id;
              trello.get('/1/boards/' + boardID + '/cards?limit=1000', function (error, cardsJSON) {
                if (error) {
                  console.log(error);
                } else {
                  var foundCard = false;
                  for (var k = 0; k < cardsJSON.length && !foundCard; k++) {
                    var cardJSON = cardsJSON[k];
                    if (cardJSON.idShort == cardNumber) {
                      foundCard = true;

                      cardID = cardJSON.id;
                      console.log('Placing \'' + cardJSON.name + '\' into \'' + listName + '\'');
                      // TODO: After card is placed into the list, comment on the card with a message similar to:
                      // TODO: 'Merged by User'
                      putCardInList(cardID, listID);
                    }
                  }
                }
              });
            }
          }
        }
      }
    }
  });
}

<commit_msg>dumb change to force a pull request<commit_after>var app = require('express')();
var bodyParser = require('body-parser');
var Trello = require('node-trello');

var devKey = process.env.DEV_KEY;
var appToken = process.env.APP_TOKEN;
var trello = new Trello(devKey, appToken);

var list = process.env.DESTINATION_LIST;
var branch;
var board;
var cardNumber;
var cardID;
var boardID;
var listID;
var listName;

app.use(bodyParser.json());

var server = app.listen(process.env.PORT, function () {
  console.log('Listening at http://%s:%s', server.address().address, server.address().port);
});

app.post('/', function (req, res) {
  //res.send({status: 'Received'});

  var pullRequestTitle = req.body.pull_request.title;

  // Regex would most likely be best in this situation. Since the naming convention for pull requests is not set,
  // pull request names are inconsistent. All we know is that everything up to and including the first number is
  // a representation of the branch to be merged from.

  var branchRegex = /\D+\d+/g;
  try {
    // Grab everything up until and including the first number
    branch = branchRegex.exec(pullRequestTitle)[0];

    // If we were successful at getting the branch name, go ahead and continue
    if (branch) {

      // Trim the branch name of any possible leading/trailing whitespaces
      branch = branch.trim();

      // If there are any whitespaces in between words, replace the whitespaces in between the words
      // with a hyphen. Ex: 'this   is a     branch 50' will be 'this-is-a-branch-50'
      if (branch.indexOf(' ') >= 0) {
        branch = branch.replace(/\s+/g, '-');
      }

      // Convert it all to lowercase since that's how it most likely will appear on GitHub
      branch = branch.toLowerCase();

      // Next, we'll grab the number out of the branch, which is the card number
      // The card number is also the short ID of the Trello card (attribute is idShort)
      var cardNumberRegex = /\d+/g;
      cardNumber = cardNumberRegex.exec(branch)[0];

      // If we were successful in getting the card number, that means the pull request was named in such
      // a way that we are possibly able to find the corresponding card on Trello
      if (cardNumber) {

        board = branch.slice(0, branch.length - cardNumber.length - 1);
        console.log('Card #' + cardNumber + '\nBranch: ' + branch + '\nBoard: ' + board);
        res.send({status: 'Card #' + cardNumber + '\nBranch: ' + branch + '\nBoard: ' + board});

        var action = req.body.action;
        // Now that we have all the information we can get, update the card on Trello

        switch (action) {
          case 'assigned':
            break;
          case 'unassigned':
            break;
          case 'labeled':
            break;
          case 'unlabeled':
            break;
          case 'opened':
            break;
          case 'closed':
            moveCard();
            break;
          case 'reopened':
            break;
          case 'synchronized':
            break;
          // The created action is for when a pull request review comment event occurs
          case 'created':
            break;
        }
        moveCard();
      }

    }

  } catch (error) {
    console.log('The pull request name is not formatted in a way to be found on Trello');
  }

});

/**
 *
 * Moves the card with the specified ID from its current list to the list with the
 * specified ID.
 *
 * @param {string} cardID - ID of the Trello card
 * @param {string} listID - ID of the Trello list
 */
function putCardInList(cardID, listID) {
  trello.put('/1/cards/' + cardID, {idList: listID}, function (error, data) {
    if (error) {
      console.log(error);
    } else {
      console.log(data);
    }
  });
}

/**
 * Upon certain pull request actions, this will move the card in the request into the
 * list specified by the environment variable DESTINATION_LIST
 *
 */
function moveCard() {
  trello.get('/1/members/me/boards?lists=all', function (error, boardsJSON) {
    if (error) {
      console.log(error);
    } else {
      var foundBoard = false;
      for (var i = 0; i < boardsJSON.length && !foundBoard; i++) {
        var boardJSON = boardsJSON[i];
        if (boardJSON.name === board) {
          foundBoard = true;
          boardID = boardJSON.id;

          var foundList = false;
          var listsJSON = boardJSON.lists;
          for (var j = 0; j < listsJSON.length && !foundList; j++) {
            var listJSON = listsJSON[j];
            if (listJSON.name === list) {
              foundList = true;

              listName = listJSON.name;
              listID = listJSON.id;
              trello.get('/1/boards/' + boardID + '/cards?limit=1000', function (error, cardsJSON) {
                if (error) {
                  console.log(error);
                } else {
                  var foundCard = false;
                  for (var k = 0; k < cardsJSON.length && !foundCard; k++) {
                    var cardJSON = cardsJSON[k];
                    if (cardJSON.idShort == cardNumber) {
                      foundCard = true;

                      cardID = cardJSON.id;
                      console.log('Placing \'' + cardJSON.name + '\' into \'' + listName + '\'');
                      // TODO: After card is placed into the list, comment on the card with a message similar to:
                      // TODO: 'Merged by User'
                      putCardInList(cardID, listID);
                    }
                  }
                }
              });
            }
          }
        }
      }
    }
  });
}

<|endoftext|>


<commit_before>var express = require('express')
var app = express()
var moment = require('moment');
var url = require('url');

app.route('/').get(function (req, res) {
	res.sendFile(process.cwd()+'/public/index.html');
});

app.get('/*', function(req, res) {
    var requrl = url.parse(req.url).pathname;
    var cleanreq = requrl.replace(/^\/|\/$|%20+/g, '');

    if (moment(+cleanreq).isValid()|moment(cleanreq).isValid()){

        if (isNaN(cleanreq)) {
            var unixtime = moment(cleanreq.toString(), "MMMM-DD-YYYY").unix()
            var naturaltime = moment(cleanreq.toString(), "MMMM-DD-YYYY").format("MMMM D, YYYY")
        }
        else {
            var unixtime = moment(cleanreq.toString(), "MMMM-DD-YYYY").unix()
            var naturaltime = moment.unix(+cleanreq).format("MMMM D, YYYY")
        }
    }
    else {
        var unixtime = null
        var naturaltime = null
    }

    var jsonstring = {
        unix : unixtime,
        natural : naturaltime
    }
    res.send(JSON.stringify(jsonstring))
});

app.listen(80, function() {
	console.log('Node.js listening on port 8080 ...')
})
<commit_msg>update<commit_after>var express = require('express')
var app = express()
var moment = require('moment');
var url = require('url');

app.route('/').get(function (req, res) {
	res.sendFile(process.cwd()+'/public/index.html');
});

app.get('/*', function(req, res) {
    var requrl = url.parse(req.url).pathname;
    var cleanreq = requrl.replace(/^\/|\/$|%20+/g, '');

    if (moment(+cleanreq).isValid()|moment(cleanreq).isValid()){

        if (isNaN(cleanreq)) {
            var unixtime = moment(cleanreq.toString(), "MMMM-DD-YYYY").unix()
            var naturaltime = moment(cleanreq.toString(), "MMMM-DD-YYYY").format("MMMM D, YYYY")
        }
        else {
            var unixtime = moment(cleanreq.toString(), "MMMM-DD-YYYY").unix()
            var naturaltime = moment.unix(+cleanreq).format("MMMM D, YYYY")
        }
    }
    else {
        var unixtime = null
        var naturaltime = null
    }

    var jsonstring = {
        unix : unixtime,
        natural : naturaltime
    }
    res.send(JSON.stringify(jsonstring))
});

app.listen($PORT, function() {
	console.log('Node.js listening on port 8080 ...')
})
<|endoftext|>