<commit_before>#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const git = require('gitty');
const exec = require('child_process').exec;
const serial = function(i, arr, callback){
	if(i>=arr.length) return callback();
	arr[i](function(){
		serial(++i, arr, callback);
	});
}
const signals = {};
let lock = false;
let count = 1;
const inc = ()=>++count;
const dec = ()=>{
	if(--count===0) waw.done('modules installed');
};
const node_file = `module.exports.command = function(waw) {\n\t// add your Run code\n};`;
const waw = {
	waw_root: __dirname,
	project_root: process.cwd(),
	core_modules: {
		core: 'https://github.com/WebArtWork/core.git'
	},
	core_orgs: {
		waw: 'https://github.com/WebArtWork/NAME.git'
	},
	core_module: name => waw.core_orgs.waw.replace('NAME', name),
	isDirectory: source => fs.lstatSync(source).isDirectory(),
	getDirectories: function(source) {
		if (!fs.existsSync(source)) {
			return [];
		}
		return fs.readdirSync(source).map(name => require('path').join(source, name)).filter(this.isDirectory);
	},
	isFile: source => fs.lstatSync(source).isFile(),
	getFiles: function(source) {
		fs.readdirSync(source).map(name => path.join(source, name)).filter(this.isFile)
	},
	getFilesRecursively: function(source, opts={}) {
		let dirs = this.getDirectories(source);
		let files = dirs.map(dir => this.getFilesRecursively(dir)).reduce((a,b) => a.concat(b), []);
		files = files.concat(this.getFiles(source));
		if(opts.end){
			for (var i = files.length - 1; i >= 0; i--) {
				if(!files[i].endsWith(opts.end)){
					files.splice(i, 1);
				}
			}
		}
		return files;
	},
    readJson: function(source){
    	if (fs.existsSync(source) && this.isFile(source)) {
    		try {
    			return JSON.parse(fs.readFileSync(source));
    		} catch(e){
    			return {};
    		}
    	} else return {};
    },
    writeJson: (path, json)=> fs.writeFileSync(path, JSON.stringify(json)),
    uniteJson: (toObj, fromObj, replace = true)=>{
		for(const each in fromObj){
			if(replace || !toObj[each]) {
				toObj[each] = fromObj[each];
			}
		}
    },
    uniteArray: (toArray, fromArray)=>{
    	for (var i = 0; i < fromArray.length; i++) {
    		toArray.push(fromArray[i]);
    	}
    },
	fetch: (folder, repo, callback, branch='master') => {
		fs.mkdirSync(folder, { recursive: true });
		folder = git(folder);
		folder.init(function(){
			folder.addRemote('origin', repo, function(err){
				folder.fetch('--all', function(err){
					folder.reset('origin/'+branch, callback);
				});
			});
		});
	},
	parallel: (arr, callback) => {
		let counter = arr.length;
		if(counter===0) return callback();
		for (let i = 0; i < arr.length; i++) {
			arr[i](function(){
				if(--counter===0) callback();
			});
		}
	},
	each: function(arrOrObj, func, callback=()=>{}, isSerial=false){
		if(typeof callback == 'boolean'){
			isSerial = callback;
			callback = ()=>{};
		}
		if(Array.isArray(arrOrObj)){
			let counter = arrOrObj.length;
			if(counter===0) return callback();
			if(isSerial){
				let serialArr = [];
				for (let i = 0; i < arrOrObj.length; i++) {
					serialArr.push(function(next){
						func(arrOrObj[i], function(){
							if(--counter===0) callback();
							else next();
						}, i);
					});
				}
				serial(0, serialArr, callback);
			}else{
				for (let i = 0; i < arrOrObj.length; i++) {
					func(arrOrObj[i], function(){
						if(--counter===0) callback();
					}, i);
				}
			}
		}else if(typeof arrOrObj == 'object'){
			if(isSerial){
				let serialArr = [];
				let arr = [];
				for(let each in arrOrObj){
					arr.push({
						value: arrOrObj[each],
						each: each
					});
				}
				let counter = arr.length;
				for (let i = 0; i < arr.length; i++) {
					serialArr.push(function(next){
						func(arr[i].each, arr[i].value, function(){
							if(--counter===0) callback();
							else next();
						}, i);
					});
				}
				serial(0, serialArr, callback);
			}else{
				let counter = 1;
				for(let each in arrOrObj){
					counter++;
					func(each, arrOrObj[each], function(){
						if(--counter===0) callback();
					});
				}
				if(--counter===0) callback();
			}
		}else callback();
	},
	node_files: (source, files, isRouter = false) => {
		if(typeof files == 'object' && files.src){
			files = [files.src];
		}else if(typeof files === 'string'){
			files = files.split(' ');
		}
		for (var i = files.length - 1; i >= 0; i--) {
			if (typeof files[i] === 'object' ) {
				files[i] = files[i].src;
			}
			if (!fs.existsSync(source+'/'+files[i])) {
				let code = node_file;
				if(isRouter){
					code = code.replace('.command', '').replace('Run', 'Router');
				}
				fs.writeFileSync(path.resolve(source, files[i]), code, 'utf8');
			}
			files[i] = require(path.resolve(source, files[i]));
		}
		return files;
	},
	npmi: function(opts, next=()=>{}) {
		if (lock) {
			return setTimeout(() => {
				waw.npmi(opts, next);
			}, 100);
		}
		lock = true;
		opts.name = path.normalize(opts.name);
		if (fs.existsSync(path.resolve(opts.path, opts.name))) {
			return next();
		}
		let cmdString = "npm install " + opts.name;
		if (opts.version == '*') opts.version = '';
		cmdString += (opts.version ? "@" + opts.version : "");
		cmdString += ' --prefix ' + opts.path;
		cmdString += (opts.global ? " -g" : "");
		cmdString += (opts.save ? " --save" : "");
		cmdString += (opts.saveDev ? " --save-dev" : "");
		cmdString += (opts.legacyBundling ? " --legacy-bundling" : "");
		cmdString += (opts.noOptional ? " --no-optional" : "");
		cmdString += (opts.ignoreScripts ? " --ignore-scripts" : "");
		const cmd = exec(cmdString, {
			cwd: opts.path ? opts.path : "/",
			maxBuffer: opts.maxBuffer ? opts.maxBuffer : 200 * 1024
		}, (error, stdout, stderr) => {
			if (error) {
				console.log("I cloudn't install " + opts.name + " on path " + opts.path);
				process.exit();
			} else {
				lock = false;
				console.log("Module installed: " + opts.name);
				next();
			}
		});
		if (opts.output) {
			var consoleOutput = function (msg) {
				console.log('npm: ' + msg);
			};
			cmd.stdout.on('data', consoleOutput);
			cmd.stderr.on('data', consoleOutput);
		}
	},
	install: {
		global: function(name, callback, branch = 'master'){
			const source = path.resolve(__dirname, 'server', name);
			if(fs.existsSync(source)){
				waw.modules.push(read_module(source, name));
			} else {
				console.log('Installing Global Module', name);
				waw.fetch(source, waw.core_module(name), () => {
					waw.modules.push(read_module(source, name));
					callback();
				}, branch);
			}
		},
		npmi: function(source, dependencies, callback=()=>{}){
			if (typeof dependencies !== 'object' || !Object.keys(dependencies)) return callback();
			inc();
			waw.each(dependencies, (name, version, next) => {
				if (fs.existsSync(path.resolve(source, 'node_modules', name))) {
					return next();
				}
				inc();
				waw.npmi({
					path: source,
					name,
					version
				}, ()=>{
					dec();
					next();
				});
			}, () => {
				dec();
				callback();
			});
		}
	},
	emit: function (signal) {
		for (var i = 0; i < signals[signal].length; i++) {
			signals[signal][i]();
		}
	},
	on: function (signal, callback) {
		if (!signals[signal]) signals[signal] = [];
		if (typeof callback === 'function') signals[signal].push(callback);
	},
	done: function (signal) {
		signals['done' + signal] = true;
	},
	ready: function (signal, callback) {
		if (signals['done' + signal]) {
			callback();
		} else {
			setTimeout(()=>{
				waw.ready(signal, callback);
			}, 100);
		}
	}
}
waw.config = waw.readJson(process.cwd()+'/config.json');
waw.uniteJson(waw.config, waw.readJson(process.cwd()+'/server.json'));
if (fs.existsSync(process.cwd()+'/angular.json')) {
	waw.core_modules.angular = waw.core_module('angular');
}
if (fs.existsSync(process.cwd()+'/template.json')) {
	waw.core_modules.template = waw.core_module('template');
	waw.core_modules.sem = waw.core_module('sem');
}
const read_module = (source, name) => {
	config = waw.readJson(source+'/module.json');
	waw.uniteJson(config, waw.readJson(source+'/part.json'));
	waw.install.npmi(source, config.dependencies);
	config.__root = path.normalize(source);
	config.__name = name;
	waw._modules[config.__name] = config;
	return config;
}
if (typeof waw.config.server !== 'string') {
	waw.config.server = 'server';
}
waw.install.npmi(process.cwd(), waw.config.dependencies, dec);
const modules_root = process.cwd() + path.sep + waw.config.server;
waw.modules = [];
waw._modules = {};
if(waw.isDirectory(modules_root)){
	waw.uniteArray(waw.modules, waw.getDirectories(modules_root).filter(path => {
		return !path.endsWith('.git') && !path.endsWith('node_modules')
	}));
	waw.module = name => waw._modules[name];
	for (let i = 0; i < waw.modules.length; i++) {
		waw.modules[i] = read_module(waw.modules[i], path.basename(waw.modules[i]));
	}
}
if(waw.config.parts) {
	waw.each(waw.config.parts, module => waw.install.global(module));
}
if(waw.config.modules) {
	waw.each(waw.config.modules, module => waw.install.global(module));
}
if(!waw.modules.length) {
	waw.each(waw.core_modules, module => waw.install.global(module));
}
module.exports = waw;
<commit_msg>fixed error with callback<commit_after>#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const git = require('gitty');
const exec = require('child_process').exec;
const { type } = require('os');
const serial = function(i, arr, callback){
	if(i>=arr.length) return callback();
	arr[i](function(){
		serial(++i, arr, callback);
	});
}
const signals = {};
let lock = false;
let count = 1;
const inc = ()=>++count;
const dec = ()=>{
	if(--count===0) waw.done('modules installed');
};
const node_file = `module.exports.command = function(waw) {\n\t// add your Run code\n};`;
const waw = {
	waw_root: __dirname,
	project_root: process.cwd(),
	core_modules: {
		core: 'https://github.com/WebArtWork/core.git'
	},
	core_orgs: {
		waw: 'https://github.com/WebArtWork/NAME.git'
	},
	core_module: name => waw.core_orgs.waw.replace('NAME', name),
	isDirectory: source => fs.lstatSync(source).isDirectory(),
	getDirectories: function(source) {
		if (!fs.existsSync(source)) {
			return [];
		}
		return fs.readdirSync(source).map(name => require('path').join(source, name)).filter(this.isDirectory);
	},
	isFile: source => fs.lstatSync(source).isFile(),
	getFiles: function(source) {
		fs.readdirSync(source).map(name => path.join(source, name)).filter(this.isFile)
	},
	getFilesRecursively: function(source, opts={}) {
		let dirs = this.getDirectories(source);
		let files = dirs.map(dir => this.getFilesRecursively(dir)).reduce((a,b) => a.concat(b), []);
		files = files.concat(this.getFiles(source));
		if(opts.end){
			for (var i = files.length - 1; i >= 0; i--) {
				if(!files[i].endsWith(opts.end)){
					files.splice(i, 1);
				}
			}
		}
		return files;
	},
    readJson: function(source){
    	if (fs.existsSync(source) && this.isFile(source)) {
    		try {
    			return JSON.parse(fs.readFileSync(source));
    		} catch(e){
    			return {};
    		}
    	} else return {};
    },
    writeJson: (path, json)=> fs.writeFileSync(path, JSON.stringify(json)),
    uniteJson: (toObj, fromObj, replace = true)=>{
		for(const each in fromObj){
			if(replace || !toObj[each]) {
				toObj[each] = fromObj[each];
			}
		}
    },
    uniteArray: (toArray, fromArray)=>{
    	for (var i = 0; i < fromArray.length; i++) {
    		toArray.push(fromArray[i]);
    	}
    },
	fetch: (folder, repo, callback, branch='master') => {
		fs.mkdirSync(folder, { recursive: true });
		folder = git(folder);
		folder.init(function(){
			folder.addRemote('origin', repo, function(err){
				folder.fetch('--all', function(err){
					folder.reset('origin/'+branch, callback);
				});
			});
		});
	},
	parallel: (arr, callback) => {
		let counter = arr.length;
		if(counter===0) return callback();
		for (let i = 0; i < arr.length; i++) {
			arr[i](function(){
				if(--counter===0) callback();
			});
		}
	},
	each: function(arrOrObj, func, callback=()=>{}, isSerial=false){
		if(typeof callback == 'boolean'){
			isSerial = callback;
			callback = ()=>{};
		}
		if(Array.isArray(arrOrObj)){
			let counter = arrOrObj.length;
			if(counter===0) return callback();
			if(isSerial){
				let serialArr = [];
				for (let i = 0; i < arrOrObj.length; i++) {
					serialArr.push(function(next){
						func(arrOrObj[i], function(){
							if(--counter===0) callback();
							else next();
						}, i);
					});
				}
				serial(0, serialArr, callback);
			}else{
				for (let i = 0; i < arrOrObj.length; i++) {
					func(arrOrObj[i], function(){
						if(--counter===0) callback();
					}, i);
				}
			}
		}else if(typeof arrOrObj == 'object'){
			if(isSerial){
				let serialArr = [];
				let arr = [];
				for(let each in arrOrObj){
					arr.push({
						value: arrOrObj[each],
						each: each
					});
				}
				let counter = arr.length;
				for (let i = 0; i < arr.length; i++) {
					serialArr.push(function(next){
						func(arr[i].each, arr[i].value, function(){
							if(--counter===0) callback();
							else next();
						}, i);
					});
				}
				serial(0, serialArr, callback);
			}else{
				let counter = 1;
				for(let each in arrOrObj){
					counter++;
					func(each, arrOrObj[each], function(){
						if(--counter===0) callback();
					});
				}
				if(--counter===0) callback();
			}
		}else callback();
	},
	node_files: (source, files, isRouter = false) => {
		if(typeof files == 'object' && files.src){
			files = [files.src];
		}else if(typeof files === 'string'){
			files = files.split(' ');
		}
		for (var i = files.length - 1; i >= 0; i--) {
			if (typeof files[i] === 'object' ) {
				files[i] = files[i].src;
			}
			if (!fs.existsSync(source+'/'+files[i])) {
				let code = node_file;
				if(isRouter){
					code = code.replace('.command', '').replace('Run', 'Router');
				}
				fs.writeFileSync(path.resolve(source, files[i]), code, 'utf8');
			}
			files[i] = require(path.resolve(source, files[i]));
		}
		return files;
	},
	npmi: function(opts, next=()=>{}) {
		if (lock) {
			return setTimeout(() => {
				waw.npmi(opts, next);
			}, 100);
		}
		lock = true;
		opts.name = path.normalize(opts.name);
		if (fs.existsSync(path.resolve(opts.path, opts.name))) {
			return next();
		}
		let cmdString = "npm install " + opts.name;
		if (opts.version == '*') opts.version = '';
		cmdString += (opts.version ? "@" + opts.version : "");
		cmdString += ' --prefix ' + opts.path;
		cmdString += (opts.global ? " -g" : "");
		cmdString += (opts.save ? " --save" : "");
		cmdString += (opts.saveDev ? " --save-dev" : "");
		cmdString += (opts.legacyBundling ? " --legacy-bundling" : "");
		cmdString += (opts.noOptional ? " --no-optional" : "");
		cmdString += (opts.ignoreScripts ? " --ignore-scripts" : "");
		const cmd = exec(cmdString, {
			cwd: opts.path ? opts.path : "/",
			maxBuffer: opts.maxBuffer ? opts.maxBuffer : 200 * 1024
		}, (error, stdout, stderr) => {
			if (error) {
				console.log("I cloudn't install " + opts.name + " on path " + opts.path);
				process.exit();
			} else {
				lock = false;
				console.log("Module installed: " + opts.name);
				next();
			}
		});
		if (opts.output) {
			var consoleOutput = function (msg) {
				console.log('npm: ' + msg);
			};
			cmd.stdout.on('data', consoleOutput);
			cmd.stderr.on('data', consoleOutput);
		}
	},
	install: {
		global: function(name, callback=()=>{}, branch = 'master'){
			const source = path.resolve(__dirname, 'server', name);
			if(fs.existsSync(source)){
				waw.modules.push(read_module(source, name));
			} else {
				console.log('Installing Global Module', name);
				waw.fetch(source, waw.core_module(name), () => {
					waw.modules.push(read_module(source, name));
					if(typeof callback === 'function') callback();
				}, branch);
			}
		},
		npmi: function(source, dependencies, callback=()=>{}){
			if (typeof dependencies !== 'object' || !Object.keys(dependencies)) return callback();
			inc();
			waw.each(dependencies, (name, version, next) => {
				if (fs.existsSync(path.resolve(source, 'node_modules', name))) {
					return next();
				}
				inc();
				waw.npmi({
					path: source,
					name,
					version
				}, ()=>{
					dec();
					next();
				});
			}, () => {
				dec();
				callback();
			});
		}
	},
	emit: function (signal) {
		for (var i = 0; i < signals[signal].length; i++) {
			signals[signal][i]();
		}
	},
	on: function (signal, callback) {
		if (!signals[signal]) signals[signal] = [];
		if (typeof callback === 'function') signals[signal].push(callback);
	},
	done: function (signal) {
		signals['done' + signal] = true;
	},
	ready: function (signal, callback) {
		if (signals['done' + signal]) {
			callback();
		} else {
			setTimeout(()=>{
				waw.ready(signal, callback);
			}, 100);
		}
	}
}
waw.config = waw.readJson(process.cwd()+'/config.json');
waw.uniteJson(waw.config, waw.readJson(process.cwd()+'/server.json'));
if (fs.existsSync(process.cwd()+'/angular.json')) {
	waw.core_modules.angular = waw.core_module('angular');
}
if (fs.existsSync(process.cwd()+'/template.json')) {
	waw.core_modules.template = waw.core_module('template');
	waw.core_modules.sem = waw.core_module('sem');
}
const read_module = (source, name) => {
	config = waw.readJson(source+'/module.json');
	waw.uniteJson(config, waw.readJson(source+'/part.json'));
	waw.install.npmi(source, config.dependencies);
	config.__root = path.normalize(source);
	config.__name = name;
	waw._modules[config.__name] = config;
	return config;
}
if (typeof waw.config.server !== 'string') {
	waw.config.server = 'server';
}
waw.install.npmi(process.cwd(), waw.config.dependencies, dec);
const modules_root = process.cwd() + path.sep + waw.config.server;
waw.modules = [];
waw._modules = {};
if(waw.isDirectory(modules_root)){
	waw.uniteArray(waw.modules, waw.getDirectories(modules_root).filter(path => {
		return !path.endsWith('.git') && !path.endsWith('node_modules')
	}));
	waw.module = name => waw._modules[name];
	for (let i = 0; i < waw.modules.length; i++) {
		waw.modules[i] = read_module(waw.modules[i], path.basename(waw.modules[i]));
	}
}
if(waw.config.parts) {
	waw.each(waw.config.parts, module => waw.install.global(module));
}
if(waw.config.modules) {
	waw.each(waw.config.modules, module => waw.install.global(module));
}
if(!waw.modules.length) {
	waw.each(waw.core_modules, module => waw.install.global(module));
}
module.exports = waw;
<|endoftext|>


<commit_before>var crypto = require('crypto');
var path = require('path');

var bcrypt = require('bcrypt');
var bodyParser = require('body-parser');
var compress = require('compression');
var connectRedis = require('connect-redis');
var cookieParser = require('cookie-parser');
var express = require('express');
var favicon = require('serve-favicon');
var LocalStrat = require('passport-local');
var nodemailer = require('nodemailer');
var passport = require('passport');
var Q = require('q');
var serveStatic = require('serve-static');
var session = require('express-session');

var apiRoute = require('./api/root.js');
var DB = require('./database.js');
var logger = require('./logger.js');
var LoL = require('./lol.js');
var Redis = require('./redis.js');
var settings = require('./settings.js');
var Stats = require('./statistics.js');

module.exports = {
  createApp: function() {
    var db = new DB();
    var redis = new Redis();
    var lol = new LoL(redis);
    var stats = new Stats(db, lol);

    var promise = db.init().then(function() {
      return redis.init(true, true, true);
    }).then(function() {
      return lol.init();
    }).then(function() {
      var app = express();
      var RedisStore = connectRedis(session);

      app.use(serveStatic(path.join(__dirname, '../public'), {
        redirect: false,
        maxAge: settings.is_prod ? settings.asset_cache_time : 0,
      }));
      app.use(favicon(path.join(__dirname, '../public/imgs/favicon.ico')));
      app.use(bodyParser.json());
      app.use(bodyParser.urlencoded({
        extended: true,
      }));
      app.use(cookieParser(settings.secret_key, {
        secure: settings.is_prod,
        maxAge: settings.cookie_age,
      }));
      app.use(session({
        secret: settings.secret_key,
        resave: false,
        saveUninitialized: true,
        store: new RedisStore({
          host: settings.redis_host,
          port: settings.redis_port
        }),
        rolling: true,
        cookie: {
          secure: settings.is_prod,
          maxAge: settings.cookie_age,
        },
      }));
      app.use(passport.initialize());
      app.use(passport.session());
      app.use(compress());

      passport.use(new LocalStrat({
        passReqToCallback: true,
      }, function(req, username, password, done) {
        redis.logInAllowed(req.ip, username).done(function(allowed) {
          if (!allowed) {
            done(null, false, {
              reason: 'throttled',
            });
          } else {
            db.getUser(username).done(function(user) {
              if (!user) {
                done(null, false, {
                  reason: 'invalid',
                });
              } else {
                Q.ninvoke(bcrypt, 'compare', password, user.password_hash).done(function(result) {
                  if (!result) {
                    done(null, false, {
                      reason: 'invalid',
                    });
                  } else {
                    done(null, {
                      username: user.username,
                      region: user.region,
                      summonerName: user.summoner_name
                    });
                  }
                });
              }
            });
          }
        });
      }));

      passport.serializeUser(function(user, done) {
        done(null, user.username);
      });

      passport.deserializeUser(function(username, done) {
        db.getUser(username).done(function(user) {
          if (!user) {
            done(null, false);
          } else {
            done(null, {
              username: username,
              region: user.region,
              summonerName: user.summoner_name,
            });
          }
        });
      });

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

      app.use('*', function(req, res) {
        var token = crypto.randomBytes(16);
        token = token.toString('base64').replace(/=/g, '');
        res.header('Set-Cookie', 'csrf=' + token + ';Path=/' + (settings.is_prod ? ';Secure' : ''));
        res.header('Cache-Control', 'no-cache,private');
        res.sendFile('index.html', {
          root: path.join(__dirname, '../public'),
        });
      });

      app.set('trust proxy', 'loopback');

      app.locals.db = db;
      app.locals.redis = redis;
      app.locals.lol = lol;
      app.locals.stats = stats;
      app.locals.emailer = nodemailer.createTransport(settings.email_url);

      return app;
    });

    return promise;
  }
};
<commit_msg>Made favicon use setting for cache time<commit_after>var crypto = require('crypto');
var path = require('path');

var bcrypt = require('bcrypt');
var bodyParser = require('body-parser');
var compress = require('compression');
var connectRedis = require('connect-redis');
var cookieParser = require('cookie-parser');
var express = require('express');
var favicon = require('serve-favicon');
var LocalStrat = require('passport-local');
var nodemailer = require('nodemailer');
var passport = require('passport');
var Q = require('q');
var serveStatic = require('serve-static');
var session = require('express-session');

var apiRoute = require('./api/root.js');
var DB = require('./database.js');
var logger = require('./logger.js');
var LoL = require('./lol.js');
var Redis = require('./redis.js');
var settings = require('./settings.js');
var Stats = require('./statistics.js');

module.exports = {
  createApp: function() {
    var db = new DB();
    var redis = new Redis();
    var lol = new LoL(redis);
    var stats = new Stats(db, lol);

    var promise = db.init().then(function() {
      return redis.init(true, true, true);
    }).then(function() {
      return lol.init();
    }).then(function() {
      var app = express();
      var RedisStore = connectRedis(session);

      app.use(serveStatic(path.join(__dirname, '../public'), {
        redirect: false,
        maxAge: settings.is_prod ? settings.asset_cache_time : 0,
      }));
      app.use(favicon(path.join(__dirname, '../public/imgs/favicon.ico'), {
        maxAge: settings.is_prod ? settings.asset_cache_time : 0,
      }));
      app.use(bodyParser.json());
      app.use(bodyParser.urlencoded({
        extended: true,
      }));
      app.use(cookieParser(settings.secret_key, {
        secure: settings.is_prod,
        maxAge: settings.cookie_age,
      }));
      app.use(session({
        secret: settings.secret_key,
        resave: false,
        saveUninitialized: true,
        store: new RedisStore({
          host: settings.redis_host,
          port: settings.redis_port
        }),
        rolling: true,
        cookie: {
          secure: settings.is_prod,
          maxAge: settings.cookie_age,
        },
      }));
      app.use(passport.initialize());
      app.use(passport.session());
      app.use(compress());

      passport.use(new LocalStrat({
        passReqToCallback: true,
      }, function(req, username, password, done) {
        redis.logInAllowed(req.ip, username).done(function(allowed) {
          if (!allowed) {
            done(null, false, {
              reason: 'throttled',
            });
          } else {
            db.getUser(username).done(function(user) {
              if (!user) {
                done(null, false, {
                  reason: 'invalid',
                });
              } else {
                Q.ninvoke(bcrypt, 'compare', password, user.password_hash).done(function(result) {
                  if (!result) {
                    done(null, false, {
                      reason: 'invalid',
                    });
                  } else {
                    done(null, {
                      username: user.username,
                      region: user.region,
                      summonerName: user.summoner_name
                    });
                  }
                });
              }
            });
          }
        });
      }));

      passport.serializeUser(function(user, done) {
        done(null, user.username);
      });

      passport.deserializeUser(function(username, done) {
        db.getUser(username).done(function(user) {
          if (!user) {
            done(null, false);
          } else {
            done(null, {
              username: username,
              region: user.region,
              summonerName: user.summoner_name,
            });
          }
        });
      });

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

      app.use('*', function(req, res) {
        var token = crypto.randomBytes(16);
        token = token.toString('base64').replace(/=/g, '');
        res.header('Set-Cookie', 'csrf=' + token + ';Path=/' + (settings.is_prod ? ';Secure' : ''));
        res.header('Cache-Control', 'no-cache,private');
        res.sendFile('index.html', {
          root: path.join(__dirname, '../public'),
        });
      });

      app.set('trust proxy', 'loopback');

      app.locals.db = db;
      app.locals.redis = redis;
      app.locals.lol = lol;
      app.locals.stats = stats;
      app.locals.emailer = nodemailer.createTransport(settings.email_url);

      return app;
    });

    return promise;
  }
};
<|endoftext|>


<commit_before>//Get our passwords
var v = 1.0;

chrome.extension.onRequest.addListener(
	function(request, sender, sendResponse)
	{
		var passes = JSON.parse(localStorage['passwords'] || '[]');

		//Our message has a tab id or extension id
		if(sender.tab || sender.id)
		{
				//The content script is just asking for options
			if(request.message == 'options')
			{
				sendResponse(JSON.parse(localStorage['options'] || '{}'));
			}
			//The content script is asking us what to do!
			else if (request.message == 'init' || request.message == 'request')
			{

				//No passwords in db, so send a quick message to tell the page.
				if(passes.length==0 && request.message=='init')
				{
					sendResponse({length: 0});
				}

				//We've only got one password, or we're only being asked for one...
				else if(passes.length==1 || (request.id && request.id.length>0))
				{
					id = parseInt(passes.length)==1?passes[0]:request.id;
					sendPass = Pass.init(id);

					if(request.password && request.password.length>0)
					{
						//We've been sent a password, so we should apply it (potentially).
						sendPass.password(request.password);
					}
					//Send back a generated password
					sendResponse(sendPass.generate(sender.tab.url,request.disabletld));
				}
				//We've got lots of passwords, so present the user with a list of selections:
				else if(passes.length>1 && request.message=='init')
				{
					var response = {};
					passes.forEach(function(id)
					{
						response[id] =
						{
							id: id,
							name: localStorage['password_'+id+'_name'],
							hash: localStorage['password_'+id+'_type']=='hash'?
								localStorage['password_'+id+'_password']:false
						}
					});
					sendResponse({length: passes.length, passes: response})
				}
			}
			else if(request.message == 'versioncheck')
			{
				/* Version check! */
				if(!localStorage['version'] || localStorage['version']<v)
				{
					if(request.notify)
					{
						localStorage['version'] = v.toFixed(1);
					}
					else
					{
						//chrome.experimental.infobars.show({path: 'scp_info_updated.html'});
						sendResponse(
						{
							notify: true,
							message: 'SuperChromePass has been updated to the latest version ('+
							v.toFixed(1).toString()+'). Click the options button for more:'
						});
					}
				}
			}
			else
			{
					console.warn('Snubbing due to bad message:');
					sendResponse({});
			}
		}
});
<commit_msg>Added extra instance to support the problem behind issue 22. Fixes issue 22<commit_after>//Get our passwords
var v = 1.0;

chrome.extension.onRequest.addListener(
	function(request, sender, sendResponse)
	{
		var passes = JSON.parse(localStorage['passwords'] || '[]');

    console.log(request,sender,sendResponse);

		//Our message has a tab id or extension id
		if(sender.tab || sender.id)
		{
				//The content script is just asking for options
			if(request.message == 'options')
			{
				sendResponse(JSON.parse(localStorage['options'] || '{}'));
			}
			//The content script is asking us what to do!
			else if (request.message == 'init' || request.message == 'request')
			{

				//No passwords in db, so send a quick message to tell the page.
				if(passes.length==0 && request.message=='init')
				{
					sendResponse({length: 0});
				}

				//We've only got one password, or we're only being asked for one...
				else if(passes.length==1 || (request.id && request.id.length>0))
				{
					id = parseInt(passes.length)==1?passes[0]:request.id;
					sendPass = Pass.init(id);

					if(request.password && request.password.length>0)
					{
						//We've been sent a password, so we should apply it (potentially).
						sendPass.password(request.password);
					}
					//Send back a generated password
					sendResponse(sendPass.generate(sender.tab.url,request.disabletld));
				}
				//We've got lots of passwords, so present the user with a list of selections:
				else if(passes.length>1 && request.message=='init')
				{
					var response = {};
					passes.forEach(function(id)
					{
						response[id] =
						{
							id: id,
							name: localStorage['password_'+id+'_name'],
							hash: localStorage['password_'+id+'_type']=='hash'?
								localStorage['password_'+id+'_password']:false
						}
					});
					sendResponse({length: passes.length, passes: response})
				}
        //Add a catch for when there are no profiles but a password needs generating
        else if(passes.length==0 && request.message=='request')
        {
          sendPass = Pass.none;
          sendPass.password(request.password);
          sendResponse(sendPass.generate(sender.tab.url,request.disabletld));
        }
			}
			else if(request.message == 'versioncheck')
			{
				/* Version check! */
				if(!localStorage['version'] || localStorage['version']<v)
				{
					if(request.notify)
					{
						localStorage['version'] = v.toFixed(1);
					}
					else
					{
						//chrome.experimental.infobars.show({path: 'scp_info_updated.html'});
						sendResponse(
						{
							notify: true,
							message: 'SuperChromePass has been updated to the latest version ('+
							v.toFixed(1).toString()+'). Click the options button for more:'
						});
					}
				}
			}
			else
			{
					console.warn('Snubbing due to bad message:');
					sendResponse({});
			}
		}
});
<|endoftext|>


<commit_before>var _ = require('underscore'),
    i18n = require('i18n-abide'),
    path = require('path'),
    expressValidator = require('express-validator'),
    moment = require('moment'),
    flash = require('connect-flash'),
    cookieParser = require('cookie-parser'),
    bodyParser = require('body-parser'),
    methodOverride = require('method-override'),
    session = require('express-session'),
    logger = require('morgan'),
    errorHandler = require('errorHandler'),

    config = {
        siteName: 'localhost',
        sessionSecret: 'localhost',
        cookieSecret: 'hostlocal',
        uri: 'http://localhost:3000/',
        port: process.env.PORT || 3000,
        db_name: process.env.DB_NAME || 'test',
        auth: {},
        redis: {},
        languages: ['en'],
        default_language: 'en',
        translation_directory: '../../public/js'
    };

module.exports = function(express, settings){
    var app = express();

    settings = settings || {};
    config = _.extend(config, settings);

    app.conf = config;

    app.use(cookieParser(app.conf.cookieSecret));

    // ## Environment specific configuration
    // Development settings
    if (app.settings.env === 'development'){
        app.use(logger('dev'));

        app.use(errorHandler({
            dumpExceptions: true,
            showStack: true
        }));

        if (config.redis.host !== undefined && config.redis.port !== undefined){
            console.info('[libby] sessions in redis %s:%s', app.conf.redis.host, app.conf.redis.port);
            var RedisStore = require('connect-redis')(session);
            app.use(session({
                store: new RedisStore({
                    host: app.conf.redis.host,
                    port: app.conf.redis.port
                }),
                secret: app.conf.sessionSecret
            }));
        }
        else {
            console.info('[libby] sessions in memory');
            app.use(session({secret:'testing-secret'}));
        }
    };

    // Test settings
    if (app.settings.env === 'test'){
        app.use(logger('dev'));

        app.use(errorHandler({
            dumpExceptions: true,
            showStack: true
        }));

        app.use(session({secret:'testing-secret'}));
    };

    // Production settings
    if (app.settings.env === 'production'){
        app.use(logger());

        app.use(errorHandler());

        if (config.redis.host !== undefined && config.redis.port !== undefined){
            console.info('[libby] sessions in redis %s:%s', app.conf.redis.host, app.conf.redis.port);
            var RedisStore = require('connect-redis')(express);
            app.use(session({
                store: new RedisStore({
                    host: app.conf.redis.host,
                    port: app.conf.redis.port
                }),
                secret: app.conf.sessionSecret
            }));
        }
        else {
            console.info('[libby] sessions in memory in production!');
            app.use(session({secret: app.conf.sessionSecret}));
        }
    };

    // Parses x-www-form-urlencoded request bodies (and json)
    app.use(bodyParser());
    app.use(methodOverride());

    app.use(flash());
    app.use(function(req, res, next){
        res.locals.messages = req.flash();
        next();
    });

    app.use(expressValidator({
        errorFormatter: function(param, msg, value) {
            var namespace = param.split('.'),
                root = namespace.shift(),
                formParam = root;

            while(namespace.length) {
                formParam += '[' + namespace.shift() + ']';
            }
            return {
                param: formParam,
                msg: msg,
                value: value
            };
        }
    }));

    // Translation settings
    console.info('[libby] i18n-abide default: %s -- supported: %s', app.conf.default_language, app.conf.languages.join(', '));
    console.info('[libby] i18n-abide translation directory: %s', app.conf.translation_directory);
    app.use(i18n.abide({
        supported_languages: app.conf.languages,
        default_lang: app.conf.default_language,
        translation_directory: app.conf.translation_directory
    }));

    // Middleware setting __ translation shortcut
    app.use(function(req, res, next){
        res.locals.__ = res.locals.gettext;
        next();
    });

    return app;
};
<commit_msg>Trust proxy setting<commit_after>var _ = require('underscore'),
    i18n = require('i18n-abide'),
    path = require('path'),
    expressValidator = require('express-validator'),
    moment = require('moment'),
    flash = require('connect-flash'),
    cookieParser = require('cookie-parser'),
    bodyParser = require('body-parser'),
    methodOverride = require('method-override'),
    session = require('express-session'),
    logger = require('morgan'),
    errorHandler = require('errorHandler'),

    config = {
        siteName: 'localhost',
        sessionSecret: 'localhost',
        cookieSecret: 'hostlocal',
        uri: 'http://localhost:3000/',
        port: process.env.PORT || 3000,
        db_name: process.env.DB_NAME || 'test',
        auth: {},
        redis: {},
        languages: ['en'],
        default_language: 'en',
        translation_directory: '../../public/js',
        trust_proxy: false
    };

module.exports = function(express, settings){
    var app = express();

    settings = settings || {};
    config = _.extend(config, settings);

    app.conf = config;

    if (settings.trust_proxy){
        app.enable('trust proxy');
    }

    app.use(cookieParser(app.conf.cookieSecret));

    // ## Environment specific configuration
    // Development settings
    if (app.settings.env === 'development'){
        app.use(logger('dev'));

        app.use(errorHandler({
            dumpExceptions: true,
            showStack: true
        }));

        if (config.redis.host !== undefined && config.redis.port !== undefined){
            console.info('[libby] sessions in redis %s:%s', app.conf.redis.host, app.conf.redis.port);
            var RedisStore = require('connect-redis')(session);
            app.use(session({
                store: new RedisStore({
                    host: app.conf.redis.host,
                    port: app.conf.redis.port
                }),
                secret: app.conf.sessionSecret
            }));
        }
        else {
            console.info('[libby] sessions in memory');
            app.use(session({secret:'testing-secret'}));
        }
    };

    // Test settings
    if (app.settings.env === 'test'){
        app.use(logger('dev'));

        app.use(errorHandler({
            dumpExceptions: true,
            showStack: true
        }));

        app.use(session({secret:'testing-secret'}));
    };

    // Production settings
    if (app.settings.env === 'production'){
        app.use(logger());

        app.use(errorHandler());

        if (config.redis.host !== undefined && config.redis.port !== undefined){
            console.info('[libby] sessions in redis %s:%s', app.conf.redis.host, app.conf.redis.port);
            var RedisStore = require('connect-redis')(express);
            app.use(session({
                store: new RedisStore({
                    host: app.conf.redis.host,
                    port: app.conf.redis.port
                }),
                secret: app.conf.sessionSecret
            }));
        }
        else {
            console.info('[libby] sessions in memory in production!');
            app.use(session({secret: app.conf.sessionSecret}));
        }
    };

    // Parses x-www-form-urlencoded request bodies (and json)
    app.use(bodyParser());
    app.use(methodOverride());

    app.use(flash());
    app.use(function(req, res, next){
        res.locals.messages = req.flash();
        next();
    });

    app.use(expressValidator({
        errorFormatter: function(param, msg, value) {
            var namespace = param.split('.'),
                root = namespace.shift(),
                formParam = root;

            while(namespace.length) {
                formParam += '[' + namespace.shift() + ']';
            }
            return {
                param: formParam,
                msg: msg,
                value: value
            };
        }
    }));

    // Translation settings
    console.info('[libby] i18n-abide default: %s -- supported: %s', app.conf.default_language, app.conf.languages.join(', '));
    console.info('[libby] i18n-abide translation directory: %s', app.conf.translation_directory);
    app.use(i18n.abide({
        supported_languages: app.conf.languages,
        default_lang: app.conf.default_language,
        translation_directory: app.conf.translation_directory
    }));

    // Middleware setting __ translation shortcut
    app.use(function(req, res, next){
        res.locals.__ = res.locals.gettext;
        next();
    });

    return app;
};
<|endoftext|>


<commit_before>var express = require('express');

var app = express.createServer(express.logger());

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

var port = process.env.PORT || 5000;
app.listen(port, function() {
  console.log("Listening on " + port);
});<commit_msg>test phantom js<commit_after>var express = require('express');

var app = express.createServer(express.logger());
var childProcess = require('child_process')
var phantomjs = require('phantomjs')
var binPath = "vendor/phantomjs/bin/phantomjs"//phantomjs.path //LD_LIBRARY_PATH

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

app.get('/test', function(request, response) {
  	var childArgs = [
	  path.join(__dirname, 'color-crawler.js'),
	  'http://google.com'
	]
  	childProcess.execFile(binPath, childArgs, function(err, stdout, stderr) {
  		response.send('Hello World!' + stdout)
	})
});

var port = process.env.PORT || 5000;
app.listen(port, function() {
  console.log("Listening on " + port);
});<|endoftext|>


<commit_before>/*jshint laxcomma:true */

/**
 * The Strider (web) app.
 */

var   apres = require('apres')
    , backchannel = require('./backchannel')
    , common = require('./common')
    , express = require('express')
    , EventEmitter = require('events').EventEmitter
    , everypaas = require('everypaas')
    , logging = require('./logging')
    , middleware = require('./middleware')
    , mongoose = require('mongoose')
    , mongoStore = require('connect-mongo')(express)
    , routes = require('../routes')
    , websockets = require('./websockets')

    , routes_admin = require('../routes/admin/index.js')
    , routes_jobs = require('../routes/jobs/index.js')
    , api = require('../routes/api')
    , api_account = require('../routes/api/account.js')
    , api_admin = require('../routes/api/admin/index.js')
    , api_collaborators = require('../routes/api/collaborators')
    , api_github = require('../routes/api/github.js')
    , api_heroku = require('../routes/api/heroku.js')
    , api_jobs = require('../routes/api/jobs.js')
    , api_repo = require('../routes/api/repo.js')
    , api_webhooks = require('../routes/api/webhooks')

    , auth = require('./auth')
    , swig = require('swig')
    ;

var MONTH_IN_MILLISECONDS = 2629743000;
var session_store;

var init = exports.init = function (config) {

  var mongodbUrl = config.db_uri;
  console.log("Using MongoDB URL: %s", mongodbUrl);
  mongoose.connect(mongodbUrl, function(e){
    if (e) throw e;
  });
  session_store = new mongoStore({url: mongodbUrl});

  swig.init({
      root: config.viewpath,
      allowErrors: true // allows errors to be thrown and caught by express instead of suppressed by Swig
    , cache: false
    , tags: require('./swigTags')
  });

  var app = express();

  app.configure(function(){
    app.set('views', __dirname + '/../views');

    app.set('view engine', 'jade');
    app.engine('jade', require('jade').__express);
    app.engine('html', require('consolidate').swig);

    app.use(middleware.bodySetter);
    app.use(express.bodyParser());
    app.use(express.cookieParser());
    app.use(express.methodOverride());
    app.use(require('stylus').middleware({ src: __dirname + '/../public' }));

    app.use(express.session({
        secret: config.session_secret, store: session_store,
        cookie: {maxAge: MONTH_IN_MILLISECONDS}
      }));
    auth.setup(app); // app.use(passport) is included

    app.use(express.static(__dirname + '/../public', {maxAge: MONTH_IN_MILLISECONDS}));
    apres.helpExpress(app);
    app.use(app.router);
    app.use(function(req, res, next) {
      var user_created_timestamp=0;
      if (req.user !== undefined) {
        user_created_timestamp = parseInt(req.user.id.substr(0,8),16);
      }
      res.locals.user_created_timestamp = user_created_timestamp;
    });
  });

  app.configure('development', function(){
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
  });

  app.configure('production', function(){
    app.use(express.errorHandler({ dumpExceptions: true, showStack: false}));
  });

  // Routes

  app.get('/', routes.index);
  app.get('/about',function(req, res) {
     res.render('about');
   });

  // Docs page (single page for moment)
  app.get('/docs', function(req, res) {res.render('docs');});
  app.get('/docs/getting_started', function(req, res) {res.render('docs/GettingStarted');});
  app.get('/docs/why_heroku_api_key', function(req, res) {res.render('docs/whyHerokuAPIKey');});

  app.get('/admin/projects', middleware.require_admin, routes_admin.projects);
  app.get('/admin/users', middleware.require_admin, routes_admin.users);
  app.get('/admin/jobs', middleware.require_admin, function(req, res) {
    res.render('admin/jobs')});
  app.get('/admin/make_admin', middleware.require_admin, routes_admin.make_admin);
  app.get('/admin/invites', middleware.require_admin, routes_admin.invites);
  app.get('/admin/:org/:repo/job/:job_id', middleware.require_admin, routes_admin.job);

  app.get('/account', middleware.require_auth_browser, routes.account);
  app.get('/add_repo', middleware.require_auth_browser, function(req, res) { res.render('add_repo.html'); });

  /* Requires at least read-only access to the repository in the path */
  app.get('/:org/:repo/latest_build', middleware.require_auth_browser, middleware.require_resource_read,
    routes_jobs.latest_build);
  app.get('/:org/:repo/', middleware.require_auth_browser, middleware.require_resource_read,
    routes_jobs.latest_build);
  app.get('/:org/:repo/job/:job_id', middleware.require_auth_browser, middleware.require_resource_read,
    routes_jobs.job);

  /* Requires admin access to the repository in the path */
  app.get('/:org/:repo/config',middleware.require_auth_browser, middleware.require_resource_admin,
    routes.config);

  app.post('/webhook', routes.webhook_signature);
  app.post('/webhook/:secret',routes.webhook_secret);

  app.get('/kickoff/:githubId', middleware.require_auth, routes.kickoff);
  app.get('/manual_setup', middleware.require_auth, function(req,res) {res.render('manual_setup');});

  app.post('/api/github/manual_setup',
    middleware.require_auth,
    middleware.require_params(["github_url"]),
    api_github.post_manual_setup);
  app.get('/api/github/metadata', middleware.require_auth, api_github.github_metadata);
  app.post('/api/github/webhooks/unset', middleware.require_auth, api_github.github_webhooks_unset);

  app.get('/api/admin/jobs', middleware.require_admin, api_admin.admin_jobs_status);
  app.get('/api/admin/users', middleware.require_admin, api_admin.get_user_list);
  app.post('/api/admin/invite/new', middleware.require_admin, api.invite_new);

  // this should be app.del and delete should be removed from the end
  // that requires javascript on client side
  app.get('/:org/:repo/delete', middleware.require_resource_admin, routes.delete_project);

  app.get('/api/jobs', middleware.require_auth, api_jobs.jobs);
  app.post('/api/jobs/start', middleware.require_auth, api_jobs.jobs_start);
  app.post('/api/heroku/account_integration', middleware.require_auth, api_heroku.heroku_account_integration);
  app.post('/api/heroku/delivery_integration', middleware.require_auth, api_heroku.heroku_delivery_integration);
  app.post('/api/heroku/config', middleware.require_auth, middleware.require_params(["url"]), api_heroku.heroku_config);

  app.post('/api/account/password', middleware.require_auth, api_account.account_password);
  app.post('/api/account/email', middleware.require_auth, api_account.account_email);

  app.post('/login', auth.authenticate);
  app.get('/logout', auth.logout);

  // collaborators
  app.get('/api/collaborators',
    middleware.require_auth,
    middleware.require_params(["url"]),
    api_collaborators.get_index);
  app.post('/api/collaborators',
    middleware.require_auth,
    middleware.require_params(["url", "email"]),
    api_collaborators.post_index);
  app.delete('/api/collaborators',
    middleware.require_auth,
    middleware.require_params(["url", "email"]),
    api_collaborators.delete_index);

  // webhooks
  app.get('/api/webhooks',
    middleware.require_auth,
    middleware.require_params(["url"]),
    api_webhooks.get_index);
  app.post('/api/webhooks',
    middleware.require_auth,
    middleware.require_params(["url", "target_url", "secret"]),
    api_webhooks.post_index);
  app.delete('/api/webhooks',
    middleware.require_auth,
    middleware.require_params(["url"]),
    api_webhooks.delete_index);

  // repo config
  app.get('/api/repo',
    middleware.require_auth,
    middleware.require_params(["url"]),
    api_repo.get_index);
  app.post('/api/repo',
    middleware.require_auth,
    middleware.require_params(["url", "active"]),
    api_repo.post_index);
  app.delete('/api/repo',
    middleware.require_auth,
    middleware.require_params(["url"]),
    api_repo.delete_index);

  common.app = app;
  common.session_store = session_store;
  //
  // ### Strider Webapp Event Emitter
  //
  // Strider has a Node.Js Event Emitter which emits many events.  This can be
  // used by extensions to add extremely flexible custom handling for just about
  // anything.
  //
  common.emitter = new EventEmitter();

  return app;
};

var run = exports.run = function(app){
  var config = require('./config');

  // Custom 404 handler.
  // Run after extensions, which might load static middlewares.
  app.use(middleware.custom404);

  var server = app.listen(config.server_port);
  // Initialize socket.io
  websockets.init(app, server, session_store);
  backchannel.init();
  console.info("Express server listening on port %d in %s mode", config.server_port, app.settings.env);
}

<commit_msg>fix broken middleware. wasn't calling next(). closes #37.<commit_after>/*jshint laxcomma:true */

/**
 * The Strider (web) app.
 */

var   apres = require('apres')
    , backchannel = require('./backchannel')
    , common = require('./common')
    , express = require('express')
    , EventEmitter = require('events').EventEmitter
    , everypaas = require('everypaas')
    , logging = require('./logging')
    , middleware = require('./middleware')
    , mongoose = require('mongoose')
    , mongoStore = require('connect-mongo')(express)
    , routes = require('../routes')
    , websockets = require('./websockets')

    , routes_admin = require('../routes/admin/index.js')
    , routes_jobs = require('../routes/jobs/index.js')
    , api = require('../routes/api')
    , api_account = require('../routes/api/account.js')
    , api_admin = require('../routes/api/admin/index.js')
    , api_collaborators = require('../routes/api/collaborators')
    , api_github = require('../routes/api/github.js')
    , api_heroku = require('../routes/api/heroku.js')
    , api_jobs = require('../routes/api/jobs.js')
    , api_repo = require('../routes/api/repo.js')
    , api_webhooks = require('../routes/api/webhooks')

    , auth = require('./auth')
    , swig = require('swig')
    ;

var MONTH_IN_MILLISECONDS = 2629743000;
var session_store;

var init = exports.init = function (config) {

  var mongodbUrl = config.db_uri;
  console.log("Using MongoDB URL: %s", mongodbUrl);
  mongoose.connect(mongodbUrl, function(e){
    if (e) throw e;
  });
  session_store = new mongoStore({url: mongodbUrl});

  swig.init({
      root: config.viewpath,
      allowErrors: true // allows errors to be thrown and caught by express instead of suppressed by Swig
    , cache: false
    , tags: require('./swigTags')
  });

  var app = express();

  app.configure(function(){
    app.set('views', __dirname + '/../views');

    app.set('view engine', 'jade');
    app.engine('jade', require('jade').__express);
    app.engine('html', require('consolidate').swig);

    app.use(middleware.bodySetter);
    app.use(express.bodyParser());
    app.use(express.cookieParser());
    app.use(express.methodOverride());
    app.use(require('stylus').middleware({ src: __dirname + '/../public' }));

    app.use(express.session({
        secret: config.session_secret, store: session_store,
        cookie: {maxAge: MONTH_IN_MILLISECONDS}
      }));
    auth.setup(app); // app.use(passport) is included

    app.use(express.static(__dirname + '/../public', {maxAge: MONTH_IN_MILLISECONDS}));
    apres.helpExpress(app);
    app.use(app.router);
    app.use(function(req, res, next) {
      var user_created_timestamp=0;
      if (req.user !== undefined) {
        user_created_timestamp = parseInt(req.user.id.substr(0,8),16);
      }
      res.locals.user_created_timestamp = user_created_timestamp;
      next();
    });
  });

  app.configure('development', function(){
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
  });

  app.configure('production', function(){
    app.use(express.errorHandler({ dumpExceptions: true, showStack: false}));
  });

  // Routes

  app.get('/', routes.index);
  app.get('/about',function(req, res) {
     res.render('about');
   });

  // Docs page (single page for moment)
  app.get('/docs', function(req, res) {res.render('docs');});
  app.get('/docs/getting_started', function(req, res) {res.render('docs/GettingStarted');});
  app.get('/docs/why_heroku_api_key', function(req, res) {res.render('docs/whyHerokuAPIKey');});

  app.get('/admin/projects', middleware.require_admin, routes_admin.projects);
  app.get('/admin/users', middleware.require_admin, routes_admin.users);
  app.get('/admin/jobs', middleware.require_admin, function(req, res) {
    res.render('admin/jobs')});
  app.get('/admin/make_admin', middleware.require_admin, routes_admin.make_admin);
  app.get('/admin/invites', middleware.require_admin, routes_admin.invites);
  app.get('/admin/:org/:repo/job/:job_id', middleware.require_admin, routes_admin.job);

  app.get('/account', middleware.require_auth_browser, routes.account);
  app.get('/add_repo', middleware.require_auth_browser, function(req, res) { res.render('add_repo.html'); });

  /* Requires at least read-only access to the repository in the path */
  app.get('/:org/:repo/latest_build', middleware.require_auth_browser, middleware.require_resource_read,
    routes_jobs.latest_build);
  app.get('/:org/:repo/', middleware.require_auth_browser, middleware.require_resource_read,
    routes_jobs.latest_build);
  app.get('/:org/:repo/job/:job_id', middleware.require_auth_browser, middleware.require_resource_read,
    routes_jobs.job);

  /* Requires admin access to the repository in the path */
  app.get('/:org/:repo/config',middleware.require_auth_browser, middleware.require_resource_admin,
    routes.config);

  app.post('/webhook', routes.webhook_signature);
  app.post('/webhook/:secret',routes.webhook_secret);

  app.get('/kickoff/:githubId', middleware.require_auth, routes.kickoff);
  app.get('/manual_setup', middleware.require_auth, function(req,res) {res.render('manual_setup');});

  app.post('/api/github/manual_setup',
    middleware.require_auth,
    middleware.require_params(["github_url"]),
    api_github.post_manual_setup);
  app.get('/api/github/metadata', middleware.require_auth, api_github.github_metadata);
  app.post('/api/github/webhooks/unset', middleware.require_auth, api_github.github_webhooks_unset);

  app.get('/api/admin/jobs', middleware.require_admin, api_admin.admin_jobs_status);
  app.get('/api/admin/users', middleware.require_admin, api_admin.get_user_list);
  app.post('/api/admin/invite/new', middleware.require_admin, api.invite_new);

  // this should be app.del and delete should be removed from the end
  // that requires javascript on client side
  app.get('/:org/:repo/delete', middleware.require_resource_admin, routes.delete_project);

  app.get('/api/jobs', middleware.require_auth, api_jobs.jobs);
  app.post('/api/jobs/start', middleware.require_auth, api_jobs.jobs_start);
  app.post('/api/heroku/account_integration', middleware.require_auth, api_heroku.heroku_account_integration);
  app.post('/api/heroku/delivery_integration', middleware.require_auth, api_heroku.heroku_delivery_integration);
  app.post('/api/heroku/config', middleware.require_auth, middleware.require_params(["url"]), api_heroku.heroku_config);

  app.post('/api/account/password', middleware.require_auth, api_account.account_password);
  app.post('/api/account/email', middleware.require_auth, api_account.account_email);

  app.post('/login', auth.authenticate);
  app.get('/logout', auth.logout);

  // collaborators
  app.get('/api/collaborators',
    middleware.require_auth,
    middleware.require_params(["url"]),
    api_collaborators.get_index);
  app.post('/api/collaborators',
    middleware.require_auth,
    middleware.require_params(["url", "email"]),
    api_collaborators.post_index);
  app.delete('/api/collaborators',
    middleware.require_auth,
    middleware.require_params(["url", "email"]),
    api_collaborators.delete_index);

  // webhooks
  app.get('/api/webhooks',
    middleware.require_auth,
    middleware.require_params(["url"]),
    api_webhooks.get_index);
  app.post('/api/webhooks',
    middleware.require_auth,
    middleware.require_params(["url", "target_url", "secret"]),
    api_webhooks.post_index);
  app.delete('/api/webhooks',
    middleware.require_auth,
    middleware.require_params(["url"]),
    api_webhooks.delete_index);

  // repo config
  app.get('/api/repo',
    middleware.require_auth,
    middleware.require_params(["url"]),
    api_repo.get_index);
  app.post('/api/repo',
    middleware.require_auth,
    middleware.require_params(["url", "active"]),
    api_repo.post_index);
  app.delete('/api/repo',
    middleware.require_auth,
    middleware.require_params(["url"]),
    api_repo.delete_index);

  common.app = app;
  common.session_store = session_store;
  //
  // ### Strider Webapp Event Emitter
  //
  // Strider has a Node.Js Event Emitter which emits many events.  This can be
  // used by extensions to add extremely flexible custom handling for just about
  // anything.
  //
  common.emitter = new EventEmitter();

  return app;
};

var run = exports.run = function(app){
  var config = require('./config');

  // Custom 404 handler.
  // Run after extensions, which might load static middlewares.
  app.use(middleware.custom404);

  var server = app.listen(config.server_port);
  // Initialize socket.io
  websockets.init(app, server, session_store);
  backchannel.init();
  console.info("Express server listening on port %d in %s mode", config.server_port, app.settings.env);
}

<|endoftext|>


<commit_before>const debug = require('debug')('peermusic:sync:actions')
const events = require('events')
const inherits = require('inherits')

inherits(Peers, events.EventEmitter)
var peers = new Peers()

var actions = {
  'REGISTER_PEER': (peer, peerId) => {
    peers.add(peer, peerId)
    setTimeout(() => peer.send({test: 'hi!'}, 'test'), 300)
  },
  'DEREGISTER_PEER': (peer, peerId) => {
    peers.remove(peerId)
  },
  'GET_INVENTORY': () => {
    return null
  },
  'GET_SONG': (id) => {
    return null
  },
  'GET_COVER': (id) => {
    return null
  },
  'GET_SIMILARITY': (id) => {
    return null
  },
  'START_CONTINUAL_SYNC': () => {

  },
  'ANSWER_REQUEST': (data) => {
    debug('hoho', data)
  }
}

peers.on('data', actions.ANSWER_REQUEST)
peers.on('close', actions.DEREGISTER_PEER)

module.exports = actions

function Peers () {
  this.remotes = {}

  this.add = (peer, peerId) => {
    var self = this
    self.remotes[peerId] = peer
    peer.on('data', (data) => self.emit('data', data))
    peer.on('close', (data) => self.emit('close', peer, peerId))
  }

  this.remove = (peerId) => {
    delete this.peers[peerId]
  }
}
<commit_msg>restructuring<commit_after>const debug = require('debug')('peermusic:sync:actions')
const events = require('events')
const inherits = require('inherits')

module.exports = {
  'REGISTER_PEER': registerPeer,
  'DEREGISTER_PEER': deregisterPeer,
  'PROCESS_INCOMING_DATA': processIncomingData
}

inherits(Peers, events.EventEmitter)
var peers = new Peers()

peers.on('data', processIncomingData)
peers.on('close', deregisterPeer)

function registerPeer (peer, peerId) {
  peers.add(peer, peerId)
  setTimeout(() => peers.broadcast({test: 'hi!'}), 300)
}

function deregisterPeer (peer, peerId) {
  peers.remove(peerId)
}

function processIncomingData (data) {
  debug('hoho', data)
}

function Peers () {
  var self = this
  self.remotes = {}

  self.add = (peer, peerId) => {
    self.remotes[peerId] = peer
    peer.on('data', (data) => self.emit('data', data))
    peer.on('close', (data) => self.emit('close', peer, peerId))
  }

  self.remove = (peerId) => {
    delete this.peers[peerId]
  }

  self.send = (data, peerId) => {
    if (!self.remotes[peerId]) {
      debug('cannot send to unregistered peer', peerId)
      return
    }
    self.remotes[peerId].send(data)
  }

  self.broadcast = (data) => {
    for (let peerId in self.remotes) {
      self.remotes[peerId].send(data)
    }
  }
}
<|endoftext|>


<commit_before>var gzippo = require('gzippo');
var express = require('express');
var morgan = require('morgan');
var app = express();

app.use(morgan('dev'));
app.use(express.static('./bin'));
app.listen(process.env.PORT || 5000);<commit_msg>added bin dir<commit_after>var gzippo = require('gzippo');
var express = require('express');
var morgan = require('morgan');
var app = express();

app.use(morgan('dev'));
app.use(express.static("" + __dirname + "/bin"));
app.listen(process.env.PORT || 5000);<|endoftext|>


<commit_before>// app.js
//
// main function for activity pump application
//
// Copyright 2011-2012, StatusNet Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var auth = require("connect-auth-evanp"),
    databank = require("databank"),
    express = require("express"),
    _ = require("underscore"),
    api = require("../routes/api"),
    web = require("../routes/web"),
    schema = require("./schema").schema,
    HTTPError = require("./httperror").HTTPError,
    Provider = require("./provider").Provider,
    URLMaker = require("./urlmaker").URLMaker,
    Databank = databank.Databank,
    DatabankObject = databank.DatabankObject;

var makeApp = function(config, callback) {

    var params,
        port = config.port || 31337,
        hostname = config.hostname || "localhost",
        db;

    // Initiate the DB

    if (_(config).has("params")) {
        params = config.params;
    } else {
        params = {};
    }

    if (_(params).has("schema")) {
        _.extend(params.schema, schema);
    } else {
        params.schema = schema;
    }

    db = Databank.get(config.driver, params);

    // Connect...

    db.connect({}, function(err) {

        var app = express.createServer();

        if (err) {
            callback(err, null);
            return;
        }

        // Configuration

        app.configure(function() {

            // Templates are in public
            app.set("views", __dirname + "/../public/template");
            app.set("view engine", "utml");
            if (!_(config).has("nologger") || !config.nologger) {
                app.use(express.logger());
            }
            app.use(express.bodyParser());
            app.use(express.cookieParser());
            app.use(express.query());
            app.use(express.methodOverride());
            app.use(express.session({secret: (config.secret || "activitypump")}));
            app.use(express.favicon());

            var provider = new Provider();

            app.use(function(req, res, next) {
                res.local("site", (config.site) ? config.site : "ActivityPump");
                res.local("owner", (config.owner) ? config.owner : "Anonymous");
                res.local("ownerurl", (config.ownerURL) ? config.ownerURL : false);
                // Initialize null
                res.local("remoteUser", null);
                res.local("user", null);
                res.local("client", null);
                res.local("nologin", false);
                next();
            });

            app.use(auth([auth.Oauth({name: "client",
                                      oauth_provider: provider,
                                      oauth_protocol: "http",
                                      authenticate_provider: null,
                                      authorize_provider: null,
                                      authorization_finished_provider: null
                                     }),
                          auth.Oauth({name: "user",
                                      oauth_provider: provider,
                                      oauth_protocol: "http",
                                      authenticate_provider: web.authenticate,
                                      authorize_provider: web.authorize,
                                      authorization_finished_provider: web.authorizationFinished
                                     })
                         ]));

            app.use(app.router);

            app.use(express["static"](__dirname + "/../public"));

        });

        app.error(function(err, req, res, next) {
            if (err instanceof HTTPError) {
                if (req.xhr) {
                    res.json({error: err.message}, err.code);
                } else if (req.accepts("html")) {
                    res.render("error", {status: err.code, error: err, title: "Error"});
                } else {
                    res.writeHead(err.code, {"Content-Type": "text/plain"});
                    res.end(err.message);
                }
            } else {
                next(err);
            }
        });

        // Routes

        api.addRoutes(app);

        // Use "noweb" to disable Web site (API engine only)

        if (!_(config).has("noweb") || !config.noweb) {
            web.addRoutes(app);
        }

        api.setBank(db);
        DatabankObject.bank = db;

        URLMaker.hostname = hostname;
        URLMaker.port = port;

        app.run = function(callback) {
            var self = this,
                removeListeners = function() {
                    self.removeListener("listening", listenSuccessHandler);
                    self.removeListener("err", listenErrorHandler);
                },
                listenErrorHandler = function(err) {
                    removeListeners();
                    callback(err);
                },
                listenSuccessHandler = function() {
                    removeListeners();
                    callback(null);
                };
            this.on("error", listenErrorHandler);
            this.on("listening", listenSuccessHandler);
            this.listen(port);
        };

        callback(null, app);
    });
};

exports.makeApp = makeApp;<commit_msg>Use standard connect-auth<commit_after>// app.js
//
// main function for activity pump application
//
// Copyright 2011-2012, StatusNet Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var auth = require("connect-auth"),
    databank = require("databank"),
    express = require("express"),
    _ = require("underscore"),
    api = require("../routes/api"),
    web = require("../routes/web"),
    schema = require("./schema").schema,
    HTTPError = require("./httperror").HTTPError,
    Provider = require("./provider").Provider,
    URLMaker = require("./urlmaker").URLMaker,
    Databank = databank.Databank,
    DatabankObject = databank.DatabankObject;

var makeApp = function(config, callback) {

    var params,
        port = config.port || 31337,
        hostname = config.hostname || "localhost",
        db;

    // Initiate the DB

    if (_(config).has("params")) {
        params = config.params;
    } else {
        params = {};
    }

    if (_(params).has("schema")) {
        _.extend(params.schema, schema);
    } else {
        params.schema = schema;
    }

    db = Databank.get(config.driver, params);

    // Connect...

    db.connect({}, function(err) {

        var app = express.createServer();

        if (err) {
            callback(err, null);
            return;
        }

        // Configuration

        app.configure(function() {

            // Templates are in public
            app.set("views", __dirname + "/../public/template");
            app.set("view engine", "utml");
            if (!_(config).has("nologger") || !config.nologger) {
                app.use(express.logger());
            }
            app.use(express.bodyParser());
            app.use(express.cookieParser());
            app.use(express.query());
            app.use(express.methodOverride());
            app.use(express.session({secret: (config.secret || "activitypump")}));
            app.use(express.favicon());

            var provider = new Provider();

            app.use(function(req, res, next) {
                res.local("site", (config.site) ? config.site : "ActivityPump");
                res.local("owner", (config.owner) ? config.owner : "Anonymous");
                res.local("ownerurl", (config.ownerURL) ? config.ownerURL : false);
                // Initialize null
                res.local("remoteUser", null);
                res.local("user", null);
                res.local("client", null);
                res.local("nologin", false);
                next();
            });

            app.use(auth([auth.Oauth({name: "client",
                                      oauth_provider: provider,
                                      oauth_protocol: "http",
                                      authenticate_provider: null,
                                      authorize_provider: null,
                                      authorization_finished_provider: null
                                     }),
                          auth.Oauth({name: "user",
                                      oauth_provider: provider,
                                      oauth_protocol: "http",
                                      authenticate_provider: web.authenticate,
                                      authorize_provider: web.authorize,
                                      authorization_finished_provider: web.authorizationFinished
                                     })
                         ]));

            app.use(app.router);

            app.use(express["static"](__dirname + "/../public"));

        });

        app.error(function(err, req, res, next) {
            if (err instanceof HTTPError) {
                if (req.xhr) {
                    res.json({error: err.message}, err.code);
                } else if (req.accepts("html")) {
                    res.render("error", {status: err.code, error: err, title: "Error"});
                } else {
                    res.writeHead(err.code, {"Content-Type": "text/plain"});
                    res.end(err.message);
                }
            } else {
                next(err);
            }
        });

        // Routes

        api.addRoutes(app);

        // Use "noweb" to disable Web site (API engine only)

        if (!_(config).has("noweb") || !config.noweb) {
            web.addRoutes(app);
        }

        api.setBank(db);
        DatabankObject.bank = db;

        URLMaker.hostname = hostname;
        URLMaker.port = port;

        app.run = function(callback) {
            var self = this,
                removeListeners = function() {
                    self.removeListener("listening", listenSuccessHandler);
                    self.removeListener("err", listenErrorHandler);
                },
                listenErrorHandler = function(err) {
                    removeListeners();
                    callback(err);
                },
                listenSuccessHandler = function() {
                    removeListeners();
                    callback(null);
                };
            this.on("error", listenErrorHandler);
            this.on("listening", listenSuccessHandler);
            this.listen(port);
        };

        callback(null, app);
    });
};

exports.makeApp = makeApp;<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchPosts } from '../actions';

class PostsIndex extends Component {
  componentDidMount() {
    this.props.fetchPosts();
  }

  render() {
    return(

        Posts Index

    );
  }
}

export default connect(null, { fetchPosts })(PostsIndex);
<commit_msg>Map over posts and render list of post titles<commit_after>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchPosts } from '../actions';
import _ from 'lodash';

class PostsIndex extends Component {
  componentDidMount() {
    this.props.fetchPosts();
  }

  renderPosts() {
    return _.map(this.props.posts, post => {
      return (

{post.title}

      );
    });
  }

  render() {
    return(

Posts

          {this.renderPosts()}

    );
  }
}

function mapStateToProps(state) {
  return { posts: state.posts };
}

export default connect(mapStateToProps, { fetchPosts })(PostsIndex);
<|endoftext|>


<commit_before>// web.js
var express = require("express");
var logfmt = require("logfmt");
var path = require('path');
var favicon = require('static-favicon');
//var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

// this first section was (part of) how to hook up to local mongodb
/*var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/tutorial3data');

// see this link for extremely brief tutorial on setting up mongodb with heroku/node - this may not use monk
// https://devcenter.heroku.com/articles/getting-started-with-nodejs#using-mongodb
var mongo = require('mongodb');
var mongoUri = process.env.MONGOLAB_URI ||
  process.env.MONGOHQ_URL ||
  'mongodb://localhost/mydb';

mongo.Db.connect(mongoUri, function (err, db) {
  db.collection('mydocs', function(er, collection) {
    collection.insert({'mykey': 'myvalue'}, {safe: true}, function(er,rs) {
    });
  });
});

*/

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

app.use(logfmt.requestLogger());

//app.use('/', routes);
//app.use('/users', users);

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

var port = Number(process.env.PORT || 5000);
app.listen(port, function() {
  console.log("Listening on " + port);
});<commit_msg>commenting out some bad code...<commit_after>// web.js
var express = require("express");
var logfmt = require("logfmt");
var path = require('path');
var favicon = require('static-favicon');
//var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

// this first section was (part of) how to hook up to local mongodb
/*var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/tutorial3data');

// see this link for extremely brief tutorial on setting up mongodb with heroku/node - this may not use monk
// https://devcenter.heroku.com/articles/getting-started-with-nodejs#using-mongodb
var mongo = require('mongodb');
var mongoUri = process.env.MONGOLAB_URI ||
  process.env.MONGOHQ_URL ||
  'mongodb://localhost/mydb';

mongo.Db.connect(mongoUri, function (err, db) {
  db.collection('mydocs', function(er, collection) {
    collection.insert({'mykey': 'myvalue'}, {safe: true}, function(er,rs) {
    });
  });
});

*/

var app = express();

app.use(logfmt.requestLogger());

//app.use('/', routes);
//app.use('/users', users);

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

var port = Number(process.env.PORT || 5000);
app.listen(port, function() {
  console.log("Listening on " + port);
});<|endoftext|>


<commit_before>'use strict';

const Rx = require('rx');
const express = require('express');
const config = require('./config');
const SioFb = require('./sioFb');
const SioBot = require('./sioBot');

module.exports = function() {

  const errorHandler = (e) => {
    console.error(e);
    if (e.stack) {
      console.error(e.stack);
    }
  };

  const textHandler = (message) => {
    console.log('OK: Sent image with text %s.', message.text);
  };

  const observer = Rx.Observer.create(undefined, errorHandler, undefined);

  const getDatePart = (image, markdown) => {
    return (markdown ? '*\[' : '[') +
      new Date(image.created_time).toLocaleDateString() +
      ']' + (markdown ? '*' : '') + ' ';
  };

  const getText = (image) => {
    return getDatePart(image, true) + image.name + '\n' +
      '[Image](' + image.images[0].source + ') | ' +
      '[FB Post](' + image.link + ')';
  };

  const getShortCaption = (image) => {
    let caption = '';
    let createdTime = getDatePart(image);
    let link = '\n(' + image.link + ')';
    // if the link is too big, remove it altogether
    if (link.length > 200) {
      link = '';
    }
    caption = link;
    let text = (createdTime + image.name).trim();
    // if the regular message is too long than the remaining available space
    if (text.length > (200 - link.length)) {
      text = text.substring(0, (197 - link.length)) + '...';
    }
    caption = text + caption;
    return caption;
  };

  const getSendImageFn = (event) => {
    return (image) => {
      return sioBot.sendText(event.chat.id, getText(image));
    };
  };

  let sioBot = new SioBot({
    start: (event) => {
      return sioBot.sendText(event.chat.id, 'OK AHAHAHAHLOL')
        .subscribe(observer);
    },
    stop: (event) => {
      return sioBot.sendText(event.chat.id, 'LOL NO.')
        .subscribe(observer);
    },
    oggy: (event) => {
      return sioFb.getLastStrip()
        .selectMany(getSendImageFn(event))
        .subscribe(textHandler, errorHandler);
    },
    canemagic: (event) => {
      // stupid Facebook can only offset up to 500 elements
      return sioFb.getStripsWithConfig({
          limit: 1,
          offset: Math.floor(Math.random() * 499)
        })
        .selectMany(getSendImageFn(event))
        .subscribe(textHandler, errorHandler);
    },
    banana: (event) => {
      return sioBot.sendText(event.chat.id, 'CHI HA DETTO BANANA?')
        .subscribe(observer);
    }
  });

  let sioFb = new SioFb();
  sioFb.pollForNewStrips()
    .selectMany(image => {
      return sioBot.sendTextAll(getText(image));
    })
    .subscribe(observer);

  let app = express();
  app.get('/', (req, res) => {
    res.send('Banana!');
  });
  app.listen(config.port, () => {
    console.log('Telegram Sio Bot is live on port %s!', config.port);
  });

};<commit_msg>feat(app): show version info on GET index, moar improvements<commit_after>'use strict';

const Rx = require('rx');
const express = require('express');
const config = require('./config');
const SioFb = require('./sioFb');
const SioBot = require('./sioBot');
const pkg = require('./../package.json');

module.exports = function() {

  const errorHandler = (e) => {
    console.error(e);
    if (e.stack) {
      console.error(e.stack);
    }
  };

  const textHandler = (message) => {
    console.log('OK: Sent image with text %s.', message.text);
  };

  const observer = Rx.Observer.create(undefined, errorHandler, undefined);

  const getDatePart = (image, markdown) => {
    return (markdown ? '*\[' : '[') +
      new Date(image.created_time).toLocaleDateString() +
      ']' + (markdown ? '*' : '') + ' ';
  };

  const getText = (image) => {
    return getDatePart(image, true) + image.name + '\n' +
      '[Image](' + image.images[0].source + ') | ' +
      '[FB Post](' + image.link + ')';
  };

  const getShortCaption = (image) => {
    let caption = '';
    let createdTime = getDatePart(image);
    let link = '\n(' + image.link + ')';
    // if the link is too big, remove it altogether
    if (link.length > 200) {
      link = '';
    }
    caption = link;
    let text = (createdTime + image.name).trim();
    // if the regular message is too long than the remaining available space
    if (text.length > (200 - link.length)) {
      text = text.substring(0, (197 - link.length)) + '...';
    }
    caption = text + caption;
    return caption;
  };

  const getSendImageFn = (event) => {
    return (image) => {
      return sioBot.sendText(event.chat.id, getText(image));
    };
  };

  let app = express();
  app.get('/', (req, res) => {
    res.send(pkg.name + ' v' + pkg.version);
  });
  app.listen(config.port || 3000, () => {
    console.log('Telegram Sio Bot is live on port %s!', config.port || 3000);
  });

  let sioBot = new SioBot({
    start: (event) => {
      return sioBot.sendText(event.chat.id, 'OK AHAHAHAHLOL')
        .subscribe(observer);
    },
    stop: (event) => {
      return sioBot.sendText(event.chat.id, 'LOL NO.')
        .subscribe(observer);
    },
    oggy: (event) => {
      return sioFb.getLastStrip()
        .selectMany(getSendImageFn(event))
        .subscribe(textHandler, errorHandler);
    },
    canemagic: (event) => {
      // stupid Facebook can only offset up to 500 elements
      return sioFb.getStripsWithConfig({
          limit: 1,
          offset: Math.floor(Math.random() * 499)
        })
        .selectMany(getSendImageFn(event))
        .subscribe(textHandler, errorHandler);
    },
    banana: (event) => {
      return sioBot.sendText(event.chat.id, 'CHI HA DETTO BANANA?')
        .subscribe(observer);
    }
  });

  let sioFb = new SioFb();
  sioFb.pollForNewStrips()
    .selectMany(image => {
      return sioBot.sendTextAll(getText(image));
    })
    .subscribe(observer);

};<|endoftext|>


<commit_before>import React, {Component} from 'react';

//76

// export default () => {
//   return
List of Blog posts.

// }

//80 fetching data
class PostIndex extends Component {
  componentWillMount() {
    console.log('this would be a good time to call acntion')
    // this.props.fetchPosts();

  }
  render() {
    return (

 List of blog posts

    );
  }
 }

export default PostIndex
<commit_msg>81 合并 component to container 然后输出。<commit_after>import React, {Component} from 'react';

//81
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import {fetchPosts} from '../actions/index';

//76
// export default () => {
//   return
List of Blog posts.

// }

//80 fetching data
class PostIndex extends Component {
  componentWillMount() {
    // console.log('this would be a good time to call acntion')
    //81
    this.props.fetchPosts();

  }
  render() {
    return (

 List of blog posts

    );
  }
 }

// export default PostIndex

// bind container with components
 function mapDispatchToProps(dispatch) {
   return bindActionCreators({fetchPosts}, dispatch);
 }

// export default connect(null,mapDispatchToProps)(PostIndex);
//上面的简便写法
// export default connect(null,{fetchPosts:fetchPosts})(PostIndex);
export default connect(null,{fetchPosts})(PostIndex);
<|endoftext|>