<commit_before>var concat = require('gulp-concat'),
    eslint = require('gulp-eslint'),
    express = require('express'),
    extend = require('jquery-extend'),
    frontMatter = require('gulp-front-matter'),
    fs = require('fs'),
    gulp = require('gulp'),
    gulpif = require('gulp-if'),
    gzip = require('gulp-gzip'),
    hb = require('handlebars'),
    highlight = require('highlight.js'),
    layouts = require('handlebars-layouts'),
    less = require('gulp-less'),
    marked = require('gulp-marked'),
    minifyCSS = require('gulp-minify-css'),
    minifyHTML = require('gulp-minify-html'),
    minifyJS = require('gulp-uglify'),
    mocha = require('gulp-mocha'),
    moment = require('moment'),
    rename = require('gulp-rename'),
    tap = require('gulp-tap');

// Config HB
layouts.register(hb);

var data = {
    authors : {}, // Populated from Markdown by 'authors' task
    posts : {}, // Populated by the 'posts' task
    tags : {}, // Populated by the 'posts' task
    pageTitle : 'Airware Makers',
    year : moment().format('YYYY'),
    timestamp : moment().format('YYYY-MM-DD-HH-mm-ss')
};

// Run tests and product coverage
gulp.task('test', ['build'], function () {
    return gulp.src('test/*.js')
        .pipe(mocha());
});

// Lint as JS files (including this one)
gulp.task('lint', ['test'], function () {
    return gulp.src([
        'src/js/*.js',
        'gulpfile.js',
        'test/*.js',
        '!node_modules/**'
    ])
    .pipe(eslint())
    .pipe(eslint.format());
});

// Minify and combine all CSS
gulp.task('styles', function() {
    return gulp.src([
        'node_modules/bootstrap/dist/css/bootstrap.css',
        'node_modules/highlight.js/styles/default.css',
        'src/less/*.less'
    ])
    .pipe(gulpif(/[.]less$/, less()))
    .pipe(concat('all.min.css'))
    .pipe(minifyCSS())
    .pipe(gzip({ append: false }))
    .pipe(gulp.dest('build'));
});

// Minify and combine all JavaScript
gulp.task('scripts', function() {
    return gulp.src([
        'node_modules/jquery/dist/jquery.js',
        'node_modules/bootstrap/dist/js/bootstrap.js',
        'src/js/*.js'
    ])
    .pipe(concat('all.min.js'))
    .pipe(minifyJS({ preserveComments: 'some' }))
    .pipe(gzip({ append: false }))
    .pipe(gulp.dest('build'));
});

// Copy static files to build dir
gulp.task('static', function() {
    return gulp.src('src/static/**')
        .pipe(gzip({ append: false }))
        .pipe(gulp.dest('build'));
});

// Register HB partials
gulp.task('partials', function() {
    return gulp.src('src/partials/*.html')
    .pipe(rename({ extname: '' }))
    .pipe(tap(function(file) {
        hb.registerPartial(file.relative, file.contents.toString());
    }));
});

// Load authors
gulp.task('authors', function() {
    data.authors = {};

    return gulp.src('src/authors/*.md')
        .pipe(frontMatter({ property: 'data' }))
        .pipe(marked())
        .pipe(rename({ extname : '' }))
        .pipe(tap(function(file) {
            data.authors[file.relative] = extend(file.data, {
                bio : file.contents.toString()
            });
        }));
});

// Generate posts
gulp.task('posts', ['partials', 'authors'], function() {
    var template = hb.compile(fs.readFileSync('src/partials/post.html', 'utf-8'));
    var category;
    data.posts = {};

    return gulp.src('src/posts/*.md')
        .pipe(frontMatter({ property: 'data' }))
        .pipe(marked({
            highlight: function(code) {
                return highlight.highlightAuto(code).value;
            }
        }))
        .pipe(tap(function(file) {
            category = file.data.category;
            var post = {
                slug : file.relative.replace('.html', ''),
                title : file.data.title + ' | ' + data.pageTitle,
                h1 : file.data.title,
                author : data.authors[file.data.author],
                post : file.contents.toString(),
                year : data.year,
                timestamp : data.timestamp
            };
            data.posts[post.slug] = post;
            file.contents = new Buffer(template(post), 'utf-8');
        }))
        .pipe(rename(function(path) {
            path.dirname = [ path.dirname, category, path.basename ].join('/');
            path.basename = 'index';
            path.extname = '.html';
        }))
        .pipe(minifyHTML())
        .pipe(gzip({ append: false }))
        .pipe(gulp.dest('build'));
});

// Generate posts
gulp.task('pages', ['partials', 'authors'], function() {
    return gulp.src('src/pages/**/*.html')
        .pipe(tap(function(file) {
            var template = hb.compile(file.contents.toString());
            file.contents = new Buffer(template(data));
        }))
        .pipe(gulpif(/^((?!index).)*$/, rename(function(path) {
            path.dirname = [ path.dirname, path.basename ].join('/');
            path.basename = 'index';
            path.extname = '.html';
        })))
        .pipe(minifyHTML())
        .pipe(gzip({ append: false }))
        .pipe(gulp.dest('build'));
});

// Serve files for local development
gulp.task('serve', function(callback) {
    express()
        .use(function(req, res, next) {
            res.header('Content-Encoding', 'gzip');
            next();
        })
        .use(express.static('build'))
        .use(function(req, res) {
            res.status(404)
                .sendFile(__dirname + '/build/error.html');
        })
        .listen(3000, callback);
});

// Build macro
gulp.task('build', [
    'static',
    'styles',
    'scripts',
    'partials',
    'authors',
    'pages',
    'posts'
]);

// Watch certain files
gulp.task('watch', ['serve', 'lint'], function() {
    gulp.watch([
        'src/**/*',
        'test/**',
        'gulpfile.js'
    ], ['lint']);
});

// What to do when you run `$ gulp`
gulp.task('default', ['watch']);<commit_msg>Unwatching gulpfile.js as it doesn't reload anyway<commit_after>var concat = require('gulp-concat'),
    eslint = require('gulp-eslint'),
    express = require('express'),
    extend = require('jquery-extend'),
    frontMatter = require('gulp-front-matter'),
    fs = require('fs'),
    gulp = require('gulp'),
    gulpif = require('gulp-if'),
    gzip = require('gulp-gzip'),
    hb = require('handlebars'),
    highlight = require('highlight.js'),
    layouts = require('handlebars-layouts'),
    less = require('gulp-less'),
    marked = require('gulp-marked'),
    minifyCSS = require('gulp-minify-css'),
    minifyHTML = require('gulp-minify-html'),
    minifyJS = require('gulp-uglify'),
    mocha = require('gulp-mocha'),
    moment = require('moment'),
    rename = require('gulp-rename'),
    tap = require('gulp-tap');

// Config HB
layouts.register(hb);
var data = {
    authors : {}, // Populated from Markdown by 'authors' task
    posts : {}, // Populated by the 'posts' task
    tags : {}, // Populated by the 'posts' task
    pageTitle : 'Airware Makers',
    year : moment().format('YYYY'),
    timestamp : moment().format('YYYY-MM-DD-HH-mm-ss')
};

// Run tests and product coverage
gulp.task('test', ['build'], function () {
    return gulp.src('test/*.js')
        .pipe(mocha());
});

// Lint as JS files (including this one)
gulp.task('lint', ['test'], function () {
    return gulp.src([
        'src/js/*.js',
        'gulpfile.js',
        'test/*.js',
        '!node_modules/**'
    ])
    .pipe(eslint())
    .pipe(eslint.format());
});

// Minify and combine all CSS
gulp.task('styles', function() {
    return gulp.src([
        'node_modules/bootstrap/dist/css/bootstrap.css',
        'node_modules/highlight.js/styles/default.css',
        'src/less/*.less'
    ])
    .pipe(gulpif(/[.]less$/, less()))
    .pipe(concat('all.min.css'))
    .pipe(minifyCSS())
    .pipe(gzip({ append: false }))
    .pipe(gulp.dest('build'));
});

// Minify and combine all JavaScript
gulp.task('scripts', function() {
    return gulp.src([
        'node_modules/jquery/dist/jquery.js',
        'node_modules/bootstrap/dist/js/bootstrap.js',
        'src/js/*.js'
    ])
    .pipe(concat('all.min.js'))
    .pipe(minifyJS({ preserveComments: 'some' }))
    .pipe(gzip({ append: false }))
    .pipe(gulp.dest('build'));
});

// Copy static files to build dir
gulp.task('static', function() {
    return gulp.src('src/static/**')
        .pipe(gzip({ append: false }))
        .pipe(gulp.dest('build'));
});

// Register HB partials
gulp.task('partials', function() {
    return gulp.src('src/partials/*.html')
    .pipe(rename({ extname: '' }))
    .pipe(tap(function(file) {
        hb.registerPartial(file.relative, file.contents.toString());
    }));
});

// Load authors
gulp.task('authors', function() {
    data.authors = {};

    return gulp.src('src/authors/*.md')
        .pipe(frontMatter({ property: 'data' }))
        .pipe(marked())
        .pipe(rename({ extname : '' }))
        .pipe(tap(function(file) {
            data.authors[file.relative] = extend(file.data, {
                bio : file.contents.toString()
            });
        }));
});

// Generate posts
gulp.task('posts', ['partials', 'authors'], function() {
    var template = hb.compile(fs.readFileSync('src/partials/post.html', 'utf-8'));
    var category;
    data.posts = {};

    return gulp.src('src/posts/*.md')
        .pipe(frontMatter({ property: 'data' }))
        .pipe(marked({
            highlight: function(code) {
                return highlight.highlightAuto(code).value;
            }
        }))
        .pipe(tap(function(file) {
            category = file.data.category;
            var post = {
                slug : file.relative.replace('.html', ''),
                title : file.data.title + ' | ' + data.pageTitle,
                h1 : file.data.title,
                author : data.authors[file.data.author],
                post : file.contents.toString(),
                year : data.year,
                timestamp : data.timestamp
            };
            data.posts[post.slug] = post;
            file.contents = new Buffer(template(post), 'utf-8');
        }))
        .pipe(rename(function(path) {
            path.dirname = [ path.dirname, category, path.basename ].join('/');
            path.basename = 'index';
            path.extname = '.html';
        }))
        .pipe(minifyHTML())
        .pipe(gzip({ append: false }))
        .pipe(gulp.dest('build'));
});

// Generate posts
gulp.task('pages', ['partials', 'authors'], function() {
    return gulp.src('src/pages/**/*.html')
        .pipe(tap(function(file) {
            var template = hb.compile(file.contents.toString());
            file.contents = new Buffer(template(data));
        }))
        .pipe(gulpif(/^((?!index).)*$/, rename(function(path) {
            path.dirname = [ path.dirname, path.basename ].join('/');
            path.basename = 'index';
            path.extname = '.html';
        })))
        .pipe(minifyHTML())
        .pipe(gzip({ append: false }))
        .pipe(gulp.dest('build'));
});

// Serve files for local development
gulp.task('serve', function(callback) {
    express()
        .use(function(req, res, next) {
            res.header('Content-Encoding', 'gzip');
            next();
        })
        .use(express.static('build'))
        .use(function(req, res) {
            res.status(404)
                .sendFile(__dirname + '/build/error.html');
        })
        .listen(3000, callback);
});

// Build macro
gulp.task('build', [
    'static',
    'styles',
    'scripts',
    'partials',
    'authors',
    'pages',
    'posts'
]);

// Watch certain files
gulp.task('watch', ['serve', 'lint'], function() {
    gulp.watch([
        'src/**/*',
        'test/**'
    ], ['lint']);
});

// What to do when you run `$ gulp`
gulp.task('default', ['watch']);<|endoftext|>


<commit_before>var ResourceService = require("services/ResourceService");

Vue.component("payment-provider-select", {

    props: [
        "template"
    ],

    data: function()
    {
        return {
            checkout: {},
            checkoutValidation: {paymentProvider: {}}
        };
    },

    /**
     * Initialise the event listener
     */
    created: function()
    {
        this.$options.template = this.template;

        ResourceService.bind("checkout", this);
        ResourceService.bind("checkoutValidation", this);

        this.checkoutValidation.paymentProvider.validate = this.validate;

        this.initDefaultPaymentProvider();
    },

    methods: {
        /**
         * Event when changing the payment provider
         */
        onPaymentProviderChange: function()
        {
            ResourceService.getResource("checkout")
                .set(this.checkout)
                .done(function()
                {
                    document.dispatchEvent(new CustomEvent("afterPaymentProviderChanged", {detail: this.checkout.methodOfPaymentId}));
                }.bind(this));

            this.validate();
        },

        validate: function()
        {
            this.checkoutValidation.paymentProvider.showError = !(this.checkout.methodOfPaymentId > 0);
        },

        initDefaultPaymentProvider: function()
        {
            // todo get entry from config | select first payment provider
            if (this.checkout.methodOfPaymentId == 0 && this.checkout.paymentDataList.length > 0)
            {
                this.checkout.methodOfPaymentId = this.checkout.paymentDataList[0].id;

                ResourceService.getResource("checkout").set(this.checkout);
            }
        }
    }
});
<commit_msg>Update PaymentProviderSelect.js<commit_after>var ResourceService = require("services/ResourceService");

Vue.component("payment-provider-select", {

    props: [
        "template"
    ],

    data: function()
    {
        return {
            checkout: {},
            checkoutValidation: {paymentProvider: {}}
        };
    },

    /**
     * Initialise the event listener
     */
    created: function()
    {
        this.$options.template = this.template;

        ResourceService.bind("checkout", this);
        ResourceService.bind("checkoutValidation", this);

        this.checkoutValidation.paymentProvider.validate = this.validate;

        this.initDefaultPaymentProvider();
    },

    methods: {
        /**
         * Event when changing the payment provider
         */
        onPaymentProviderChange: function()
        {
            ResourceService.getResource("checkout")
                .set(this.checkout)
                .done(function()
                {
                    document.dispatchEvent(new CustomEvent("afterPaymentMethodChanged", {detail: this.checkout.methodOfPaymentId}));
                }.bind(this));

            this.validate();
        },

        validate: function()
        {
            this.checkoutValidation.paymentProvider.showError = !(this.checkout.methodOfPaymentId > 0);
        },

        initDefaultPaymentProvider: function()
        {
            // todo get entry from config | select first payment provider
            if (this.checkout.methodOfPaymentId == 0 && this.checkout.paymentDataList.length > 0)
            {
                this.checkout.methodOfPaymentId = this.checkout.paymentDataList[0].id;

                ResourceService.getResource("checkout").set(this.checkout);
            }
        }
    }
});
<|endoftext|>


<commit_before><commit_msg>Add express webserver<commit_after>var express = require('express');
var bodyParser = require('body-parser');
var app = express();

var comments = [{author: 'Author1', text: 'Comment1'}];

app.use('/', express.static(__dirname));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.get('/data/comments.json', function(req, res) {
  res.setHeader('Content-Type', 'application/json');
  res.send(JSON.stringify(comments));
});

app.post('/data/comments.json', function(req, res) {
  comments.push(req.body);
  res.setHeader('Content-Type', 'application/json');
  res.send(JSON.stringify(comments));
});

app.listen(3000);

console.log('Server started: http://localhost:3000/');<|endoftext|>


<commit_before>/*jshint node:true*/
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var merge = require('merge-stream');
var dest = 'extension';
var base = {base: 'src/'};

gulp.task('copy', () => gulp.src([
    'src/manifest.json',
    'src/icon_128.jpg',
    'src/*.css'], base)
    .pipe(gulp.dest(dest)));

gulp.task('html', () => gulp.src('src/*.html', base)
    .pipe($.htmlReplace({js: 'lib.js'}))
    .pipe(gulp.dest(dest)));

gulp.task('js', () => gulp.src('src/*.js', base)
    .pipe($.ngAnnotate())
    .pipe($.uglify())
    .pipe(gulp.dest(dest)));

var d = require('gulp-debug');

gulp.task('lib', () => merge(
    gulp.src('src/templates/*.html', base)
    .pipe(d({title:'should have zero'}))
    .pipe($.angularTemplatecache()),
    gulp.src('src/common/*.js')
    .pipe(d({title:'should have common'}))
    .pipe($.ngAnnotate())
    .pipe($.uglify()),
    gulp.src(['src/bower/angular/angular.min.js',
                   'src/bower/lodash/lodash.min.js']))
    .pipe(d({title:'should have bower deps'}))
    .pipe($.concat('lib.js'))
    .pipe(d({title:'should have lib.js'}))
    .pipe(gulp.dest(dest)));

gulp.task('default', ['copy', 'html', 'js', 'lib']);

gulp.task('clean', () => require('del')(dest));
<commit_msg>isolated the problem down to running uglify<commit_after>/*jshint node:true*/
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var merge = require('merge-stream');
var dest = 'extension';
var base = {base: 'src/'};

gulp.task('copy', () => gulp.src([
    'src/manifest.json',
    'src/icon_128.jpg',
    'src/*.css'], base)
    .pipe(gulp.dest(dest)));

gulp.task('html', () => gulp.src('src/*.html', base)
    .pipe($.htmlReplace({js: 'lib.js'}))
    .pipe(gulp.dest(dest)));

gulp.task('js', () => gulp.src('src/*.js', base)
    .pipe($.ngAnnotate())
    .pipe($.uglify())
    .pipe(gulp.dest(dest)));

var d = require('gulp-debug');

gulp.task('lib', () => merge(
    gulp.src(['src/bower/angular/angular.min.js',
                   'src/bower/lodash/lodash.min.js']),
    gulp.src('src/templates/*.html', base)
    .pipe(d({title:'should have zero'}))
    .pipe($.angularTemplatecache()),
    gulp.src('src/common/*.js')
    .pipe(d({title:'should have common'}))
    .pipe($.ngAnnotate())
    // .pipe($.uglify()),
)
    .pipe($.concat('lib.js'))
    .pipe(d({title:'should have lib.js'}))
    .pipe(gulp.dest(dest)));

gulp.task('default', ['copy', 'html', 'js', 'lib']);

gulp.task('clean', () => require('del')(dest));
<|endoftext|>


<commit_before>var gulp = require('gulp');
var pug = require('gulp-pug');
var uglifyjs = require('gulp-uglify');
var webpack = require('webpack-stream');
var rename = require('gulp-rename');
var argv = require('yargs').argv;
var newer = require('gulp-newer');
var named = require('vinyl-named-with-path');
var through = require('through');
var path = require('path');
var plumber = require('gulp-plumber');

/*
parameter
*/
// production mode will do minify and so on
var isProduction = (argv.p === undefined) ? false : true;
if( isProduction )
	console.log('production mode detected');

/*
task
*/
// javascript bundling task
// let webpack do his 'watch' job
gulp.task('bundling', function() {
    var src = 'view/src/**/bundle.js';
    var dest = 'view';

    var stream = gulp.src(src)
            .pipe(plumber())
            .pipe(named())
            .pipe(webpack({
                watch: true,
                context: __dirname + '/view', // file loader가 view를 [path]로 인식해버려서..
                module: {
                    loaders: [
                        {test: /\.(scss|sass|css)$/, loader: 'style!css!sass'},
                        {test: /\.vue$/, loader: 'vue'},
                        {test: /\.(png|eot|woff2|woff|ttf|svg)/, loader: 'file?name=[path][name].[ext]&publicPath=/'}
                    ]
                }
            }))
            .pipe(rename(function(file) {
                file.basename = 'bundle';
            }));
    if( isProduction )
        stream.pipe(uglifyjs({mangle: {toplevel: true}}));
    return stream.pipe(gulp.dest(dest));
});

// convert pug to html
gulp.task('pug', function() {
    var src = 'view/src/**/*.pug';
    var dest = 'view';

	return gulp.src(src)
            .pipe(plumber())
            .pipe(named())
			.pipe(pug({locals: {LANTERN_TITLE: 'LANTERN'}}))
			.pipe(gulp.dest(dest));
});

gulp.task('watch', function() {
	gulp.watch('view/src/**/*.pug', ['pug']);
});

gulp.task('default', ['watch', 'bundling', 'pug']);<commit_msg>*del no more pug task on watch<commit_after>var gulp = require('gulp');
var pug = require('gulp-pug');
var uglifyjs = require('gulp-uglify');
var webpack = require('webpack-stream');
var rename = require('gulp-rename');
var argv = require('yargs').argv;
var newer = require('gulp-newer');
var named = require('vinyl-named-with-path');
var through = require('through');
var path = require('path');
var plumber = require('gulp-plumber');

/*
parameter
*/
// production mode will do minify and so on
var isProduction = (argv.p === undefined) ? false : true;
if( isProduction )
	console.log('production mode detected');

/*
task
*/
// javascript bundling task
// let webpack do his 'watch' job
gulp.task('bundling', function() {
    var src = 'view/src/**/bundle.js';
    var dest = 'view';

    var stream = gulp.src(src)
            .pipe(plumber())
            .pipe(named())
            .pipe(webpack({
                watch: true,
                context: __dirname + '/view', // file loader가 view를 [path]로 인식해버려서..
                module: {
                    loaders: [
                        {test: /\.(scss|sass|css)$/, loader: 'style!css!sass'},
                        {test: /\.vue$/, loader: 'vue'},
                        {test: /\.(png|eot|woff2|woff|ttf|svg)/, loader: 'file?name=[path][name].[ext]&publicPath=/'}
                    ]
                }
            }))
            .pipe(rename(function(file) {
                file.basename = 'bundle';
            }));
    if( isProduction )
        stream.pipe(uglifyjs({mangle: {toplevel: true}}));
    return stream.pipe(gulp.dest(dest));
});

// convert pug to html
gulp.task('pug', function() {
    var src = 'view/src/**/*.pug';
    var dest = 'view';

	return gulp.src(src)
            .pipe(plumber())
            .pipe(named())
			.pipe(pug({locals: {LANTERN_TITLE: 'LANTERN'}}))
			.pipe(gulp.dest(dest));
});

gulp.task('watch', function() {
	gulp.watch('view/src/**/*.pug', ['pug']);
});

gulp.task('default', ['watch', 'bundling']);<|endoftext|>


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

var _ = require('underscore');
var fs = require('fs');
var http = require('http');
var connect = require('connect');
var program = require('commander');
var compression = require('compression');
var serveStatic = require('serve-static');

program
	.version(require('./package').version)
	.usage('[options]')
	.option('-p, --port <value>', 'The port on which the assets server will respond', function(value) {
		return parseInt(value, 10);
	}, 3000)
	.option('-H, --hostname <name>', 'The hostname the assets server will use', '0.0.0.0')
	.option('-b, --base <path>', 'The base (or root) directory from which files will be served', '.')
	.option('-m, --middleware <path>', 'This option expects a path to CommonJS module which will return function that returns an array of middlewares')

program.parse(process.argv);

var config = program.opts();
var middleware = config.middleware && fs.existsSync(config.middleware) && require(config.middleware);

var app = connect();
var server = null;

// Конфигурируем сервер.
app.use(compression());

if (middleware) {
	app.use.apply(app, middleware({
		static: serveStatic
	}, config));
}

// Запускаем сервер.
server = http.createServer(app).listen(config.port);

server.on('listening', function() {
	var info = server.address();

	console.log('Started assets server on http://' + info.address + ':' + info.port);
});

server.on('error', function(err) {
	if (err.code === 'EADDRINUSE') {
		console.error('Port ' + config.port + ' is already in use by another process.');
	} else {
		console.error(err);
	}
});
<commit_msg>Fixed issues with middleware mechanism<commit_after>#!/usr/bin/env node

var _ = require('underscore');
var fs = require('fs');
var http = require('http');
var path = require('path');
var connect = require('connect');
var program = require('commander');
var compression = require('compression');
var serveStatic = require('serve-static');

program
	.version(require('./package').version)
	.usage('[options]')
	.option('-p, --port <value>', 'The port on which the assets server will respond', function(value) {
		return parseInt(value, 10);
	}, 3000)
	.option('-H, --hostname <name>', 'The hostname the assets server will use', '0.0.0.0')
	.option('-b, --base <path>', 'The base (or root) directory from which files will be served', '.')
	.option('-m, --middleware <path>', 'This option expects a path to CommonJS module which will return function that returns an array of middlewares')

program.parse(process.argv);

var config = program.opts();
var pathToModule = path.resolve(config.middleware);
var middleware = config.middleware && fs.existsSync(pathToModule) && require(pathToModule);

var app = connect();
var server = null;

// Конфигурируем сервер.
app.use(compression());

if (middleware) {
	app.use.apply(app, middleware({
		static: serveStatic
	}, config));
}

// Запускаем сервер.
server = http.createServer(app).listen(config.port);

server.on('listening', function() {
	var info = server.address();

	console.log('Started assets server on http://' + info.address + ':' + info.port);
});

server.on('error', function(err) {
	if (err.code === 'EADDRINUSE') {
		console.error('Port ' + config.port + ' is already in use by another process.');
	} else {
		console.error(err);
	}
});
<|endoftext|>


<commit_before>var express = require('express')
  , path    = require('path')
  , crypto  = require('crypto')
  , http    = require('http')
  , winston = require('winston')
  , fs      = require('fs');

var app = express();

app.configure(function() {
  app.set('ipaddress', process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1');
  app.set('port', process.env.OPENSHIFT_NODEJS_PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser('45710b553b5b7293753d03bd3601f70a'));
  app.use(express.session());
  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function() {
  app.use(express.errorHandler());
});

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

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

app.get('/play/:token/:time/:increment', function(req, res) {
  res.render('play', {
    'token': req.params.token,
    'time': req.params.time,
    'increment': req.params.increment
  });
});

app.get('/logs', function(req, res) {
  fs.readFile(__dirname + '/logs/games.log', function (err, data) {
    if (err) {
      res.redirect('/');
    }
    res.set('Content-Type', 'text/plain');
    res.send(data);
  });
});

var server = http.createServer(app).listen(app.get('port'), app.get('ipaddress'), function() {
  console.log("Express server listening on port " + app.get('port'));
});

var games = {};
var timer;

/**
 * Winston logger
 */
winston.add(winston.transports.File, {
  filename: __dirname + '/logs/games.log',
  handleExceptions: true,
  exitOnError: false,
  json: false
});
winston.remove(winston.transports.Console);
winston.handleExceptions(new winston.transports.Console());
winston.exitOnError = false;

/**
 * Sockets
 */
var io = require('socket.io').listen(server, {log: false});

if (process.env.OPENSHIFT_NODEJS_IP) {
  io.configure(function(){
    io.set('transports', ['websocket']);
  });
}

io.sockets.on('connection', function (socket) {

  socket.on('start', function (data) {
    var token;
    var b = new Buffer(Math.random() + new Date().getTime() + socket.id);
    token = b.toString('base64').slice(12, 32);

    //token is valid for 5 minutes
    var timeout = setTimeout(function () {
      if (games[token].players.length === 0) {
        delete games[token];
        socket.emit('token-expired');
      }
    }, 5 * 60 * 1000);

    games[token] = {
      'creator': socket,
      'players': [],
      'interval': null,
      'timeout': timeout
    };

    socket.emit('created', {
      'token': token
    });
  });

  socket.on('join', function (data) {
    var game, color, time = data.time;

    if (!(data.token in games)) {
      socket.emit('token-invalid');
      return;
    }

    clearTimeout(games[data.token].timeout);
    game = games[data.token];

    if (game.players.length >= 2) {
      socket.emit('full');
      return;
    } else if (game.players.length === 1) {
      if (game.players[0].color === 'black') {
        color = 'white';
      } else {
        color = 'black';
      }
      winston.log('info', 'Number of currently running games', { '#': Object.keys(games).length });
    } else {
      var colors = ['black', 'white'];

      color = colors[Math.floor(Math.random() * 2)];
    }

    //join room
    socket.join(data.token);

    games[data.token].players.push({
      'id': socket.id,
      'socket': socket,
      'color': color,
      'time': data.time - data.increment + 1,
      'increment': data.increment
    });

    game.creator.emit('ready', {});

    socket.emit('joined', {
      'color': color
    });
  });

  socket.on('timer-white', function (data) {
    runTimer('white', data.token, socket);
  });

  socket.on('timer-black', function (data) {
    runTimer('black', data.token, socket);
  });

  socket.on('timer-clear-interval', function (data) {
    if (data.token in games) {
      clearInterval(games[data.token].interval);
    }
  });

  socket.on('new-move', function (data) {
    var opponent;

    if (data.token in games) {
      opponent = getOpponent(data.token, socket);
      if (opponent) {
        opponent.socket.emit('move', {
          'move': data.move
        });
      }
    }
  });

  socket.on('resign', function (data) {
    if (data.token in games) {
      clearInterval(games[data.token].interval);
      io.sockets.in(data.token).emit('player-resigned', {
        'color': data.color
      });
    }
  });

  socket.on('rematch-offer', function (data) {
    var opponent;

    if (data.token in games) {
      opponent = getOpponent(data.token, socket);
      if (opponent) {
        opponent.socket.emit('rematch-offered');
      }
    }
  });

  socket.on('rematch-decline', function (data) {
    var opponent;

    if (data.token in games) {
      opponent = getOpponent(data.token, socket);
      if (opponent) {
        opponent.socket.emit('rematch-declined');
      }
    }
  });

  socket.on('rematch-confirm', function (data) {
    var opponent;

    if (data.token in games) {

      for(var j in games[data.token].players) {
        games[data.token].players[j].time = data.time - data.increment + 1;
        games[data.token].players[j].increment = data.increment;
        games[data.token].players[j].color = games[data.token].players[j].color === 'black' ? 'white' : 'black';
      }

      opponent = getOpponent(data.token, socket);
      if (opponent) {
        io.sockets.in(data.token).emit('rematch-confirmed');
      }
    }
  })

  socket.on('disconnect', function (data) {
    var player, opponent, game;
    for (var token in games) {
    game = games[token];

      for (var j in game.players) {
        player = game.players[j];

        if (player.socket === socket) {
          opponent = game.players[Math.abs(j - 1)];
          opponent.socket.emit('opponent-disconnected');
          clearInterval(games[token].interval);
          delete games[token];
        }
      }
    }
  });

  socket.on('send-message', function (data) {
    if (data.token in games) {
      var opponent = getOpponent(data.token, socket);
      opponent.socket.emit('receive-message', data);
    }
  });
});

function runTimer(color, token, socket) {
  var player, time_left, game = games[token];

  if (!game) return;

  for (var i in game.players) {
    player = game.players[i];

    if (player.socket === socket && player.color === color) {

      clearInterval(games[token].interval);
      games[token].players[i].time += games[token].players[i].increment;

      return games[token].interval = setInterval(function() {
        games[token].players[i].time -= 1;
        time_left = games[token].players[i].time;

        if (time_left >= 0) {
          io.sockets.in(token).emit('countdown', {
            'time': time_left,
            'color': color
          });
        } else {
          io.sockets.in(token).emit('countdown-gameover', {
            'color': color
          });
          clearInterval(games[token].interval);
        }
      }, 1000);
    }
  }
}

function getOpponent(token, socket) {
  var player, game = games[token];

  for (var j in game.players) {
    player = game.players[j];

    if (player.socket === socket) {
      var opponent = game.players[Math.abs(j - 1)];

      return opponent;
    }
  }
}<commit_msg>fix: emit events only if opponent is available<commit_after>var express = require('express')
  , path    = require('path')
  , crypto  = require('crypto')
  , http    = require('http')
  , winston = require('winston')
  , fs      = require('fs');

var app = express();

app.configure(function() {
  app.set('ipaddress', process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1');
  app.set('port', process.env.OPENSHIFT_NODEJS_PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser('45710b553b5b7293753d03bd3601f70a'));
  app.use(express.session());
  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function() {
  app.use(express.errorHandler());
});

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

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

app.get('/play/:token/:time/:increment', function(req, res) {
  res.render('play', {
    'token': req.params.token,
    'time': req.params.time,
    'increment': req.params.increment
  });
});

app.get('/logs', function(req, res) {
  fs.readFile(__dirname + '/logs/games.log', function (err, data) {
    if (err) {
      res.redirect('/');
    }
    res.set('Content-Type', 'text/plain');
    res.send(data);
  });
});

var server = http.createServer(app).listen(app.get('port'), app.get('ipaddress'), function() {
  console.log("Express server listening on port " + app.get('port'));
});

var games = {};
var timer;

/**
 * Winston logger
 */
winston.add(winston.transports.File, {
  filename: __dirname + '/logs/games.log',
  handleExceptions: true,
  exitOnError: false,
  json: false
});
winston.remove(winston.transports.Console);
winston.handleExceptions(new winston.transports.Console());
winston.exitOnError = false;

/**
 * Sockets
 */
var io = require('socket.io').listen(server, {log: false});

  io.configure(function(){
    io.set('transports', ['websocket']);
  });

io.sockets.on('connection', function (socket) {

  socket.on('start', function (data) {
    var token;
    var b = new Buffer(Math.random() + new Date().getTime() + socket.id);
    token = b.toString('base64').slice(12, 32);

    //token is valid for 5 minutes
    var timeout = setTimeout(function () {
      if (games[token].players.length === 0) {
        delete games[token];
        socket.emit('token-expired');
      }
    }, 4000);

    games[token] = {
      'creator': socket,
      'players': [],
      'interval': null,
      'timeout': timeout
    };

    socket.emit('created', {
      'token': token
    });
  });

  socket.on('join', function (data) {
    var game, color, time = data.time;

    if (!(data.token in games)) {
      socket.emit('token-invalid');
      return;
    }

    clearTimeout(games[data.token].timeout);
    game = games[data.token];

    if (game.players.length >= 2) {
      socket.emit('full');
      return;
    } else if (game.players.length === 1) {
      if (game.players[0].color === 'black') {
        color = 'white';
      } else {
        color = 'black';
      }
      winston.log('info', 'Number of currently running games', { '#': Object.keys(games).length });
    } else {
      var colors = ['black', 'white'];

      color = colors[Math.floor(Math.random() * 2)];
    }

    //join room
    socket.join(data.token);

    games[data.token].players.push({
      'id': socket.id,
      'socket': socket,
      'color': color,
      'time': data.time - data.increment + 1,
      'increment': data.increment
    });

    game.creator.emit('ready', {});

    socket.emit('joined', {
      'color': color
    });
  });

  socket.on('timer-white', function (data) {
    runTimer('white', data.token, socket);
  });

  socket.on('timer-black', function (data) {
    runTimer('black', data.token, socket);
  });

  socket.on('timer-clear-interval', function (data) {
    if (data.token in games) {
      clearInterval(games[data.token].interval);
    }
  });

  socket.on('new-move', function (data) {
    var opponent;

    if (data.token in games) {
      opponent = getOpponent(data.token, socket);
      if (opponent) {
        opponent.socket.emit('move', {
          'move': data.move
        });
      }
    }
  });

  socket.on('resign', function (data) {
    if (data.token in games) {
      clearInterval(games[data.token].interval);
      io.sockets.in(data.token).emit('player-resigned', {
        'color': data.color
      });
    }
  });

  socket.on('rematch-offer', function (data) {
    var opponent;

    if (data.token in games) {
      opponent = getOpponent(data.token, socket);
      if (opponent) {
        opponent.socket.emit('rematch-offered');
      }
    }
  });

  socket.on('rematch-decline', function (data) {
    var opponent;

    if (data.token in games) {
      opponent = getOpponent(data.token, socket);
      if (opponent) {
        opponent.socket.emit('rematch-declined');
      }
    }
  });

  socket.on('rematch-confirm', function (data) {
    var opponent;

    if (data.token in games) {

      for(var j in games[data.token].players) {
        games[data.token].players[j].time = data.time - data.increment + 1;
        games[data.token].players[j].increment = data.increment;
        games[data.token].players[j].color = games[data.token].players[j].color === 'black' ? 'white' : 'black';
      }

      opponent = getOpponent(data.token, socket);
      if (opponent) {
        io.sockets.in(data.token).emit('rematch-confirmed');
      }
    }
  })

  socket.on('disconnect', function (data) {
    var player, opponent, game;
    for (var token in games) {
    game = games[token];

      for (var j in game.players) {
        player = game.players[j];

        if (player.socket === socket) {
          opponent = game.players[Math.abs(j - 1)];
          if (opponent) {
            opponent.socket.emit('opponent-disconnected');
          }
          clearInterval(games[token].interval);
          delete games[token];
        }
      }
    }
  });

  socket.on('send-message', function (data) {
    if (data.token in games) {
      var opponent = getOpponent(data.token, socket);
      if (opponent) {
        opponent.socket.emit('receive-message', data);
      }
    }
  });
});

function runTimer(color, token, socket) {
  var player, time_left, game = games[token];

  if (!game) return;

  for (var i in game.players) {
    player = game.players[i];

    if (player.socket === socket && player.color === color) {

      clearInterval(games[token].interval);
      games[token].players[i].time += games[token].players[i].increment;

      return games[token].interval = setInterval(function() {
        games[token].players[i].time -= 1;
        time_left = games[token].players[i].time;

        if (time_left >= 0) {
          io.sockets.in(token).emit('countdown', {
            'time': time_left,
            'color': color
          });
        } else {
          io.sockets.in(token).emit('countdown-gameover', {
            'color': color
          });
          clearInterval(games[token].interval);
        }
      }, 1000);
    }
  }
}

function getOpponent(token, socket) {
  var player, game = games[token];

  for (var j in game.players) {
    player = game.players[j];

    if (player.socket === socket) {
      var opponent = game.players[Math.abs(j - 1)];

      return opponent;
    }
  }
}<|endoftext|>


<commit_before>var gulp         = require('gulp');
var autoprefixer = require('gulp-autoprefixer');
var browsersync  = require('browser-sync').create();
var cache        = require('gulp-cache');
var coffee       = require('gulp-coffee');
var concat       = require('gulp-concat');
var csscomb      = require('gulp-csscomb');
var del          = require('del');
var imagemin     = require('gulp-imagemin');
var jshint       = require('gulp-jshint');
var less         = require('gulp-less');
var cleancss     = require('gulp-clean-css');
var plumber      = require('gulp-plumber');
var rename       = require('gulp-rename');
var sourcemaps   = require('gulp-sourcemaps');
var uglify       = require('gulp-uglify');

// Paths
var paths = {
    bower: './bower_components/',
    static: './htmlcsshonors/static/',
    templates: './htmlcsshonors/templates/',
    name: 'htmlcsshonors'
};

// Clean CSS
gulp.task('css:clean', function () {
    return del([
        paths.static + 'css/**/*.css',
        paths.static + 'css/**/*.map'
    ]);
});

// LESS
gulp.task('less', ['css:clean'], function () {
    return gulp.src([
        paths.static + 'less/**/*.less'
    ])
    .pipe(sourcemaps.init())
    .pipe(less())
    .pipe(sourcemaps.write('./', {
        includeContent: false,
        sourceRoot: '../less'
    }))
    .pipe(gulp.dest(paths.static + 'css'))
    .pipe(browsersync.stream());
});

// CSS
gulp.task('css', ['less'], function () {
    return gulp.src([
        paths.bower + 'bootstrap/dist/css/bootstrap.css',
        paths.static + 'css/**/*.css'
    ])
    .pipe(concat(paths.name + '.css'))
    .pipe(gulp.dest(paths.static + 'css'));
});

// Optimize CSS
gulp.task('css:optimize', ['css'], function () {
    return gulp.src([
        paths.static + 'css/**/*.css'
    ])
    .pipe(plumber({
        errorHandler: function (error) {
            console.log(error);
            this.emit('end');
        }
    }))
    .pipe(autoprefixer('last 2 versions'))
    .pipe(csscomb())
    .pipe(gulp.dest(paths.static + 'css'))
    .pipe(cleancss({
        advanced: false,
        keepSpecialComments: 0
    }))
    .pipe(rename({
        suffix: '.min'
    }))
    .pipe(gulp.dest(paths.static + 'css'));
});

// Clean JavaScript
gulp.task('js:clean', function () {
    return del([
        paths.static + 'js/**/*.js',
        paths.static + 'js/**/*.map',
        '!' + paths.static + 'js/script.js'
    ]);
});

// CoffeeScript
gulp.task('coffee', ['js:clean'], function () {
    return gulp.src([
        paths.static + 'coffee/**/*.coffee'
    ])
    .pipe(sourcemaps.init())
    .pipe(coffee())
    .pipe(sourcemaps.write('./', {
        includeContent: false,
        sourceRoot: '../coffee'
    }))
    .pipe(gulp.dest(paths.static + 'js'));
});

// JSHint
gulp.task('jshint', ['coffee'], function () {
    return gulp.src([
        paths.static + 'js/**/*.js'
    ])
    .pipe(jshint())
    .pipe(jshint.reporter('default'))
    .pipe(gulp.dest(paths.static + 'js'));
});

// JavaScript
gulp.task('js', ['jshint'], function () {
    return gulp.src([
        paths.bower + 'jquery/dist/jquery.js',
        paths.bower + 'bootstrap/dist/js/bootstrap.js',
        paths.static + 'js/**/*.js'
    ])
    .pipe(concat(paths.name + '.js'))
    .pipe(gulp.dest(paths.static + 'js'))
    .pipe(browsersync.stream());
});

// Optimize JavaScript
gulp.task('js:optimize', ['js'], function () {
    return gulp.src([
        paths.static + 'js/**/*.js'
    ])
    .pipe(plumber({
        errorHandler: function (error) {
            console.log(error);
            this.emit('end');
        }
    }))
    .pipe(gulp.dest(paths.static + 'js'))
    .pipe(uglify())
    .pipe(rename({
        suffix: '.min'
    }))
    .pipe(gulp.dest(paths.static + 'js'));
});

// Fonts
gulp.task('fonts', function () {
    return gulp.src([
        paths.bower + 'bootstrap/fonts/**/*.{eot,svg,ttf,woff,woff2}',
    ])
    .pipe(gulp.dest(paths.static + 'fonts'));
});

// Images
gulp.task('images', function () {
    return gulp.src([
        paths.static + 'img/**/*.{png,jpg,gif,bmp,ico}'
    ])
    .pipe(cache(imagemin({
        optimizationLevel: 3,
        progressive: true,
        interlaced: true
    })))
    .pipe(gulp.dest(paths.static + 'img'));
});

// Gulp watch tasks (keep it minimal)
gulp.task('watch', function () {
    browsersync.init({
        proxy: '127.0.0.1:8000',
    });
    gulp.watch([
        paths.static + 'less/**/*.less'
    ], ['css']);
    gulp.watch([
        paths.static + 'coffee/**/*.coffee',
        paths.static + 'js/script.js'
    ], ['js']);
    gulp.watch([
        paths.static + 'less/**/*.less',
        paths.static + 'coffee/**/*.coffee',
        paths.static + 'js/script.js',
        paths.templates + '*/**'
    ]).on('change', browsersync.reload);
});

// Gulp build task for deploy
gulp.task('default', [
    'css:optimize',
    'js:optimize',
    'images',
    'fonts'
]);
<commit_msg>BrowserSync needs to stream<commit_after>var gulp         = require('gulp');
var autoprefixer = require('gulp-autoprefixer');
var browsersync  = require('browser-sync').create();
var cache        = require('gulp-cache');
var coffee       = require('gulp-coffee');
var concat       = require('gulp-concat');
var csscomb      = require('gulp-csscomb');
var del          = require('del');
var imagemin     = require('gulp-imagemin');
var jshint       = require('gulp-jshint');
var less         = require('gulp-less');
var cleancss     = require('gulp-clean-css');
var plumber      = require('gulp-plumber');
var rename       = require('gulp-rename');
var sourcemaps   = require('gulp-sourcemaps');
var uglify       = require('gulp-uglify');

// Paths
var paths = {
    bower: './bower_components/',
    static: './htmlcsshonors/static/',
    templates: './htmlcsshonors/templates/',
    name: 'htmlcsshonors'
};

// Clean CSS
gulp.task('css:clean', function () {
    return del([
        paths.static + 'css/**/*.css',
        paths.static + 'css/**/*.map'
    ]);
});

// LESS
gulp.task('less', ['css:clean'], function () {
    return gulp.src([
        paths.static + 'less/**/*.less'
    ])
    .pipe(sourcemaps.init())
    .pipe(less())
    .pipe(sourcemaps.write('./', {
        includeContent: false,
        sourceRoot: '../less'
    }))
    .pipe(gulp.dest(paths.static + 'css'))
    .pipe(browsersync.stream({stream: true}));
});

// CSS
gulp.task('css', ['less'], function () {
    return gulp.src([
        paths.bower + 'bootstrap/dist/css/bootstrap.css',
        paths.static + 'css/**/*.css'
    ])
    .pipe(concat(paths.name + '.css'))
    .pipe(gulp.dest(paths.static + 'css'));
});

// Optimize CSS
gulp.task('css:optimize', ['css'], function () {
    return gulp.src([
        paths.static + 'css/**/*.css'
    ])
    .pipe(plumber({
        errorHandler: function (error) {
            console.log(error);
            this.emit('end');
        }
    }))
    .pipe(autoprefixer('last 2 versions'))
    .pipe(csscomb())
    .pipe(gulp.dest(paths.static + 'css'))
    .pipe(cleancss({
        advanced: false,
        keepSpecialComments: 0
    }))
    .pipe(rename({
        suffix: '.min'
    }))
    .pipe(gulp.dest(paths.static + 'css'));
});

// Clean JavaScript
gulp.task('js:clean', function () {
    return del([
        paths.static + 'js/**/*.js',
        paths.static + 'js/**/*.map',
        '!' + paths.static + 'js/script.js'
    ]);
});

// CoffeeScript
gulp.task('coffee', ['js:clean'], function () {
    return gulp.src([
        paths.static + 'coffee/**/*.coffee'
    ])
    .pipe(sourcemaps.init())
    .pipe(coffee())
    .pipe(sourcemaps.write('./', {
        includeContent: false,
        sourceRoot: '../coffee'
    }))
    .pipe(gulp.dest(paths.static + 'js'));
});

// JSHint
gulp.task('jshint', ['coffee'], function () {
    return gulp.src([
        paths.static + 'js/**/*.js'
    ])
    .pipe(jshint())
    .pipe(jshint.reporter('default'))
    .pipe(gulp.dest(paths.static + 'js'));
});

// JavaScript
gulp.task('js', ['jshint'], function () {
    return gulp.src([
        paths.bower + 'jquery/dist/jquery.js',
        paths.bower + 'bootstrap/dist/js/bootstrap.js',
        paths.static + 'js/**/*.js'
    ])
    .pipe(concat(paths.name + '.js'))
    .pipe(gulp.dest(paths.static + 'js'))
    .pipe(browsersync.stream());
});

// Optimize JavaScript
gulp.task('js:optimize', ['js'], function () {
    return gulp.src([
        paths.static + 'js/**/*.js'
    ])
    .pipe(plumber({
        errorHandler: function (error) {
            console.log(error);
            this.emit('end');
        }
    }))
    .pipe(gulp.dest(paths.static + 'js'))
    .pipe(uglify())
    .pipe(rename({
        suffix: '.min'
    }))
    .pipe(gulp.dest(paths.static + 'js'));
});

// Fonts
gulp.task('fonts', function () {
    return gulp.src([
        paths.bower + 'bootstrap/fonts/**/*.{eot,svg,ttf,woff,woff2}',
    ])
    .pipe(gulp.dest(paths.static + 'fonts'));
});

// Images
gulp.task('images', function () {
    return gulp.src([
        paths.static + 'img/**/*.{png,jpg,gif,bmp,ico}'
    ])
    .pipe(cache(imagemin({
        optimizationLevel: 3,
        progressive: true,
        interlaced: true
    })))
    .pipe(gulp.dest(paths.static + 'img'));
});

// Gulp watch tasks (keep it minimal)
gulp.task('watch', function () {
    browsersync.init({
        proxy: '127.0.0.1:8000',
    });
    gulp.watch([
        paths.static + 'less/**/*.less'
    ], ['css']);
    gulp.watch([
        paths.static + 'coffee/**/*.coffee',
        paths.static + 'js/script.js'
    ], ['js']);
    gulp.watch([
        paths.static + 'less/**/*.less',
        paths.static + 'coffee/**/*.coffee',
        paths.static + 'js/script.js',
        paths.templates + '*/**'
    ]).on('change', browsersync.reload);
});

// Gulp build task for deploy
gulp.task('default', [
    'css:optimize',
    'js:optimize',
    'images',
    'fonts'
]);
<|endoftext|>


<commit_before>var fs = require("fs");
var express = require("express");
var app = express();
var socketio = require("socket.io");
var sass = require("node-sass");
var http = require("http");

var PORT = process.env.PORT || 3000;

/* make a list of emoji */

var stickers = [];
var STICKERS_DIRNAME = __dirname + "/public/img/stickers/";

function makeStickersList(filenames) {
    stickers.length = 0;
    filenames.forEach(function(filename) {
        stickers.push(filename.slice(0, -4));
    });
}

makeStickersList(fs.readdirSync(STICKERS_DIRNAME));

fs.watch(STICKERS_DIRNAME, function() {
    makeStickersList(fs.readdirSync(STICKERS_DIRNAME));
});

/* function for sending error page */

function sendError(res, code) {
    var text = http.STATUS_CODES[code] || "Something went wrong";
    res.render("views/error.jade", {
        status_code: code,
        status_text: text
    });
}

/* set up express */

app.set("views", __dirname + "/public");
app.set("view engine", "jade");

app.get("/", function(req, res) {
    res.render("index.jade", {
        stickers: stickers
    });
});

app.get("/:path.html", function(req, res) {
    res.render(req.params.path + ".jade", {
        stickers: stickers
    });
});

app.get("/:path.css", function(req, res) {
    sass.render({
        file: __dirname + "/public/" + req.params.path + ".scss",
    }, function(err, result) {
        if (!err) {
            res.append("Content-Type", "text/css");
            res.send(result.css);
        } else {
            res.sendFile(__dirname + "/public" + req.originalUrl);
        }
    });
});

app.get("/file/:id/*", function(req, res) {
    var mediaID = req.params.id;
    if (files.hasOwnProperty(mediaID)) {
        var fileObject = files[mediaID];
        var file = fileObject.file;
        var type = fileObject.type;
        res.append("Content-Type", type || "text/plain");
        res.send(file);
    } else {
        sendError(res, 404);
    }
});

app.get("/yeya", function(req, res) {
    sendError(res, "418");
});

app.get("*", function(req, res) {
    fs.exists(__dirname + "/public" + req.originalUrl, function(exists) {
        if (exists) {
            res.sendFile(__dirname + "/public" + req.originalUrl);
        } else {
            sendError(res, 404);
        }
    });
});

var files = {};

var server = app.listen(PORT, function() {
    var host = server.address().address;
    var port = server.address().port;

    console.log("Abungo running on port %s", port);

    /* hey ho, let's go */

    var io = socketio(server);

    var rooms = {};

    var disconnectUser = function(room, nick) {
        var user = room.users[nick];
        if (user) {
            delete room.users[nick];
            Object.keys(room.users).forEach(function(userNick) {
                var rUser = room.users[userNick];
                rUser.socket.emit("user_left", {
                    nick: nick
                });
            });
            console.log("disconnected", nick);
        }
    };

    /* delete files that have expired */

    setInterval(function() {
        Object.keys(files).forEach(function(mediaID) {
            var file = files[mediaID];
            var now = new Date();
            var delta = now - file.uploadedDate;
            console.log(mediaID, delta, 600000 - delta);
            if (delta > 600000) { // 10 minutes
                delete files[mediaID];
                console.log("deleted" + mediaID, files);
            }
        });
    }, 5000);

    /* socket messages (the actual stuff) */

    io.on("connection", function(socket){
        socket.emit("connected", {
            date: new Date()
        });

        console.log("new connection");

        socket.on("login", function(data){
            var nickTaken = false;

            if (rooms[data.room] && rooms[data.room].users.hasOwnProperty(data.nick)) {
                nickTaken = true;
            }

            if (!nickTaken) {
                if (!rooms[data.room]) {
                    rooms[data.room] = {
                        users: {}
                    };
                }

                var room = rooms[data.room];
                var userID = data.userID || ("" + new Date().getTime() + Math.round(Math.random() * 10000));
                room.users[data.nick] = {
                    socket: socket,
                    userID: userID,
                    nick: data.nick,
                    ip: socket.handshake.address
                };
                var user = room.users[data.nick];
                console.log("%s (%s) joined room '%s'", user.nick, user.ip, data.room);

                if (data.rejoin) {
                    socket.emit("login_rejoin_accepted", {
                        userID: userID,
                        nick: data.nick,
                        room: data.room,
                        users: Object.keys(room.users)
                    });
                } else {
                    socket.emit("login_accepted", {
                        userID: userID,
                        nick: data.nick,
                        room: data.room,
                        users: Object.keys(room.users)
                    });
                }

                Object.keys(room.users).forEach(function(userNick) {
                    var user = room.users[userNick];
                    user.socket.emit("user_joined", {
                        nick: data.nick
                    });
                });

                socket.on("message", function(data) {
                    //setTimeout(function(){
                    var isFile = !!data.mediaUpload;
                    var isSticker = !!data.sticker;

                    var sendableMessageData = {
                        nick: user.nick,
                        messageID: data.messageID // for sender client use only
                    };

                    if (isFile) {
                        if (data.mediaUpload.length < 10000000) { // 10 mb
                            var mediaID = "" + Math.round(Math.random() * 100000) + new Date().getTime();
                            files[mediaID] = {
                                file: data.mediaUpload,
                                type: data.mediaType,
                                uploadedDate: new Date()
                            };
                            sendableMessageData.mediaID = mediaID;
                            sendableMessageData.mediaName = data.mediaName;
                            sendableMessageData.mediaType = data.mediaType;

                            console.log("%s (%s) sent file: %s (%s)", user.nick, user.ip, data.mediaName, data.mediaType);
                        } else {
                            sendableMessageData = null;
                            console.log("%s (%s) tried to send huge file: %s (%s)", user.nick, user.ip, data.mediaName, data.mediaType);
                        }
                    } else if (isSticker) {
                        sendableMessageData.sticker = data.sticker;
                        sendableMessageData.stickerSize = data.stickerSize;

                        console.log("%s (%s) sent sticker '%s'", user.nick, user.ip, data.sticker);
                    } else {
                        sendableMessageData.message = data.message;

                        console.log("%s (%s) said: %s", user.nick, user.ip, data.message);
                    }

                    if (sendableMessageData) {
                        Object.keys(room.users).forEach(function(userNick) {
                            var user = room.users[userNick];
                            user.socket.emit("message_incoming", sendableMessageData);
                        });
                    }
                    //}, 2000);
                });

                socket.on("typing_start", function(data) {
                    Object.keys(room.users).forEach(function(userNick) {
                        var tuser = room.users[userNick];
                        tuser.socket.emit("typing_start", {
                            nick: user.nick
                        });
                    });
                });

                socket.on("typing_stop", function(data) {
                    Object.keys(room.users).forEach(function(userNick) {
                        var tuser = room.users[userNick];
                        tuser.socket.emit("typing_stop", {
                            nick: user.nick
                        });
                    });
                });

                socket.on("ping", function(data) {
                    socket.emit("pong");
                    user.lastPing = new Date();
                });
                var pingInterval = setInterval(function(){
                    if (room.users[data.nick] && room.users[data.nick].userID === user.userID) {
                        if (!user.lastPing) {
                            user.lastPing = new Date();
                        }
                        var delta = new Date() - user.lastPing;

                        if (delta > 30000) {
                            socket.disconnect();
                        }

                        console.log(data.nick, delta);
                    } else {
                        clearInterval(pingInterval);
                    }
                }, 5000);

                socket.on("disconnect", function() {
                    disconnectUser(room, user.nick);
                });
            } else {
                var nickTakenUser = rooms[data.room].users[data.nick];
                if (nickTakenUser.userID !== data.userID) {
                    socket.emit("login_rejected");
                    console.log("login rejected");
                }
            }
        });

        socket.on("login_resume", function(data) {
            var room = rooms[data.room];
            if (room && room.users && room.users.hasOwnProperty(data.nick) && room.users[data.nick].userID === data.userID) {
                room.users[data.nick].socket = socket;
            } else {
                socket.emit("login_resume_rejected");
            }
        });
    });
});
<commit_msg>Less crap in console<commit_after>var fs = require("fs");
var express = require("express");
var app = express();
var socketio = require("socket.io");
var sass = require("node-sass");
var http = require("http");

var PORT = process.env.PORT || 3000;

/* make a list of emoji */

var stickers = [];
var STICKERS_DIRNAME = __dirname + "/public/img/stickers/";

function makeStickersList(filenames) {
    stickers.length = 0;
    filenames.forEach(function(filename) {
        stickers.push(filename.slice(0, -4));
    });
}

makeStickersList(fs.readdirSync(STICKERS_DIRNAME));

fs.watch(STICKERS_DIRNAME, function() {
    makeStickersList(fs.readdirSync(STICKERS_DIRNAME));
});

/* function for sending error page */

function sendError(res, code) {
    var text = http.STATUS_CODES[code] || "Something went wrong";
    res.render("views/error.jade", {
        status_code: code,
        status_text: text
    });
}

/* set up express */

app.set("views", __dirname + "/public");
app.set("view engine", "jade");

app.get("/", function(req, res) {
    res.render("index.jade", {
        stickers: stickers
    });
});

app.get("/:path.html", function(req, res) {
    res.render(req.params.path + ".jade", {
        stickers: stickers
    });
});

app.get("/:path.css", function(req, res) {
    sass.render({
        file: __dirname + "/public/" + req.params.path + ".scss",
    }, function(err, result) {
        if (!err) {
            res.append("Content-Type", "text/css");
            res.send(result.css);
        } else {
            res.sendFile(__dirname + "/public" + req.originalUrl);
        }
    });
});

app.get("/file/:id/*", function(req, res) {
    var mediaID = req.params.id;
    if (files.hasOwnProperty(mediaID)) {
        var fileObject = files[mediaID];
        var file = fileObject.file;
        var type = fileObject.type;
        res.append("Content-Type", type || "text/plain");
        res.send(file);
    } else {
        sendError(res, 404);
    }
});

app.get("/yeya", function(req, res) {
    sendError(res, "418");
});

app.get("*", function(req, res) {
    fs.exists(__dirname + "/public" + req.originalUrl, function(exists) {
        if (exists) {
            res.sendFile(__dirname + "/public" + req.originalUrl);
        } else {
            sendError(res, 404);
        }
    });
});

var files = {};

var server = app.listen(PORT, function() {
    var host = server.address().address;
    var port = server.address().port;

    console.log("Abungo running on port %s", port);

    /* hey ho, let's go */

    var io = socketio(server);

    var rooms = {};

    var disconnectUser = function(room, nick) {
        var user = room.users[nick];
        if (user) {
            delete room.users[nick];
            Object.keys(room.users).forEach(function(userNick) {
                var rUser = room.users[userNick];
                rUser.socket.emit("user_left", {
                    nick: nick
                });
            });
            console.log("disconnected", nick);
        }
    };

    /* delete files that have expired */

    setInterval(function() {
        Object.keys(files).forEach(function(mediaID) {
            var file = files[mediaID];
            var now = new Date();
            var delta = now - file.uploadedDate;
            if (delta > 600000) { // 10 minutes
                delete files[mediaID];
                console.log("deleted" + mediaID, files);
            }
        });
    }, 5000);

    /* socket messages (the actual stuff) */

    io.on("connection", function(socket){
        socket.emit("connected", {
            date: new Date()
        });

        console.log("new connection");

        socket.on("login", function(data){
            var nickTaken = false;

            if (rooms[data.room] && rooms[data.room].users.hasOwnProperty(data.nick)) {
                nickTaken = true;
            }

            if (!nickTaken) {
                if (!rooms[data.room]) {
                    rooms[data.room] = {
                        users: {}
                    };
                }

                var room = rooms[data.room];
                var userID = data.userID || ("" + new Date().getTime() + Math.round(Math.random() * 10000));
                room.users[data.nick] = {
                    socket: socket,
                    userID: userID,
                    nick: data.nick,
                    ip: socket.handshake.address
                };
                var user = room.users[data.nick];
                console.log("%s (%s) joined room '%s'", user.nick, user.ip, data.room);

                if (data.rejoin) {
                    socket.emit("login_rejoin_accepted", {
                        userID: userID,
                        nick: data.nick,
                        room: data.room,
                        users: Object.keys(room.users)
                    });
                } else {
                    socket.emit("login_accepted", {
                        userID: userID,
                        nick: data.nick,
                        room: data.room,
                        users: Object.keys(room.users)
                    });
                }

                Object.keys(room.users).forEach(function(userNick) {
                    var user = room.users[userNick];
                    user.socket.emit("user_joined", {
                        nick: data.nick
                    });
                });

                socket.on("message", function(data) {
                    //setTimeout(function(){
                    var isFile = !!data.mediaUpload;
                    var isSticker = !!data.sticker;

                    var sendableMessageData = {
                        nick: user.nick,
                        messageID: data.messageID // for sender client use only
                    };

                    if (isFile) {
                        if (data.mediaUpload.length < 10000000) { // 10 mb
                            var mediaID = "" + Math.round(Math.random() * 100000) + new Date().getTime();
                            files[mediaID] = {
                                file: data.mediaUpload,
                                type: data.mediaType,
                                uploadedDate: new Date()
                            };
                            sendableMessageData.mediaID = mediaID;
                            sendableMessageData.mediaName = data.mediaName;
                            sendableMessageData.mediaType = data.mediaType;

                            console.log("%s (%s) sent file: %s (%s)", user.nick, user.ip, data.mediaName, data.mediaType);
                        } else {
                            sendableMessageData = null;
                            console.log("%s (%s) tried to send huge file: %s (%s)", user.nick, user.ip, data.mediaName, data.mediaType);
                        }
                    } else if (isSticker) {
                        sendableMessageData.sticker = data.sticker;
                        sendableMessageData.stickerSize = data.stickerSize;

                        console.log("%s (%s) sent sticker '%s'", user.nick, user.ip, data.sticker);
                    } else {
                        sendableMessageData.message = data.message;

                        console.log("%s (%s) said: %s", user.nick, user.ip, data.message);
                    }

                    if (sendableMessageData) {
                        Object.keys(room.users).forEach(function(userNick) {
                            var user = room.users[userNick];
                            user.socket.emit("message_incoming", sendableMessageData);
                        });
                    }
                    //}, 2000);
                });

                socket.on("typing_start", function(data) {
                    Object.keys(room.users).forEach(function(userNick) {
                        var tuser = room.users[userNick];
                        tuser.socket.emit("typing_start", {
                            nick: user.nick
                        });
                    });
                });

                socket.on("typing_stop", function(data) {
                    Object.keys(room.users).forEach(function(userNick) {
                        var tuser = room.users[userNick];
                        tuser.socket.emit("typing_stop", {
                            nick: user.nick
                        });
                    });
                });

                socket.on("ping", function(data) {
                    socket.emit("pong");
                    user.lastPing = new Date();
                });
                var pingInterval = setInterval(function(){
                    if (room.users[data.nick] && room.users[data.nick].userID === user.userID) {
                        if (!user.lastPing) {
                            user.lastPing = new Date();
                        }
                        var delta = new Date() - user.lastPing;

                        if (delta > 30000) {
                            socket.disconnect();
                        }
                    } else {
                        clearInterval(pingInterval);
                    }
                }, 5000);

                socket.on("disconnect", function() {
                    disconnectUser(room, user.nick);
                });
            } else {
                var nickTakenUser = rooms[data.room].users[data.nick];
                if (nickTakenUser.userID !== data.userID) {
                    socket.emit("login_rejected");
                    console.log("login rejected");
                }
            }
        });

        socket.on("login_resume", function(data) {
            var room = rooms[data.room];
            if (room && room.users && room.users.hasOwnProperty(data.nick) && room.users[data.nick].userID === data.userID) {
                room.users[data.nick].socket = socket;
            } else {
                socket.emit("login_resume_rejected");
            }
        });
    });
});
<|endoftext|>


<commit_before>var browserSync = require('browser-sync').create();
var gulp        = require('gulp');
var jade        = require('gulp-jade');
var notify      = require('gulp-notify');
var plumber     = require('gulp-plumber');
var pleeease    = require('gulp-pleeease');
var sass        = require('gulp-sass');
var sourcemaps  = require('gulp-sourcemaps');

paths = {
  jade: ['./jade/'],
  scss: ['./scss/']
};

gulp.task('browser-sync', function() {
   browserSync.init({
     server: {
       baseDir: './'
     }
   });
});
gulp.task('jade', function() {
  gulp.src([paths.jade + '**/*.jade', '!' + paths.jade + '**/_*.jade'])
    .pipe(plumber({
      errorHandler: notify.onError('Error: <%= error.message %>')
    }))
    .pipe(jade({
      pretty: true
    }))
    .pipe(gulp.dest('./'))
    .pipe(browserSync.stream());
});
gulp.task('sass', function() {
  gulp.src(paths.scss + '**/*.scss')
    .pipe(plumber({
      errorHandler: notify.onError('Error: <%= error.message %>')
    }))
    .pipe(sass({outputStyle: 'compressed'}))
    .pipe(sourcemaps.init())
    .pipe(pleeease({
      browsers: ['last 2 versions'],
      minifier: false
    }))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('./'))
    .pipe(browserSync.stream());
});

gulp.task('default', ['jade','sass','browser-sync'], function() {
  gulp.watch([paths.jade + '**/*.jade'], ['jade']);
  gulp.watch([paths.scss + '**/*.scss'], ['sass']);
});
<commit_msg>対象ファイルの除外処理の改善<commit_after>var browserSync = require('browser-sync').create();
var gulp        = require('gulp');
var jade        = require('gulp-jade');
var notify      = require('gulp-notify');
var plumber     = require('gulp-plumber');
var pleeease    = require('gulp-pleeease');
var sass        = require('gulp-sass');
var sourcemaps  = require('gulp-sourcemaps');

paths = {
  jade: ['./jade/'],
  scss: ['./scss/']
};

gulp.task('browser-sync', function() {
   browserSync.init({
     server: {
       baseDir: './'
     }
   });
});
gulp.task('jade', function() {
  gulp.src([paths.jade + '**/!(_)*.jade'])
    .pipe(plumber({
      errorHandler: notify.onError('Error: <%= error.message %>')
    }))
    .pipe(jade({
      pretty: true
    }))
    .pipe(gulp.dest('./'))
    .pipe(browserSync.stream());
});
gulp.task('sass', function() {
  gulp.src(paths.scss + '**/*.scss')
    .pipe(plumber({
      errorHandler: notify.onError('Error: <%= error.message %>')
    }))
    .pipe(sass({outputStyle: 'compressed'}))
    .pipe(sourcemaps.init())
    .pipe(pleeease({
      browsers: ['last 2 versions'],
      minifier: false
    }))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('./'))
    .pipe(browserSync.stream());
});

gulp.task('default', ['jade','sass','browser-sync'], function() {
  gulp.watch([paths.jade + '**/*.jade'], ['jade']);
  gulp.watch([paths.scss + '**/*.scss'], ['sass']);
});
<|endoftext|>


<commit_before>var express = require('express'),
	http = require('http'),
    api = require('./routes/callsApi');

var app = express();

app.configure(function () {
    app.set('port', process.env.PORT || 3000);
    app.use(express.logger('dev'));  /* 'default', 'short', 'tiny', 'dev' */
    app.use(express.bodyParser());
    //app.use(express.static(path.join(__dirname, 'public')));
});

app.get('/api/findById/:id', api.findById); // TESTE FIND ONE
app.get('/', api.findRaiz);
app.get('/api/mesas', api.mesas); // /api/getmesas
app.get('/api/mesa/:idmesa', api.consumomesa); // /api/getmesa/ID_MESA --- FIND ITENS (not findOne) return list objects
app.get('/api/produto', api.produto); // /api/GetProduto
app.get('/api/produtogrupo', api.produtogrupo); // /api/GetProdutoGrupo
app.get('/api/garcom', api.garcom); // /api/GetGarcom

app.put('/api/atualizarmesa', api.atualizarmesa); // /api/atualizarmesa?id=1&situacao=2

app.get('/api/consumomesa/:idmesa', api.getconsumomesa); // /api/getmesa/ID_MESA --- FIND ITENS (not findOne) return list objects
app.post('/api/consumomesa', api.addconsumomesa); // /api/addconsumomesa?mesaid=1&deviceid=2&produtoid=2&quantidade=1

app.post('/api/agendamento', api.clear); // agendamento pra limpar as mesas e os consumos

http.createServer(app).listen(app.get('port'), function () {
    console.log("Express server listening on port " + app.get('port'));
});<commit_msg>alteracao nos nomes<commit_after>var express = require('express'),
	http = require('http'),
    api = require('./routes/callsApi');

var app = express();

app.configure(function () {
    app.set('port', process.env.PORT || 3000);
    //app.use(express.logger('dev'));  /* 'default', 'short', 'tiny', 'dev' */
    app.use(express.bodyParser());
    //app.use(express.static(path.join(__dirname, 'public')));
});

app.get('/api/findById/:id', api.findById); // TESTE FIND ONE
app.get('/', api.findRaiz);
app.get('/api/mesas', api.mesas); // /api/getmesas
app.get('/api/produto', api.produto); // /api/GetProduto
app.get('/api/produtogrupo', api.produtogrupo); // /api/GetProdutoGrupo
app.get('/api/garcom', api.garcom); // /api/GetGarcom

app.put('/api/atualizarmesa', api.atualizarmesa); // /api/atualizarmesa?id=1&situacao=2

app.get('/api/mesa/:idmesa', api.getconsumomesa); // /api/getmesa/ID_MESA --- FIND ITENS (not findOne) return list objects
app.get('/api/consumomesa/:idmesa', api.getconsumomesa); // /api/getmesa/ID_MESA --- FIND ITENS (not findOne) return list objects
app.post('/api/consumomesa', api.addconsumomesa); // /api/addconsumomesa?mesaid=1&deviceid=2&produtoid=2&quantidade=1

app.post('/api/agendamento', api.clear); // agendamento pra limpar as mesas e os consumos

http.createServer(app).listen(app.get('port'), function () {
    console.log("Express server listening on port " + app.get('port'));
});<|endoftext|>


<commit_before>var admin = require('firebase-admin');
var express = require('express');
var app = express();
var path = require('path');
var router = express.Router();

var serviceAccount = require("path/to/serviceAccountKey.json");

app.use(express.static(path.join(__dirname, 'wwww')));

app.get('*', function(req,res){
	res.sendfile('/www.index.html');
});

var server = app.listen(8080, function() {
	console.log('Server running at http://localhost:8080');
}

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
});

<commit_msg>modified server.js<commit_after>var admin = require('firebase-admin');
var express = require('express');
var app = express();
var path = require('path');
var router = express.Router();

var serviceAccount = require("path/to/serviceAccountKey.json");

app.use(express.static(path.join(__dirname, 'wwww')));

app.get('*', function(req,res){
	res.sendfile('/www.index.html');
});

var server = app.listen(8080, function() {
	console.log('Server running at http://localhost:8080');
});

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://tardy-ccd34.firebaseio.com"
});

<|endoftext|>


<commit_before>// server.js
var express = require('express');
var app = express();
var server = require("http").createServer(app);
var io = require('socket.io')(server);
var port = 3000;

//create the node server and serve the files
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {
        res.sendFile(__dirname + '/public/index.html');
});
server.listen(port);
console.log('Cage Bot is now available to worship at http://45.55.86.193:' + port);

//SocketIO connection handler and listening
io.on('connect', function (socket) {
        console.log("your socket id is ", socket.id);

        socket.on('public-join', function(data) {
          console.log('worshiper connected');
        });

        socket.on('cage-pi-connect', function(data) {
            console.log(data);
        });

        socket.on('disconnect', function() {
          console.log('browser closed');
        })
});

<commit_msg>server.js<commit_after>// server.js
var express = require('express');
var app = express();
var server = require("http").createServer(app);
var io = require('socket.io')(server);
var port = 3000;

//create the node server and serve the files
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {
        res.sendFile(__dirname + '/public/index.html');
});
server.listen(port);
console.log('Cage Bot is now available to worship at http://45.55.86.193:' + port);

//SocketIO connection handler and listening
io.on('connect', function (socket) {
        console.log("your socket id is ", socket.id);

        socket.on('public-join', function(data) {
          console.log(data);
        });

        socket.on('cage-pi-connect', function(data) {
            console.log(data);
        });

        socket.on('disconnect', function() {
          console.log('browser closed');
        })
});

<|endoftext|>


<commit_before>// server.js

    // set up ========================
	var port = process.env.PORT || 8081;
	require('console');
    var express  = require('express');
    var app      = express();                               // create our app express
    var mongoose = require('mongoose');                     // mongoose for mongodb
    var morgan = require('morgan');             // log requests to the console (express4)
    var bodyParser = require('body-parser');    // pull information from HTML POST (express4)
    var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)

    // configuration =================

  	//mongoose.connect('mongodb://localhost:27017/mean'); //Local dB
	mongoose.connect('mongodb://vvaisan:Miisu#Kiti@waffle.modulusmongo.net:27017/etiRyw3y'); //Remote dB
    app.use(express.static(__dirname + '/public'));                 // set the static files location /public/img will be /img for users
    app.use(morgan('dev'));                                         // log every request to the console
    app.use(bodyParser.urlencoded({'extended':'true'}));            // parse application/x-www-form-urlencoded
    app.use(bodyParser.json());                                     // parse application/json
    app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
    app.use(methodOverride());
	//app.use(require('browser-logger')()); //Added 7.1.2016, Also %npm install browser-logger. Don't work in heroku server

	var Todo = mongoose.model('Todo', {
        text : String,
		completed:{
			type: Boolean,
  		    default: false
		},
		note: String,
		updated_at:  {type: Date, default:Date.now }
    });
	app.get('/api/todos', function(req, res) {

        // use mongoose to get all todos in the database
        Todo.find(function(err, todos) {

            // if there is an error retrieving, send the error. nothing after res.send(err) will execute
            if (err)
                res.send(err)

            res.json(todos); // return all todos in JSON format
        });
    });

    // create todo and send back all todos after creation
    app.post('/api/todos', function(req, res) {

        // create a todo, information comes from AJAX request from Angular
         Todo.create({
            text : req.body.text,
			completed: req.body.completed,
            note : req.body.note
        }, function(err, todo) {
            if (err)
                res.send(err);

            // get and return all the todos after you create another
            Todo.find(function(err, todos) {
                if (err)
                    res.send(err)
                res.json(todos);
            });
        });

    });

	// update a todo (completed)
    app.put('/api/todos/:todo_id', function(req, res) {
 		Todo.update({_id: req.params.todo_id}, {
        completed: true
		} , function(err, todo) {
            if (err)
                res.send(err);

            // get and return all the todos after you create another
            Todo.find(function(err, todos) {
                if (err)
                    res.send(err)
                res.json(todos);
            });
        });

    });

    // delete a todo
    app.delete('/api/todos/:todo_id', function(req, res) {
        Todo.remove({
            _id : req.params.todo_id
        }, function(err, todo) {
            if (err)
                res.send(err);

            // get and return all the todos after you create another
            Todo.find(function(err, todos) {
                if (err)
                    res.send(err)
                res.json(todos);
            });
        });
    });

	 // application -------------------------------------------------------------
    app.get('*', function(req, res) {
        res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
    });

    // listen (start app with node server.js) ======================================
    app.listen(port);
    console.log("App listening on port" + port);
<commit_msg>Added comment in line 2<commit_after>// server.js
// In this file there is also RestAPI
    // set up ========================
	var port = process.env.PORT || 8081;
	require('console');
    var express  = require('express');
    var app      = express();                               // create our app express
    var mongoose = require('mongoose');                     // mongoose for mongodb
    var morgan = require('morgan');             // log requests to the console (express4)
    var bodyParser = require('body-parser');    // pull information from HTML POST (express4)
    var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)

    // configuration =================

  	//mongoose.connect('mongodb://localhost:27017/mean'); //Local dB
	mongoose.connect('mongodb://vvaisan:Miisu#Kiti@waffle.modulusmongo.net:27017/etiRyw3y'); //Remote dB
    app.use(express.static(__dirname + '/public'));                 // set the static files location /public/img will be /img for users
    app.use(morgan('dev'));                                         // log every request to the console
    app.use(bodyParser.urlencoded({'extended':'true'}));            // parse application/x-www-form-urlencoded
    app.use(bodyParser.json());                                     // parse application/json
    app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
    app.use(methodOverride());
	//app.use(require('browser-logger')()); //Added 7.1.2016, Also %npm install browser-logger. Don't work in heroku server

	var Todo = mongoose.model('Todo', {
        text : String,
		completed:{
			type: Boolean,
  		    default: false
		},
		note: String,
		updated_at:  {type: Date, default:Date.now }
    });
	app.get('/api/todos', function(req, res) {

        // use mongoose to get all todos in the database
        Todo.find(function(err, todos) {

            // if there is an error retrieving, send the error. nothing after res.send(err) will execute
            if (err)
                res.send(err)

            res.json(todos); // return all todos in JSON format
        });
    });

    // create todo and send back all todos after creation
    app.post('/api/todos', function(req, res) {

        // create a todo, information comes from AJAX request from Angular
         Todo.create({
            text : req.body.text,
			completed: req.body.completed,
            note : req.body.note
        }, function(err, todo) {
            if (err)
                res.send(err);

            // get and return all the todos after you create another
            Todo.find(function(err, todos) {
                if (err)
                    res.send(err)
                res.json(todos);
            });
        });

    });

	// update a todo (completed)
    app.put('/api/todos/:todo_id', function(req, res) {
 		Todo.update({_id: req.params.todo_id}, {
        completed: true
		} , function(err, todo) {
            if (err)
                res.send(err);

            // get and return all the todos after you create another
            Todo.find(function(err, todos) {
                if (err)
                    res.send(err)
                res.json(todos);
            });
        });

    });

    // delete a todo
    app.delete('/api/todos/:todo_id', function(req, res) {
        Todo.remove({
            _id : req.params.todo_id
        }, function(err, todo) {
            if (err)
                res.send(err);

            // get and return all the todos after you create another
            Todo.find(function(err, todos) {
                if (err)
                    res.send(err)
                res.json(todos);
            });
        });
    });

	 // application -------------------------------------------------------------
    app.get('*', function(req, res) {
        res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
    });

    // listen (start app with node server.js) ======================================
    app.listen(port);
    console.log("App listening on port" + port);
<|endoftext|>


<commit_before>/**
 * Created by chrissu on 12/12/15.
 */
var preferencesCommunities = require('./lib/preferencesCommunities');
var directionsCommunities = require('./lib/directionsCommunities');
var validator = require('validator');
var express = require('express');

var app = express();

app.use(express.static('public'));

function validOps(ops) {
  for (var op in ops) {
    if (ops[op] !== '<' && ops[op] !== '>') {
      return false;
    }
  }
  return true;
}

function validNums(nums) {
  for (var num in nums) {
    if (!validator.isInt(nums[num]) || num < 1 || num > 5) {
      return false;
    }
  }
  return true;
}

function validParams(opsAndNums) {
  return opsAndNums.ops && opsAndNums.nums && validOps(opsAndNums.ops) &&
      validNums(opsAndNums.nums);
}

// jscs:disable
// http://localhost:8080/preferences?ops[violentCrime]=%3C&ops[nonViolentCrime]=%3C&ops[nightlife]=%3E&ops[price]=%3C&ops[crowded]=%3C&nums[violentCrime]=4&nums[nonViolentCrime]=3&nums[nightlife]=4&nums[price]=4&nums[crowded]=2
// jscs:enable
app.get('/preferences', function(req, res) {
  if (validParams(req.query)) {
    var params = {
      violentCrimePctOfAvg: [req.query.ops.violentCrime,
                              req.query.nums.violentCrime],
      nonViolentCrimePctOfAvg: [req.query.ops.nonViolentCrime,
                                req.query.nums.nonViolentCrime],
      nightlifePctOfAvg: [req.query.ops.nightlife, req.query.nums.nightlife],
      pricePctOfAvg: [req.query.ops.price, req.query.nums.price],
      crowdedPctOfAvg: [req.query.ops.crowded, req.query.nums.crowded]
    };
    preferencesCommunities.communitiesByPreferences(params,
                                                    function(err, result) {
      if (err) {
        res.send('
Error with request
');
      } else {
        res.send(result);
      }
    });
  } else {
    res.send('
Error with request
');
  }
});

// jscs:disable
// http://localhost:8080/directions?destination=201%20S%20Wacker%20Dr,%20Chicago,%20IL&mode=driving
// jscs:enable
app.get('/directions', function(req, res) {
  if (req.query.destination && req.query.mode &&
      (req.query.mode === 'driving' || req.query.mode === 'transit')) {
    var params = {
      destination: req.query.destination,
      mode: req.query.mode
    };
    directionsCommunities.getTimeToCommunities(params, function(err, result) {
      if (err) {
        res.send('
Error with request
');
      } else {
        res.send(result);
      }
    });
  } else {
    res.send('
Error with request
');
  }
});

app.listen(8080, function() {
  console.log('listening to port localhost:8080');
});
<commit_msg>Tommy tried to fix his bad code, but didn't finish.<commit_after>/**
 * Created by chrissu on 12/12/15.
 */
var preferencesCommunities = require('./lib/preferencesCommunities');
var directionsCommunities = require('./lib/directionsCommunities');
var validator = require('validator');
var express = require('express');

var app = express();

app.use(express.static('public'));

function validOp(op) {
  return op === '<' || op === '>';
}

function validNum(num) {
  return validator.isInt(num) && num > 0 && num < 6;
}

function validParam(param) {
  var valid = {
    violentCrime: true,
    nonViolentCrime: true,
    nightlife: true,
    price: true,
    crowded: true
  };
  if (valid[param]) {
    return true;
  } else {
    return false;
  }
}

function validParams(opsAndNums) {
  for (var preference in opsAndNums) {
    if (opsAndNums.hasOwnProperty(preference) &&
          (!validOp(opsAndNums[preference].op) ||
          !validNum(opsAndNums[preference].num) ||
          !validParam(preference))) {
      return false;
    }
  }
  return true;
}

// jscs:disable
// http://localhost:8080/preferences?violentCrime[op]=%3C&nonViolentCrime[op]=%3C&nightlife[op]=%3E&price[op]=%3C&crowded[op]=%3C&violentCrime[num]=4&nonViolentCrime[num]=3&nightlife[num]=4&price[num]=4&crowded[num]=2
// jscs:enable
app.get('/preferences', function(req, res) {
  console.log(req.query);
  if (validParams(req.query)) {
    var params = {
      violentCrimePctOfAvg: [req.query.violentCrime.op,
                              req.query.violentCrime.num],
      nonViolentCrimePctOfAvg: [req.query.nonViolentCrime.op,
                                req.query.nonViolentCrime.num],
      nightlifePctOfAvg: [req.query.nightlife.op, req.query.nightlife.num],
      pricePctOfAvg: [req.query.price.op, req.query.price.num],
      crowdedPctOfAvg: [req.query.crowded.op, req.query.crowded.num]
    };
    preferencesCommunities.communitiesByPreferences(params,
                                                    function(err, result) {
      if (err) {
        res.send('
Error with request
');
      } else {
        res.send(result);
      }
    });
  } else {
    res.send('
Error with request
');
  }
});

// jscs:disable
// http://localhost:8080/directions?destination=201%20S%20Wacker%20Dr,%20Chicago,%20IL&mode=driving
// jscs:enable
app.get('/directions', function(req, res) {
  console.log(req.query);
  if (req.query.destination && req.query.mode &&
      (req.query.mode === 'driving' || req.query.mode === 'transit')) {
    var params = {
      destination: req.query.destination,
      mode: req.query.mode
    };
    directionsCommunities.getTimeToCommunities(params, function(err, result) {
      if (err) {
        res.send('
Error with request
');
      } else {
        res.send(result);
      }
    });
  } else {
    res.send('
Error with request
');
  }
});

app.listen(8080, function() {
  console.log('listening to port localhost:8080');
});
<|endoftext|>