<commit_before>var _path = require('path');
var _fs = require('fs');

var walk = require('walkdir');

var util = require('../util');

var toSystem = util.toSystem;
var toRelative = util.toRelative;

var config = require('../config');
var streamer = require('../vlc');
var hdhomerun = require('../hdhomerun');

var collections = [];
Object.keys(config.collections).forEach(function (collection) {
  collections.push({
    name: collection,
    path: config.collections[collection],
  });
});

var valid_extensions = {};
Object.keys(config.formats).forEach(function (type) {
  config.formats[type].forEach(function (ext) {
    valid_extensions[ext] = type;
  });
});

var hdhomeruns = [];
Object.keys(config.hdhomerun).forEach(function(device) {
  var hd = config.hdhomerun[device];
  hdhomeruns.push({
    id: hd.id,
    name: device,
    tuners: Object.keys(hd.tuners),
  });
});

var db = require('dirty')(_path.join(__dirname, '..', 'index.db'));

exports.index = function(req, res){
  res.render('index', {
    title: 'NimbusMeus',
    collections: collections,
    hdhomerun: hdhomeruns,
  });
};

exports.listing = function (req, res) {
  var spath = toSystem(req.params[0]);
  var title = 'Listing for: ';
  if (spath.path) {
    var d = db.get(spath.path);

    d.dirs.forEach(function (dir) {
      dir.name = _path.basename(dir.path);
      dir.path = toRelative(dir.path, spath);
    });

    d.files.forEach(function (file) {
      file.name = _path.basename(file.path);
      file.path = toRelative(file.path, spath);
    });

    res.render('listing', {
      title: _path.basename(spath.path),
      dirs: d.dirs,
      files: d.files,
   });
  } else {
    res.render('error', {
      title: 'Error in Listing',
      error: 'Path does not exist',
    });
  }
};

exports.view = function (req, res) {
  var title = 'Viewing: ';
  var sessid = req.session.id;
  var waiting = true;
  var montior, ext, timeoud, timerid, canRender;

  var spath = toSystem(req.params[0]);

  if (spath.path) {
    title += _path.basename(spath.path);

    ext = _path.extname(spath.path).toLowerCase().replace('.', '');
    ext = valid_extensions[ext];

    streamer.play({
      sess: sessid,
      mrl: spath.path,
      host: req.headers.host,
      settings: req.session.settings || {},
      type: ext,
    }, function (err, monitor) {
      streamer.waitStream(monitor.path, 15000, function (err) {
        if (err) {
          res.render('error', {
            title: 'Streaming Error',
            error: err,
          });
          return;
        }

        res.render('view', {
          title: title,
          path: monitor.url,
        });
      });
    });;
  }
};

exports.stream = function (req, res) {
  var path = req.params[0];
  var sessid = req.session.id;

  var file = _path.normalize(_path.join(
    util.tmpdir(), sessid, _path.join.apply(null, path.split('/')
  )));

  res.sendfile(file);
};

exports.settings = function (req, res) {
  var settings = req.session.settings || {};

  res.render('settings', {
    title: 'Settings',
    refer: req.header('Referrer'),
    bandwidth: settings.bandwidth ? settings.bandwidth : 0,
    fps: settings.fps ? settings.fps : 0,
    width: settings.width ? settings.width : 0,
    height: settings.height ? settings.height : 0,
  });
};

exports.settings_save = function (req, res) {
  var settings = req.session.settings || {};

  settings.bandwidth = req.body.bandwidth;
  settings.fps = req.body.fps;
  settings.width = req.body.width;
  settings.height = req.body.height;

  req.session.save();

  if (req.body.refer) {
    res.redirect(req.body.refer);
  } else {
    res.render('settings', {
      title: 'Settings',
      refer: req.header('Referrer'),
      bandwidth: settings.bandwidth ? settings.bandwidth : 0,
      fps: settings.fps ? settings.fps : 0,
      width: settings.width ? settings.width : 0,
      height: settings.height ? settings.height : 0,
    });
  }
};

exports.tv = function (req, res) {
  var tunerfile = config.hdhomerun[req.params.device].tuners[req.params.tuner];

  hdhomerun.parse(tunerfile, function (err, channels) {
    if (err) {
      res.render('error', {
        title: 'TV Parse Error',
        error: err,
      });
      return;
    }

    res.render('tv', {
      title: 'TV Channels',
      channels: channels,
      device: config.hdhomerun[req.params.device].id,
      tuner: req.params.tuner,
    });
  });
};

exports.tv_view = function (req, res) {
  var sessid = req.session.id;

  hdhomerun.tune(req.params, function (err) {
    if (err) {
      res.render('error', {
        title: 'TV View Error',
        error: err,
      });
      return;
    }

    streamer.play({
      sess: sessid,
      mrl:  'udp://@:5000',
      type: 'video',
      live: true,
      host: req.headers.host,
      settings: req.session.settings || {},
    }, function (err, monitor) {

      hdhomerun.stream(req.params, function (err) {
        if (err) {
          res.render('error', {
            title: 'HDHomeRun Stream Error',
            error: err,
          });
          return;
        }
        streamer.waitStream(monitor.path, 30000, function (err) {
          if (err) {
            res.render('error', {
              title: 'HDHomeRun Stream Wait Error',
              error: err,
            });
            return;
          }
          res.render('view', {
            title: 'Live TV',
            path: monitor.url,
          });
        });
      });
    });
  });
};
<commit_msg>restore sorting of files and directories<commit_after>var _path = require('path');
var _fs = require('fs');

var walk = require('walkdir');

var util = require('../util');

var toSystem = util.toSystem;
var toRelative = util.toRelative;

var config = require('../config');
var streamer = require('../vlc');
var hdhomerun = require('../hdhomerun');

var collections = [];
Object.keys(config.collections).forEach(function (collection) {
  collections.push({
    name: collection,
    path: config.collections[collection],
  });
});

var valid_extensions = {};
Object.keys(config.formats).forEach(function (type) {
  config.formats[type].forEach(function (ext) {
    valid_extensions[ext] = type;
  });
});

var hdhomeruns = [];
Object.keys(config.hdhomerun).forEach(function(device) {
  var hd = config.hdhomerun[device];
  hdhomeruns.push({
    id: hd.id,
    name: device,
    tuners: Object.keys(hd.tuners),
  });
});

var db = require('dirty')(_path.join(__dirname, '..', 'index.db'));

exports.index = function(req, res){
  res.render('index', {
    title: 'NimbusMeus',
    collections: collections,
    hdhomerun: hdhomeruns,
  });
};

exports.listing = function (req, res) {
  var spath = toSystem(req.params[0]);
  var title = 'Listing for: ';
  var d = db.get(spath.path || 'DNE');

  if (spath.path && d) {
    d.dirs.forEach(function (dir) {
      dir.name = _path.basename(dir.path);
      dir.path = toRelative(dir.path, spath);
    });

    d.files.forEach(function (file) {
      file.name = _path.basename(file.path);
      file.path = toRelative(file.path, spath);
    });

    var compare = function (a, b) {
      return a.name.toLowerCase() > b.name.toLowerCase() ? 1 : -1;
    }

    res.render('listing', {
      title: _path.basename(spath.path),
      dirs: d.dirs.sort(compare),
      files: d.files.sort(compare),
   });
  } else {
    res.render('error', {
      title: 'Error in Listing',
      error: 'Path does not exist',
    });
  }
};

exports.view = function (req, res) {
  var title = 'Viewing: ';
  var sessid = req.session.id;
  var waiting = true;
  var montior, ext, timeoud, timerid, canRender;

  var spath = toSystem(req.params[0]);

  if (spath.path) {
    title += _path.basename(spath.path);

    ext = _path.extname(spath.path).toLowerCase().replace('.', '');
    ext = valid_extensions[ext];

    streamer.play({
      sess: sessid,
      mrl: spath.path,
      host: req.headers.host,
      settings: req.session.settings || {},
      type: ext,
    }, function (err, monitor) {
      streamer.waitStream(monitor.path, 15000, function (err) {
        if (err) {
          res.render('error', {
            title: 'Streaming Error',
            error: err,
          });
          return;
        }

        res.render('view', {
          title: title,
          path: monitor.url,
        });
      });
    });;
  }
};

exports.stream = function (req, res) {
  var path = req.params[0];
  var sessid = req.session.id;

  var file = _path.normalize(_path.join(
    util.tmpdir(), sessid, _path.join.apply(null, path.split('/')
  )));

  res.sendfile(file);
};

exports.settings = function (req, res) {
  var settings = req.session.settings || {};

  res.render('settings', {
    title: 'Settings',
    refer: req.header('Referrer'),
    bandwidth: settings.bandwidth ? settings.bandwidth : 0,
    fps: settings.fps ? settings.fps : 0,
    width: settings.width ? settings.width : 0,
    height: settings.height ? settings.height : 0,
  });
};

exports.settings_save = function (req, res) {
  var settings = req.session.settings || {};

  settings.bandwidth = req.body.bandwidth;
  settings.fps = req.body.fps;
  settings.width = req.body.width;
  settings.height = req.body.height;

  req.session.save();

  if (req.body.refer) {
    res.redirect(req.body.refer);
  } else {
    res.render('settings', {
      title: 'Settings',
      refer: req.header('Referrer'),
      bandwidth: settings.bandwidth ? settings.bandwidth : 0,
      fps: settings.fps ? settings.fps : 0,
      width: settings.width ? settings.width : 0,
      height: settings.height ? settings.height : 0,
    });
  }
};

exports.tv = function (req, res) {
  var tunerfile = config.hdhomerun[req.params.device].tuners[req.params.tuner];

  hdhomerun.parse(tunerfile, function (err, channels) {
    if (err) {
      res.render('error', {
        title: 'TV Parse Error',
        error: err,
      });
      return;
    }

    res.render('tv', {
      title: 'TV Channels',
      channels: channels,
      device: config.hdhomerun[req.params.device].id,
      tuner: req.params.tuner,
    });
  });
};

exports.tv_view = function (req, res) {
  var sessid = req.session.id;

  hdhomerun.tune(req.params, function (err) {
    if (err) {
      res.render('error', {
        title: 'TV View Error',
        error: err,
      });
      return;
    }

    streamer.play({
      sess: sessid,
      mrl:  'udp://@:5000',
      type: 'video',
      live: true,
      host: req.headers.host,
      settings: req.session.settings || {},
    }, function (err, monitor) {

      hdhomerun.stream(req.params, function (err) {
        if (err) {
          res.render('error', {
            title: 'HDHomeRun Stream Error',
            error: err,
          });
          return;
        }
        streamer.waitStream(monitor.path, 30000, function (err) {
          if (err) {
            res.render('error', {
              title: 'HDHomeRun Stream Wait Error',
              error: err,
            });
            return;
          }
          res.render('view', {
            title: 'Live TV',
            path: monitor.url,
          });
        });
      });
    });
  });
};
<|endoftext|>


<commit_before>var fs = require('fs'),
	gulp = require('gulp'),
	less = require('gulp-less'),
	clean = require('gulp-clean'),
	//postcss = require('gulp-postcss'),
	rename = require('gulp-rename'),
    concatCss = require('gulp-concat-css'),
    concat = require('gulp-concat'),
    coffee = require('gulp-coffee');

var sources = {
	coffee: [
		'vendor/mermetbt/biome/src/resources/js/app.coffee'
	],
	css: [
		'vendor/mermetbt/biome/src/resources/css/app.css'
	],
	js: [
		//'vendor/mermetbt/biome/src/resources/js/app.js'
	],
	vendor_css: [
		'vendor/bower_components/font-awesome/css/font-awesome.css',
		'build/css/bootstrap.css',
		//'vendor/bower_components/bootstrap/dist/css/bootstrap.css',
		//'vendor/bower_components/bootstrap/dist/css/bootstrap-theme.css',
		'vendor/bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.css',
		'vendor/bower_components/datatables-responsive-helper/files/1.10/css/datatables.responsive.css',
		//'vendor/bower_components/datatables/media/css/jquery.dataTables.css',
		//'vendor/bower_components/datatables/media/css/dataTables.bootstrap.css',
		'vendor/bower_components/select2-ng/dist/css/select2.min.css'
	],
	vendor_js: [
		'vendor/bower_components/jquery/dist/jquery.js',
		'vendor/bower_components/bootstrap/dist/js/bootstrap.js',
		'vendor/bower_components/datatables/media/js/jquery.dataTables.js',
		'vendor/bower_components/datatables/media/js/dataTables.bootstrap.js',
		//'vendor/bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.min.js',
		'vendor/bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.min.js',
		'vendor/bower_components/autosize/dist/autosize.min.js',
		'vendor/bower_components/select2-ng/dist/js/select2.full.min.js'
	],
	vendor_fonts: [
		'vendor/bower_components/bootstrap/dist/fonts/*',
		'vendor/bower_components/font-awesome/fonts/*'
	]
}

gulp.task('check', function () {
	var found = true;
	for(var i in sources.coffee)
	{
		if(!fs.existsSync(sources.coffee[i]))
		{
			console.error(sources.coffee[i] + ' not found!');
			found = false;
		}
	}
	for(var i in sources.css)
	{
		if(!fs.existsSync(sources.css[i]))
		{
			console.error(sources.css[i] + ' not found!');
			found = false;
		}
	}
	for(var i in sources.js)
	{
		if(!fs.existsSync(sources.js[i]))
		{
			console.error(sources.js[i] + ' not found!');
			found = false;
		}
	}
	for(var i in sources.vendor_js)
	{
		if(!fs.existsSync(sources.vendor_js[i]))
		{
			console.error(sources.vendor_js[i] + ' not found!');
			found = false;
		}
	}
	for(var i in sources.vendor_css)
	{
		if(!fs.existsSync(sources.vendor_css[i]))
		{
			console.error(sources.vendor_css[i] + ' not found!');
			found = false;
		}
	}
	return found;
});

/**
 * Clean the directories
 */
gulp.task('clean', function () {
	return gulp.src(['build/css/*.css', 'build/js/*.js', 'public/css/*.min.css', 'public/js/*.min.js'], {read: false})
		.pipe(clean());
});

/**
 * Compile bootstrap with less
 */
gulp.task('build-bootstrap-less', function(){
    return gulp.src('resources/less/bootstrap.less')
        .pipe(less())
        .pipe(gulp.dest('build/css/'));
});

/**
 * Handle biome
 */
gulp.task('biome_css', function () {
	return gulp.src(sources.css)
		.pipe(concatCss('app.css'))
		.pipe(gulp.dest('build/css/'));
});

gulp.task('biome_js', function() {
	return gulp.src(sources.js)
		.pipe(concat('app.js'))
		.pipe(gulp.dest('build/js/'));
});

/**
 * Vendor
 */

gulp.task('vendor_css', ['build-bootstrap-less'], function () {
	return gulp.src(sources.vendor_css)
		.pipe(concatCss('vendor.css', {rebaseUrls: false}))
		.pipe(gulp.dest('build/css/'));
});

gulp.task('vendor_js', function () {
	return gulp.src(sources.vendor_js)
		.pipe(concat('vendor.js'))
		.pipe(gulp.dest('build/js/'));
});

gulp.task('vendor_fonts', function () {
	return gulp.src(sources.vendor_fonts)
		.pipe(gulp.dest('public/fonts/'));
});

gulp.task('vendor', ['vendor_css', 'vendor_js', 'vendor_fonts']);

/**
 * Compile coffee script
 */
gulp.task('coffee', ['biome_js'], function () {
    return gulp.src(sources.coffee)
        .pipe(coffee({bare: true}))
        .pipe(concat('app.js'))
        .pipe(gulp.dest('build/js/'))
        .on('error', console.log);
});

/**
 * Handle app resources
 */
gulp.task('resources_css', ['biome_css', 'build-bootstrap-less'], function() {
	return gulp.src('resources/css/*.css')
		.pipe(concatCss('app.css'))
		.pipe(gulp.dest('build/css/'));
});
gulp.task('resources_js', ['coffee', 'biome_js'], function() {
	return gulp.src('resources/js/*.js')
		.pipe(concat('app.js'))
		.pipe(gulp.dest('build/js/'));
});
gulp.task('resources_fonts', function() {
	return gulp.src('resources/fonts/**/*')
		.pipe(gulp.dest('public/fonts/'));
});
gulp.task('resources_images', function() {
	return gulp.src('resources/images/*')
		.pipe(gulp.dest('public/images/'));
});

gulp.task('resources', ['resources_css', 'resources_js', 'resources_fonts', 'resources_images']);

/**
 * Minify CSS
 */
gulp.task('cssmin', function () {
    return gulp.src(['build/css/app.css', 'build/css/vendor.css'])
        //.pipe(require('gulp-cssmin')())
        .pipe(rename({suffix: '.min'}))
        .pipe(gulp.dest('public/css'));
});

/**
 * Uglify
 */
gulp.task('uglify', function () {
    return gulp.src(['build/js/app.js', 'build/js/vendor.js'])
        //.pipe(require('gulp-uglify')())
        .pipe(rename({suffix: '.min'}))
        .pipe(gulp.dest('public/js'));
});

/**
 * Build
 */
gulp.task('minify', ['cssmin', 'uglify']);

gulp.task('build', ['vendor', 'resources'], function() {
	return gulp.start('minify');
});

gulp.task('default', ['clean'], function() {
	return gulp.start('build');
});
<commit_msg>Fix compilation.<commit_after>var fs = require('fs'),
	gulp = require('gulp'),
	less = require('gulp-less'),
	clean = require('gulp-clean'),
	//postcss = require('gulp-postcss'),
	rename = require('gulp-rename'),
    concatCss = require('gulp-concat-css'),
    concat = require('gulp-concat'),
    coffee = require('gulp-coffee');

var sources = {
	coffee: [
		'vendor/mermetbt/biome/src/resources/js/app.coffee'
	],
	css: [
		'vendor/mermetbt/biome/src/resources/css/app.css',
		'resources/css/*.css'
	],
	js: [
		//'vendor/mermetbt/biome/src/resources/js/app.js'
		'build/js/app.coffee.js',
		'resources/js/*.js'
	],
	vendor_css: [
		'vendor/bower_components/font-awesome/css/font-awesome.css',
		'build/css/bootstrap.css',
		//'vendor/bower_components/bootstrap/dist/css/bootstrap.css',
		//'vendor/bower_components/bootstrap/dist/css/bootstrap-theme.css',
		'vendor/bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.css',
		'vendor/bower_components/datatables-responsive-helper/files/1.10/css/datatables.responsive.css',
		//'vendor/bower_components/datatables/media/css/jquery.dataTables.css',
		//'vendor/bower_components/datatables/media/css/dataTables.bootstrap.css',
		'vendor/bower_components/select2-ng/dist/css/select2.min.css'
	],
	vendor_js: [
		'vendor/bower_components/jquery/dist/jquery.js',
		'vendor/bower_components/bootstrap/dist/js/bootstrap.js',
		'vendor/bower_components/datatables/media/js/jquery.dataTables.js',
		'vendor/bower_components/datatables/media/js/dataTables.bootstrap.js',
		//'vendor/bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.min.js',
		'vendor/bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.min.js',
		'vendor/bower_components/autosize/dist/autosize.min.js',
		'vendor/bower_components/select2-ng/dist/js/select2.full.min.js'
	],
	vendor_fonts: [
		'vendor/bower_components/bootstrap/dist/fonts/*',
		'vendor/bower_components/font-awesome/fonts/*'
	]
}

gulp.task('check', function () {
	var found = true;
	for(var i in sources.coffee)
	{
		if(!fs.existsSync(sources.coffee[i]))
		{
			console.error(sources.coffee[i] + ' not found!');
			found = false;
		}
	}
	for(var i in sources.css)
	{
		if(!fs.existsSync(sources.css[i]))
		{
			console.error(sources.css[i] + ' not found!');
			found = false;
		}
	}
	for(var i in sources.js)
	{
		if(!fs.existsSync(sources.js[i]))
		{
			console.error(sources.js[i] + ' not found!');
			found = false;
		}
	}
	for(var i in sources.vendor_js)
	{
		if(!fs.existsSync(sources.vendor_js[i]))
		{
			console.error(sources.vendor_js[i] + ' not found!');
			found = false;
		}
	}
	for(var i in sources.vendor_css)
	{
		if(!fs.existsSync(sources.vendor_css[i]))
		{
			console.error(sources.vendor_css[i] + ' not found!');
			found = false;
		}
	}
	return found;
});

/**
 * Clean the directories
 */
gulp.task('clean', function () {
	return gulp.src(['build/css/*.css', 'build/js/*.js', 'public/css/*.min.css', 'public/js/*.min.js'], {read: false})
		.pipe(clean());
});

/**
 * Compile bootstrap with less
 */
gulp.task('build-bootstrap-less', function(){
    return gulp.src('resources/less/bootstrap.less')
        .pipe(less())
        .pipe(gulp.dest('build/css/'));
});

/**
 * Vendor
 */

gulp.task('vendor_css', ['build-bootstrap-less'], function () {
	return gulp.src(sources.vendor_css)
		.pipe(concatCss('vendor.css', {rebaseUrls: false}))
		.pipe(gulp.dest('build/css/'));
});

gulp.task('vendor_js', function () {
	return gulp.src(sources.vendor_js)
		.pipe(concat('vendor.js'))
		.pipe(gulp.dest('build/js/'));
});

gulp.task('vendor_fonts', function () {
	return gulp.src(sources.vendor_fonts)
		.pipe(gulp.dest('public/fonts/'));
});

gulp.task('vendor', ['vendor_css', 'vendor_js', 'vendor_fonts']);

/**
 * Compile coffee script
 */
gulp.task('coffee', function () {
    return gulp.src(sources.coffee)
        .pipe(coffee({bare: true}))
        .pipe(concat('app.coffee.js'))
        .pipe(gulp.dest('build/js/'))
        .on('error', console.log);
});

/**
 * Handle app resources
 */
gulp.task('resources_css', ['build-bootstrap-less'], function() {
	return gulp.src(sources.css)
		.pipe(concatCss('app.css', {rebaseUrls: false}))
		.pipe(gulp.dest('build/css/'));
});
gulp.task('resources_js', ['coffee'], function() {
	return gulp.src(sources.js)
		.pipe(concat('app.js'))
		.pipe(gulp.dest('build/js/'));
});
gulp.task('resources_fonts', function() {
	return gulp.src('resources/fonts/**/*')
		.pipe(gulp.dest('public/fonts/'));
});
gulp.task('resources_images', function() {
	return gulp.src('resources/images/*')
		.pipe(gulp.dest('public/images/'));
});

gulp.task('resources', ['resources_css', 'resources_js', 'resources_fonts', 'resources_images']);

/**
 * Minify CSS
 */
gulp.task('cssmin', function () {
    return gulp.src(['build/css/app.css', 'build/css/vendor.css'])
        //.pipe(require('gulp-cssmin')())
        .pipe(rename({suffix: '.min'}))
        .pipe(gulp.dest('public/css'));
});

/**
 * Uglify
 */
gulp.task('uglify', function () {
    return gulp.src(['build/js/app.js', 'build/js/vendor.js'])
        //.pipe(require('gulp-uglify')())
        .pipe(rename({suffix: '.min'}))
        .pipe(gulp.dest('public/js'));
});

/**
 * Build
 */
gulp.task('minify', ['cssmin', 'uglify']);

gulp.task('build', ['vendor', 'resources'], function() {
	return gulp.start('minify');
});

gulp.task('default', ['clean'], function() {
	return gulp.start('build');
});
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();

var moment = require("moment");
var later = require("later");
var botgram = require("botgram");

var bot = botgram(process.env.TELEGRAM_TOKEN);

const ConfigState = {
	NONE: 0,
	DATE: 1,
	DATE_CONFIRMATION: 2,
	PILL_TYPE: 3,
	ALARM_TIME: 4,
	COMPLETED: 5
};

var timers = {};

bot.context({ isAsking: ConfigState.NONE });

bot.command("start", function (msg, reply, next) {
	console.log("Start from: ", msg.from.id);
	reply.text("Ciao! Sono Bibot.");

	askStepDate(msg, reply);
});

bot.text(function (msg, reply, next) {
	console.log("Received a text message:", msg.text);

	switch (msg.context.isAsking) {
		case ConfigState.DATE:
			stepDate(msg, reply);
			break;

		case ConfigState.DATE_CONFIRMATION:
			stepDateConfirmation(msg, reply);
			break;

		case ConfigState.PILL_TYPE:
			stepPillType(msg, reply);
			break;

		case ConfigState.ALARM_TIME:
			stepAlarmTime(msg, reply);
			break;
	}
});

function askStepDate(msg, reply) {
	let today = moment().format("YYYY-MM-DD");
	msg.context.isAsking = ConfigState.DATE;
	reply.text("In che giorno hai iniziato a prendere la pillola? Ad esempio: " + today);
}

function stepDate(msg, reply) {
	let dateRaw = msg.text;
	let date = moment(dateRaw, "YYYY-MM-DD");

	if (!date.isValid()) {
		reply.text("La data è errata. Puoi reinserirla?");
		return;
	}

	msg.context.isAsking = ConfigState.DATE_CONFIRMATION;
	msg.context.stepDate = date;
	let formatted = date.locale("IT").format("LLLL");
	reply.text("Confermi questa data? (S/N) \n" + formatted);
}

function stepDateConfirmation(msg, reply) {
	let answerText = msg.text.toLowerCase();

	if (answerText == "n" || answerText == "no") {
		reply.text("Va bene, ricominciamo.");
		askStepDate(msg, reply);
		return;
	}

	if (answerText != "s" && answerText != "si") {
		reply.text("Lo prendo come un no.");
		askStepDate(msg, reply);
		return;
	}

	askStepPillType(msg, reply);
}

function askStepPillType(msg, reply) {
	msg.context.isAsking = ConfigState.PILL_TYPE;
	msg.context.stepDateConfirmation = true;
	reply.text("Prendi una pillola da 21 o da 28 giorni? (21/28)");
}

function stepPillType(msg, reply) {
	let pillType = msg.text;

	if (pillType != "21" && pillType != "28") {
		reply.text("Scusa, non ho capito.");
		askStepPillType(msg, reply);
		return;
	}

	msg.context.stepPillType = pillType;

	askStepAlarmTime(msg, reply);
}

function askStepAlarmTime(msg, reply) {
	msg.context.isAsking = ConfigState.ALARM_TIME;
	reply.text("A che ora vuoi che ti avvisi?");
}

function stepAlarmTime(msg, reply) {
	let timeRaw = msg.text;
	let time = moment(timeRaw, ['h:m a', 'H:m']);

	if (!time.isValid()) {
		reply.text("L'orario è scritto in modo errato. Puoi scriverlo di nuovo?");
		return;
	}

	msg.context.isAsking = ConfigState.COMPLETED;
	msg.context.stepAlarmTime = time;

	setScheduling(msg, reply);
}

function setScheduling(msg, reply) {
	let startingDateMoment = msg.context.stepDate;
	let startingDate = startingDateMoment.utc().format("DDD");

	let timeMoment = msg.context.stepAlarmTime;
	let time = timeMoment.utc().format("HH:mm");

	let pillType = msg.context.stepPillType;

	let sched;
	if (pillType == "28") {
		sched = later.parse.recur().after(startingDate).dayOfYear().on(time).time();
	}
	else if (pillType == "21") {
		sched = later.parse.recur().after(startingDate).dayOfYear().on(time).time().except().every(4).weekOfYear();
	}
	else {
		reply.text("Ho avuto dei problemi mentre impostavo il timer. Puoi ripetere ripartendo da /start?");
		return;
	}

	var occurrences = later.schedule(sched).next(100);
	var schedText = "";
	for (var i = 0; i < 100; i++) {
		schedText += occurrences[i] + '\n';
	}

	reply.text("Ti avviserò questi giorni: \n" + schedText);

	let timer = later.setInterval(function () {
		reply.text("Ehi, prendi la pillola!");
	}, sched);

	let id = msg.chat.id;

	let oldTimer = timers[id];
	if (oldPinger) oldTimer.clear();

	timers[id] = timer;
}

bot.command("stop", function (msg, reply, next) {
	console.log("Stopped from: ", msg.from.id);
	msg.context.isAsking = ConfigState.NONE;

	let id = msg.chat.id;

	let oldTimer = timers[id];
	if (!oldPinger) {
		reply.text("Non hai nessun allarme da fermare!");
		return;
	}

	oldTimer.clear();
	reply.text("Ho fermato l'allarme. Puoi ripetere la configurazione con /start.");
	reply.text("Ciao, a presto!");
});

/* GET home page. */
router.get('/', function (req, res, next) {
	res.render('index', { title: 'Bibot' });
});

module.exports = router;
<commit_msg>Fix messages<commit_after>var express = require('express');
var router = express.Router();

var moment = require("moment");
var later = require("later");
var botgram = require("botgram");

var bot = botgram(process.env.TELEGRAM_TOKEN);

const ConfigState = {
	NONE: 0,
	DATE: 1,
	DATE_CONFIRMATION: 2,
	PILL_TYPE: 3,
	ALARM_TIME: 4,
	COMPLETED: 5
};

var timers = {};

bot.context({ isAsking: ConfigState.NONE });

bot.command("start", function (msg, reply, next) {
	console.log("Start from: ", msg.from.id);
	reply.text("Ciao! Sono Bibot.");

	askStepDate(msg, reply);
});

bot.text(function (msg, reply, next) {
	console.log("Received a text message:", msg.text);

	switch (msg.context.isAsking) {
		case ConfigState.DATE:
			stepDate(msg, reply);
			break;

		case ConfigState.DATE_CONFIRMATION:
			stepDateConfirmation(msg, reply);
			break;

		case ConfigState.PILL_TYPE:
			stepPillType(msg, reply);
			break;

		case ConfigState.ALARM_TIME:
			stepAlarmTime(msg, reply);
			break;
	}
});

function askStepDate(msg, reply) {
	let today = moment().format("YYYY-MM-DD");
	msg.context.isAsking = ConfigState.DATE;
	reply.text("In che giorno hai iniziato a prendere la pillola? Ad esempio: " + today);
}

function stepDate(msg, reply) {
	let dateRaw = msg.text;
	let date = moment(dateRaw, "YYYY-MM-DD");

	if (!date.isValid()) {
		reply.text("La data è errata. Puoi reinserirla?");
		return;
	}

	msg.context.isAsking = ConfigState.DATE_CONFIRMATION;
	msg.context.stepDate = date;
	let formatted = date.locale("IT").format("dddd, D MMMM YYYY");
	reply.text("Confermi questa data? (S/N) \n" + formatted);
}

function stepDateConfirmation(msg, reply) {
	let answerText = msg.text.toLowerCase();

	if (answerText == "n" || answerText == "no") {
		reply.text("Va bene, ricominciamo.");
		askStepDate(msg, reply);
		return;
	}

	if (answerText != "s" && answerText != "si") {
		reply.text("Lo prendo come un no.");
		askStepDate(msg, reply);
		return;
	}

	askStepPillType(msg, reply);
}

function askStepPillType(msg, reply) {
	msg.context.isAsking = ConfigState.PILL_TYPE;
	msg.context.stepDateConfirmation = true;
	reply.text("Prendi una pillola da 21 o da 28 giorni? (21/28)");
}

function stepPillType(msg, reply) {
	let pillType = msg.text;

	if (pillType != "21" && pillType != "28") {
		reply.text("Scusa, non ho capito.");
		askStepPillType(msg, reply);
		return;
	}

	msg.context.stepPillType = pillType;

	askStepAlarmTime(msg, reply);
}

function askStepAlarmTime(msg, reply) {
	msg.context.isAsking = ConfigState.ALARM_TIME;
	reply.text("A che ora vuoi che ti avvisi? Ad esempio: 20:00");
}

function stepAlarmTime(msg, reply) {
	let timeRaw = msg.text;
	let time = moment(timeRaw, ['h:m a', 'H:m']);

	if (!time.isValid()) {
		reply.text("Non riesco a capire l'orario. Puoi scriverlo di nuovo?");
		return;
	}

	msg.context.isAsking = ConfigState.COMPLETED;
	msg.context.stepAlarmTime = time;

	setScheduling(msg, reply);
}

function setScheduling(msg, reply) {
	let startingDateMoment = msg.context.stepDate;
	let startingDate = startingDateMoment.utc().format("DDD");

	let timeMoment = msg.context.stepAlarmTime;
	let time = timeMoment.utc().format("HH:mm");

	let pillType = msg.context.stepPillType;

	let sched;
	if (pillType == "28") {
		sched = later.parse.recur().after(startingDate).dayOfYear().on(time).time();
	}
	else if (pillType == "21") {
		sched = later.parse.recur().after(startingDate).dayOfYear().on(time).time().except().every(4).weekOfYear();
	}
	else {
		reply.text("Ho avuto dei problemi mentre impostavo il timer. Puoi ripetere ripartendo da /start?");
		return;
	}

	var occurrences = later.schedule(sched).next(100);
	var schedText = "";
	for (var i = 0; i < 100; i++) {
		schedText += occurrences[i] + '\n';
	}

	reply.text("Ti avviserò questi giorni: \n" + schedText);

	let timer = later.setInterval(function () {
		reply.text("Ehi, prendi la pillola!");
	}, sched);

	let id = msg.chat.id;

	let oldTimer = timers[id];
	if (oldPinger) oldTimer.clear();

	timers[id] = timer;
}

bot.command("stop", function (msg, reply, next) {
	console.log("Stopped from: ", msg.from.id);
	msg.context.isAsking = ConfigState.NONE;

	let id = msg.chat.id;

	let oldTimer = timers[id];
	if (!oldPinger) {
		reply.text("Non hai nessun allarme da fermare!");
		return;
	}

	oldTimer.clear();
	reply.text("Ho fermato l'allarme. Puoi ripetere la configurazione con /start.");
	reply.text("Ciao, a presto!");
});

/* GET home page. */
router.get('/', function (req, res, next) {
	res.render('index', { title: 'Bibot' });
});

module.exports = router;
<|endoftext|>


<commit_before>"use strict";

var path = {
  from: {
    protos: {
      css: './css/*.css'
    },
    src: {
      html: './src/*.html',
      css: './src/css/*.css',
      img: './src/img/*.*',
      js: './src/js/*.*'
    },
    examples: {
      html: './examples/*.html',
      css: './examples/css/*.css',
      img: './examples/img/*.*',
      js: './npm /js/*.*'
    }
  },
  dest: {
    protos_build: {
      css: './src/css'
    },
    protos_examples: {
      css: './examples/css'
    },
    src: {
      html: './build/',
      css: './build/css',
      img: './build/img',
      js: './build/js'
    },
    examples: {
      html: './build-examples/',
      css: './build-examples/css',
      img: './build-examples/img',
      js:'./build-examples/js'
    },
  }
}

var gulp = require('gulp');
var rigger = require('gulp-rigger');
var watch = require('gulp-watch');

gulp.task('protos', function () {
    gulp.src(path.from.protos.css)
        .pipe(gulp.dest(path.dest.protos_build.css))
});

gulp.task('protos-example', function () {
    gulp.src(path.from.protos.css)
        .pipe(gulp.dest(path.dest.protos_examples.css))
});

gulp.task('html', function () {
    gulp.src(path.from.src.html)
        .pipe(rigger())
        .pipe(gulp.dest(path.dest.src.html))
});

gulp.task('css', function () {
    gulp.src(path.from.src.css)
        .pipe(gulp.dest(path.dest.src.css))
});

gulp.task('img', function () {
    gulp.src(path.from.src.img)
        .pipe(gulp.dest(path.dest.src.img))
});

gulp.task('js', function () {
    gulp.src(path.from.src.js)
        .pipe(gulp.dest(path.dest.src.js))
});

gulp.task('html-example', function () {
    gulp.src(path.from.examples.html)
        .pipe(rigger())
        .pipe(gulp.dest(path.dest.examples.html))
});

gulp.task('css-example', function () {
    gulp.src(path.from.examples.css)
        .pipe(gulp.dest(path.dest.examples.css))
});

gulp.task('img-example', function () {
    gulp.src(path.from.examples.img)
        .pipe(gulp.dest(path.dest.examples.img))
});

gulp.task('js-example', function () {
    gulp.src(path.from.examples.js)
        .pipe(gulp.dest(path.from.examples.js))
});

gulp.task('watch', function() {
  watch('./css/*.css', function(event, cb) {
    gulp.start('protos');
  });
  watch('./css/*.css', function(event, cb) {
    gulp.start('protos-example');
  });
  watch('./src/**/*.html', function(event, cb) {
    gulp.start('html');
  });
  watch('./src/css/*.css', function(event, cb) {
    gulp.start('css');
  });
  watch('./src/img/*.*', function(event, cb) {
    gulp.start('img');
  });
  watch('./src/js/*.*', function(event, cb) {
    gulp.start('js');
  });
  watch('./examples/**/*.html', function(event, cb) {
    gulp.start('html-example');
  });
  watch('./examples/*.css', function(event, cb) {
    gulp.start('css-example');
  });
  watch('./examples/img/*.*', function(event, cb) {
    gulp.start('img-example');
  });
  watch('./examples/js/*.*', function(event, cb) {
    gulp.start('js-example');
  });
});

gulp.task('default', ['watch', 'protos', 'protos-example', 'html', 'css', 'js', 'img', 'html-example', 'css-example', 'img-example', 'js-example',]);
<commit_msg>fix errors in paths<commit_after>"use strict";

var path = {
  from: {
    protos: {
      css: './css/*.css'
    },
    src: {
      html: './src/*.html',
      css: './src/css/*.css',
      img: './src/img/*.*',
      js: './src/js/*.*'
    },
    examples: {
      html: './examples/*.html',
      css: './examples/css/*.css',
      img: './examples/img/*.*',
      js: './examples/js/*.*'
    }
  },
  dest: {
    protos_build: {
      css: './src/css'
    },
    protos_examples: {
      css: './examples/css'
    },
    src: {
      html: './build/',
      css: './build/css',
      img: './build/img',
      js: './build/js'
    },
    examples: {
      html: './build-examples/',
      css: './build-examples/css',
      img: './build-examples/img',
      js:'./build-examples/js'
    },
  }
}

var gulp = require('gulp');
var rigger = require('gulp-rigger');
var watch = require('gulp-watch');

gulp.task('protos', function () {
    gulp.src(path.from.protos.css)
        .pipe(gulp.dest(path.dest.protos_build.css))
});

gulp.task('protos-example', function () {
    gulp.src(path.from.protos.css)
        .pipe(gulp.dest(path.dest.protos_examples.css))
});

gulp.task('html', function () {
    gulp.src(path.from.src.html)
        .pipe(rigger())
        .pipe(gulp.dest(path.dest.src.html))
});

gulp.task('css', function () {
    gulp.src(path.from.src.css)
        .pipe(gulp.dest(path.dest.src.css))
});

gulp.task('img', function () {
    gulp.src(path.from.src.img)
        .pipe(gulp.dest(path.dest.src.img))
});

gulp.task('js', function () {
    gulp.src(path.from.src.js)
        .pipe(gulp.dest(path.dest.src.js))
});

gulp.task('html-example', function () {
    gulp.src(path.from.examples.html)
        .pipe(rigger())
        .pipe(gulp.dest(path.dest.examples.html))
});

gulp.task('css-example', function () {
    gulp.src(path.from.examples.css)
        .pipe(gulp.dest(path.dest.examples.css))
});

gulp.task('img-example', function () {
    gulp.src(path.from.examples.img)
        .pipe(gulp.dest(path.dest.examples.img))
});

gulp.task('js-example', function () {
    gulp.src(path.from.examples.js)
        .pipe(gulp.dest(path.dest.examples.js))
});

gulp.task('watch', function() {
  watch('./css/*.css', function(event, cb) {
    gulp.start('protos');
  });
  watch('./css/*.css', function(event, cb) {
    gulp.start('protos-example');
  });
  watch('./src/**/*.html', function(event, cb) {
    gulp.start('html');
  });
  watch('./src/css/*.css', function(event, cb) {
    gulp.start('css');
  });
  watch('./src/img/*.*', function(event, cb) {
    gulp.start('img');
  });
  watch('./src/js/*.*', function(event, cb) {
    gulp.start('js');
  });
  watch('./examples/**/*.html', function(event, cb) {
    gulp.start('html-example');
  });
  watch('./examples/css/*.css', function(event, cb) {
    gulp.start('css-example');
  });
  watch('./examples/img/*.*', function(event, cb) {
    gulp.start('img-example');
  });
  watch('./examples/js/*.*', function(event, cb) {
    gulp.start('js-example');
  });
});

gulp.task('default', ['watch', 'protos', 'protos-example', 'html', 'css', 'js', 'img', 'html-example', 'css-example', 'img-example', 'js-example',]);
<|endoftext|>


<commit_before>
/*
 * GET home page.
 */

exports.index = function(req, res){
<<<<<<< HEAD
	res.render('index', { title: 'Locate It', login: req.session.login });
};

exports.api = function(req, res){
	res.render('api', {title : 'Locate It API'});
}
=======
  res.render('index', { title: 'Locate It', login: req.session.login });
};
>>>>>>> branch 'master' of https://github.com/letcheck/locateit.git
<commit_msg>solving the solving<commit_after>
/*
 * GET home page.
 */

exports.index = function(req, res){

	res.render('index', { title: 'Locate It', login: req.session.login });
};

exports.api = function(req, res){
	res.render('api', {title : 'Locate It API'});
};

<|endoftext|>


<commit_before>var gulp = require('gulp'),
    nodemon = require('gulp-nodemon'),
    jshint = require('gulp-jshint'),
    sass = require('gulp-sass'),
    sourcemaps = require('gulp-sourcemaps');

//define the default task and add the watch task to it
gulp.task('default', ['watch']);

gulp.task('start', function () {
  nodemon({
    script: './bin/www'
  //, ext: 'js html'
  , env: { 'NODE_ENV': 'development' }
  })
})

gulp.task('lint', function () {
  gulp.src('./**/*.js')
    .pipe(jshint())
})

gulp.task('develop', function () {
  nodemon({ script: './bin/www'
          //, ext: 'html js'
          , ignore: ['ignored.js']
          , tasks: ['lint'] })
    .on('restart', function () {
      console.log('restarted!')
    })
})

gulp.task('build-css', function() {
  return gulp.src('public/css/**/*.css')
    .pipe(sourcemaps.init()) // Process the original sources
      .pipe(sass())
    .pipe(sourcemaps.write()) // Add the map to modified source.
    .pipe(gulp.dest('public/css/stylesheets'));
});

//configure which files to watch and what tasks to use on file changes
gulp.task('watch', function() {
  gulp.watch('./**/*.js', ['jshint']);
  gulp.watch('public/css/**/*.css', ['build-css']);
});<commit_msg>Delete gulpfile.js<commit_after><|endoftext|>


<commit_before>var _path = require('path');
var _fs = require('fs');

var walk = require('walkdir');

var util = require('../util');

var toSystem = util.toSystem;
var toRelative = util.toRelative;
var hashit = util.hashit;

var config = require('../config');
var streamer = require('../vlc');
var hdhomerun = require('../hdhomerun');

var collections = [];
Object.keys(config.collections).forEach(function (collection) {
  collections.push({
    name: collection,
    path: config.collections[collection],
  });
});

var valid_extensions = {};
Object.keys(config.formats).forEach(function (type) {
  config.formats[type].forEach(function (ext) {
    valid_extensions[ext] = type;
  });
});

var hdhomeruns = [];
Object.keys(config.hdhomerun).forEach(function(device) {
  var hd = config.hdhomerun[device];
  hdhomeruns.push({
    id: hd.id,
    name: device,
    tuners: Object.keys(hd.tuners),
  });
});

exports.index = function(req, res){
  res.render('index', {
    title: 'NimbusMeus',
    collections: collections,
    hdhomerun: hdhomeruns,
  });
};

var shouldIgnore = function (path) {
  var ignore = false;
  var reg, pat, m;
  for (m in config.ignore) {
    pat = config.ignore[m];
    reg = new RegExp(pat, "i");
    ignore = reg.test(_path.basename(path));
    if (ignore) {
      break;
    }
  }
  return ignore;
}

exports.listing = function (req, res) {
  var spath = toSystem(req.params[0]);
  var title = 'Listing for: ';
  if (spath.path) {
    var files = [], dirs = [];
    title += spath.original;

    walk(spath.path, { no_recurse: true })
    .on('file', function (path, stat) {
      if (!shouldIgnore(path)) {
        files.push({
          name: _path.basename(path),
          path: path, //toRelative(path, spath),
          spath: spath,
        });
      }
    })
    .on('directory', function (path, stat) {
      if (!shouldIgnore(path)) {
        dirs.push({
          name: _path.basename(path),
          path: toRelative(path, spath),
        });
      }
    })
    .on('error', function (err) {
      console.log(arguments);
    })
    .on('end', function () {
      var compare = function (a, b) {
        var ret = a.name.toLowerCase() > b.name.toLowerCase() ? 1 : -1;
        return ret;
      }

      streamer.processFiles(files, function (err, files) {
        files = files.sort(compare);
        dirs = dirs.sort(compare);

        res.render('listing', {
          title: title,
          dirs: dirs,
          files: files,
        });
      });
    });
  } else {
    console.log('no spath', spath);
    res.render('listing', { title: title, dirs: [], files: [], root: '' });
  }
};

exports.view = function (req, res) {
  var title = 'Viewing: ';
  var sessid = req.session.hash;
  var waiting = true;
  var montior, ext, timeoud, timerid, canRender;

  var spath = toSystem(req.params[0]);

  if (!sessid) {
    req.session.hash = hashit(req.session.id);
    sessid = req.session.hash;
  }

  if (spath.path) {
    title += _path.basename(spath.path);

    ext = _path.extname(spath.path).toLowerCase().replace('.', '');
    ext = valid_extensions[ext];

    streamer.play({
      sess: sessid,
      mrl: spath.path,
      host: req.headers.host,
      settings: req.session.settings,
      type: ext,
    }, function (err, monitor) {
      streamer.waitStream(monitor.path, 15000, function (err) {
        if (err) {
          res.render('error', {
            title: 'Streaming Error',
            error: err,
          });
          return;
        }

        res.render('view', {
          title: title,
          path: monitor.url,
        });
      });
    });;
  }
};

exports.stream = function (req, res) {
  var path = req.params[0];
  var sessid = req.session.hash;

  streamer.touch(sessid);

  var file = _path.normalize(_path.join(
    util.tmpdir(), sessid, _path.join.apply(null, path.split('/')
  )));

  res.sendfile(file);
};

exports.settings = function (req, res) {
  var settings = req.session.settings;

  if (!req.session.settings) {
    settings = req.session.settings = {};
  }

  res.render('settings', {
    title: 'Settings',
    refer: req.header('Referrer'),
    bandwidth: settings.bandwidth ? settings.bandwidth : 0,
    fps: settings.fps ? settings.fps : 0,
    width: settings.width ? settings.width : 0,
    height: settings.height ? settings.height : 0,
  });
};

exports.settings_save = function (req, res) {
  var settings = req.session.settings;

  if (!settings) {
    settings = req.session.settings = {};
  }

  settings.bandwidth = req.body.bandwidth;
  settings.fps = req.body.fps;
  settings.width = req.body.width;
  settings.height = req.body.height;

  req.session.save();

  if (req.body.refer) {
    res.redirect(req.body.refer);
  } else {
    res.render('settings', {
      title: 'Settings',
      refer: req.header('Referrer'),
      bandwidth: settings.bandwidth ? settings.bandwidth : 0,
      fps: settings.fps ? settings.fps : 0,
      width: settings.width ? settings.width : 0,
      height: settings.height ? settings.height : 0,
    });
  }
};

exports.tv = function (req, res) {
  var tunerfile = config.hdhomerun[req.params.device].tuners[req.params.tuner];

  hdhomerun.parse(tunerfile, function (err, channels) {
    if (err) {
      res.render('error', {
        title: 'TV Parse Error',
        error: err,
      });
      return;
    }

    res.render('tv', {
      title: 'TV Channels',
      channels: channels,
      device: config.hdhomerun[req.params.device].id,
      tuner: req.params.tuner,
    });
  });
};

exports.tv_view = function (req, res) {
  var sessid = req.session.hash;

  if (!sessid) {
    req.session.hash = hashit(req.session.id);
    sessid = req.session.hash;
  }

  hdhomerun.tune(req.params, function (err) {
    if (err) {
      res.render('error', {
        title: 'TV View Error',
        error: err,
      });
      return;
    }

    streamer.play({
      sess: sessid,
      mrl:  'udp://@:5000',
      type: 'video',
      live: true,
      host: req.headers.host,
      settings: req.session.settings,
    }, function (err, monitor) {

      hdhomerun.stream(req.params, function (err) {
        if (err) {
          res.render('error', {
            title: 'HDHomeRun Stream Error',
            error: err,
          });
          return;
        }
        streamer.waitStream(monitor.path, 30000, function (err) {
          if (err) {
            res.render('error', {
              title: 'HDHomeRun Stream Wait Error',
              error: err,
            });
            return;
          }
          res.render('view', {
            title: 'Live TV',
            path: monitor.url,
          });
        });
      });
    });
  });
};
<commit_msg>handle sessions without settings<commit_after>var _path = require('path');
var _fs = require('fs');

var walk = require('walkdir');

var util = require('../util');

var toSystem = util.toSystem;
var toRelative = util.toRelative;
var hashit = util.hashit;

var config = require('../config');
var streamer = require('../vlc');
var hdhomerun = require('../hdhomerun');

var collections = [];
Object.keys(config.collections).forEach(function (collection) {
  collections.push({
    name: collection,
    path: config.collections[collection],
  });
});

var valid_extensions = {};
Object.keys(config.formats).forEach(function (type) {
  config.formats[type].forEach(function (ext) {
    valid_extensions[ext] = type;
  });
});

var hdhomeruns = [];
Object.keys(config.hdhomerun).forEach(function(device) {
  var hd = config.hdhomerun[device];
  hdhomeruns.push({
    id: hd.id,
    name: device,
    tuners: Object.keys(hd.tuners),
  });
});

exports.index = function(req, res){
  res.render('index', {
    title: 'NimbusMeus',
    collections: collections,
    hdhomerun: hdhomeruns,
  });
};

var shouldIgnore = function (path) {
  var ignore = false;
  var reg, pat, m;
  for (m in config.ignore) {
    pat = config.ignore[m];
    reg = new RegExp(pat, "i");
    ignore = reg.test(_path.basename(path));
    if (ignore) {
      break;
    }
  }
  return ignore;
}

exports.listing = function (req, res) {
  var spath = toSystem(req.params[0]);
  var title = 'Listing for: ';
  if (spath.path) {
    var files = [], dirs = [];
    title += spath.original;

    walk(spath.path, { no_recurse: true })
    .on('file', function (path, stat) {
      if (!shouldIgnore(path)) {
        files.push({
          name: _path.basename(path),
          path: path, //toRelative(path, spath),
          spath: spath,
        });
      }
    })
    .on('directory', function (path, stat) {
      if (!shouldIgnore(path)) {
        dirs.push({
          name: _path.basename(path),
          path: toRelative(path, spath),
        });
      }
    })
    .on('error', function (err) {
      console.log(arguments);
    })
    .on('end', function () {
      var compare = function (a, b) {
        var ret = a.name.toLowerCase() > b.name.toLowerCase() ? 1 : -1;
        return ret;
      }

      streamer.processFiles(files, function (err, files) {
        files = files.sort(compare);
        dirs = dirs.sort(compare);

        res.render('listing', {
          title: title,
          dirs: dirs,
          files: files,
        });
      });
    });
  } else {
    console.log('no spath', spath);
    res.render('listing', { title: title, dirs: [], files: [], root: '' });
  }
};

exports.view = function (req, res) {
  var title = 'Viewing: ';
  var sessid = req.session.hash;
  var waiting = true;
  var montior, ext, timeoud, timerid, canRender;

  var spath = toSystem(req.params[0]);

  if (!sessid) {
    req.session.hash = hashit(req.session.id);
    sessid = req.session.hash;
  }

  if (spath.path) {
    title += _path.basename(spath.path);

    ext = _path.extname(spath.path).toLowerCase().replace('.', '');
    ext = valid_extensions[ext];

    streamer.play({
      sess: sessid,
      mrl: spath.path,
      host: req.headers.host,
      settings: req.session.settings || {},
      type: ext,
    }, function (err, monitor) {
      streamer.waitStream(monitor.path, 15000, function (err) {
        if (err) {
          res.render('error', {
            title: 'Streaming Error',
            error: err,
          });
          return;
        }

        res.render('view', {
          title: title,
          path: monitor.url,
        });
      });
    });;
  }
};

exports.stream = function (req, res) {
  var path = req.params[0];
  var sessid = req.session.hash;

  streamer.touch(sessid);

  var file = _path.normalize(_path.join(
    util.tmpdir(), sessid, _path.join.apply(null, path.split('/')
  )));

  res.sendfile(file);
};

exports.settings = function (req, res) {
  var settings = req.session.settings || {};

  res.render('settings', {
    title: 'Settings',
    refer: req.header('Referrer'),
    bandwidth: settings.bandwidth ? settings.bandwidth : 0,
    fps: settings.fps ? settings.fps : 0,
    width: settings.width ? settings.width : 0,
    height: settings.height ? settings.height : 0,
  });
};

exports.settings_save = function (req, res) {
  var settings = req.session.settings || {};

  settings.bandwidth = req.body.bandwidth;
  settings.fps = req.body.fps;
  settings.width = req.body.width;
  settings.height = req.body.height;

  req.session.save();

  if (req.body.refer) {
    res.redirect(req.body.refer);
  } else {
    res.render('settings', {
      title: 'Settings',
      refer: req.header('Referrer'),
      bandwidth: settings.bandwidth ? settings.bandwidth : 0,
      fps: settings.fps ? settings.fps : 0,
      width: settings.width ? settings.width : 0,
      height: settings.height ? settings.height : 0,
    });
  }
};

exports.tv = function (req, res) {
  var tunerfile = config.hdhomerun[req.params.device].tuners[req.params.tuner];

  hdhomerun.parse(tunerfile, function (err, channels) {
    if (err) {
      res.render('error', {
        title: 'TV Parse Error',
        error: err,
      });
      return;
    }

    res.render('tv', {
      title: 'TV Channels',
      channels: channels,
      device: config.hdhomerun[req.params.device].id,
      tuner: req.params.tuner,
    });
  });
};

exports.tv_view = function (req, res) {
  var sessid = req.session.hash;

  if (!sessid) {
    req.session.hash = hashit(req.session.id);
    sessid = req.session.hash;
  }

  hdhomerun.tune(req.params, function (err) {
    if (err) {
      res.render('error', {
        title: 'TV View Error',
        error: err,
      });
      return;
    }

    streamer.play({
      sess: sessid,
      mrl:  'udp://@:5000',
      type: 'video',
      live: true,
      host: req.headers.host,
      settings: req.session.settings || {},
    }, function (err, monitor) {

      hdhomerun.stream(req.params, function (err) {
        if (err) {
          res.render('error', {
            title: 'HDHomeRun Stream Error',
            error: err,
          });
          return;
        }
        streamer.waitStream(monitor.path, 30000, function (err) {
          if (err) {
            res.render('error', {
              title: 'HDHomeRun Stream Wait Error',
              error: err,
            });
            return;
          }
          res.render('view', {
            title: 'Live TV',
            path: monitor.url,
          });
        });
      });
    });
  });
};
<|endoftext|>


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

'use strict';

// Include Gulp & Tools We'll Use
var gulp = require('gulp');
var fs = require('fs');
var $ = require('gulp-load-plugins')();
var del = require('del');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
var pagespeed = require('psi');
var reload = browserSync.reload;

var AUTOPREFIXER_BROWSERS = [
  'ie >= 9',
  'ie_mob >= 10',
  'ff >= 30',
  'chrome >= 34',
  'safari >= 7',
  'opera >= 12',
  'ios >= 7',
  'android >= 4.4',
  'bb >= 10'
];

var plumberOption = {
      errorHandler: function(err) {
        console.log(err);
        this.emit('end');
      }
    };

var loadJSON = function(path) {
  var data = fs.readFileSync(path, 'utf8');
  return JSON.parse(data);
};

var RplusConfig = loadJSON('./app/manifest.webapp');

gulp.task('filter-webfont-chars', function() {
  var rawHtml = fs.readFileSync('./app/index.html', 'utf8');
  var webFontChars = encodeURIComponent(rawHtml.match(/say\-hi[^>]+?>([^<]+)/).pop().replace(/\s/g, ''));

  var outputPath = ['.tmp', 'dist'];
  var changeWebFont = function($folder) {
    gulp.src([
        $folder + '/index.html'
      ])
      .pipe($.replace(/family=Courgette.*?"/, 'family=Courgette&text=' + webFontChars + '"'))
      .pipe(gulp.dest($folder));
  };

  for (var i = 0; i < outputPath.length; i++) {
    changeWebFont(outputPath[i]);
  }
});

gulp.task('update-version', function() {
  console.log(RplusConfig.version);
  var regPattern = /data-version="[\.\d]+?"/;
  var outputPath = ['.tmp', 'dist'];
  var changeVersion = function($folder) {
    gulp.src([
        $folder + '/index.html',
        $folder + '/offline.appcache'
      ])
      .pipe($.replace(regPattern, 'data-version="' + RplusConfig.version + '"'))
      .pipe(gulp.dest($folder));
  };

  for (var i = 0; i < outputPath.length; i++) {
    changeVersion(outputPath[i]);
  }
});

// JS task
gulp.task('js', function() {
  return gulp.src('app/scripts/*.js')
    .pipe($.plumber(plumberOption))
    .pipe($.jscs())
    .on('error', $.notify.onError(function() {
      return 'jscs error';
    }))
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.notify(function(file) {
      // ref: https://gist.github.com/rudijs/9148283
      if (!file.jshint.success) {
        return 'jshint error';
      }
    }))
    .pipe($.util.env.type !== 'dev' ? $.uglify({preserveComments: 'some'}) : $.util.noop())
    .pipe(gulp.dest('.tmp/scripts'))
    .pipe(gulp.dest('dist/scripts'))
    .pipe($.size({title: 'images'}));
});

// Optimize Images
gulp.task('images', function() {
  return gulp.src(['app/images/**/*', '!app/images/inject-svg/icons/*.svg'])
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('.tmp/images'))
    .pipe(gulp.dest('dist/images'))
    .pipe($.size({title: 'images'}));
});

// Copy All Files At The Root Level (app)
gulp.task('copy', function() {
  return gulp.src([
    'app/*',
    '!app/*.html',
    'node_modules/apache-server-configs/dist/.htaccess'
  ], {
    dot: true
  }).pipe(gulp.dest('.tmp'))
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'copy'}));
});

// Compile and Automatically Prefix Stylesheets
gulp.task('libsass', function() {
  // For best performance, don't add Sass partials to `gulp.src`
  return gulp.src([
      'app/styles/main.scss'
    ])
    .pipe($.plumber(plumberOption))
    .pipe($.changed('libsass', {extension: '.scss'}))
    .pipe($.sass())
    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
    // Concatenate And Minify Styles
    .pipe($.if('*.css', $.csso()))
    .pipe(gulp.dest('.tmp/styles'))
    .pipe(gulp.dest('dist/styles'))
    .pipe($.size({title: 'styles'}));
});

// Scan Your HTML For Assets & Optimize Them
gulp.task('html', function() {
  var assets = $.useref.assets({searchPath: '{.tmp,app}'});

  return gulp.src('app/**/*.html')
    .pipe($.plumber(plumberOption))
    .pipe(assets)
    // Concatenate And Minify JavaScript
    .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
    // Remove Any Unused CSS
    // Note: If not using the Style Guide, you can delete it from
    // the next line to only include styles your project uses.
    .pipe($.if('*.css', $.uncss({
      html: [
        'app/index.html'
      ],
      // CSS Selectors for UnCSS to ignore
      ignore: [
        /avatar/,
        /.contact-link/,
        /#card/,
        /.navdrawer-container.open/,
        /.app-bar.open/
      ]
    })))
    // Concatenate And Minify Styles
    // In case you are still using useref build blocks
    .pipe($.if('*.css', $.csso()))
    .pipe(assets.restore())
    .pipe($.useref())
    // Output Files: to .tmp folder
    .pipe(gulp.dest('.tmp'))
    .pipe($.size({title: 'html'}));
});

gulp.task('inject-html', ['html'], function() {
  return gulp.src('.tmp/**/*.html')
    .pipe($.plumber(plumberOption))
    // inject css into html inline style
    .pipe($.inject(gulp.src(['.tmp/styles/*.css', '.tmp/scripts/init.js']), {
      starttag: '<!-- inject:head:{{ext}} -->',
      transform: function(filePath, file) {
        // return file contents as string
        var _ext;
        var tags;
        _ext = filePath.split('.').reverse()[0];

        tags = ('js' === _ext ? 'script' : 'style');

        return '<' + tags + '>' + file.contents.toString('utf8') + '</' + tags + '>';
      }
    }))
    // Minify Any HTML
    .pipe($.if('*.html', $.minifyHtml({quotes: true})))
    // Output Files: to dist folder
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'inject-html'}));
});

gulp.task('svgicons', function() {
  function transformSvg ($svg, done) {
    $svg.attr('style', 'display:none');
    done(null, $svg);
  }

  gulp.src('./app/images/inject-svg/icons/*.svg')
    .pipe($.imagemin({
      svgoPlugins: [{removeViewBox: false}]
    }))
    .pipe($.svgstore({
       prefix: 'inject-icon-',
       transformSvg: transformSvg
    }))
    .pipe(gulp.dest('.tmp/images/inject-svg/'))
    .pipe(gulp.dest('dist/images/inject-svg/'));

  $.iconify({
      src: './app/images/inject-svg/icons/*.svg',
      pngOutput: './app/images/inject-svg/png',
      scssOutput: './.tmp/images/inject-svg/scss',
      cssOutput:  './app/images/inject-svg/css',
      styleTemplate: './app/styles/_icon_gen.scss.mustache'
  });
});

// Clean Output Directory
gulp.task('clean', del.bind(null, ['.tmp', 'dist']));

// Watch Files For Changes & Reload
gulp.task('serve', function() {
  browserSync({
    browser: 'google-chrome',
    notify: false,
    ghostMode: {
      clicks: false,
      forms: false,
      scroll: true
    },

    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    server: ['.tmp', 'app']
  });

  gulp.watch(['app/**/*.html'], ['html', reload]);
  gulp.watch(['app/styles/**/*.{scss,css}'], ['libsass', reload]);
  gulp.watch(['app/scripts/**/*.js'], ['js', reload]);
  gulp.watch(['app/images/**/*'], reload);
});

// Build and serve the output from the dist build
gulp.task('serve:dist', function() {
  browserSync({
    browser: 'google-chrome',
    notify: false,
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    port: 8000,
    server: 'dist'
  });

  gulp.watch(['app/**/*.html'], ['inject-html', reload]);
  gulp.watch(['app/styles/**/*.{scss,css}'], ['libsass', 'inject-html', reload]);
  gulp.watch(['app/scripts/**/*.js'], ['js', 'inject-html', reload]);
  gulp.watch(['app/images/**/*'], reload);
});

// deploy dist folder to github branch gh-pages
gulp.task('deploy', function() {
  return gulp.src('./dist/**/*')
    .pipe($.ghPages());
});

// Build Production Files, the Default Task
gulp.task('default', ['clean'], function(cb) {
  runSequence('svgicons', 'libsass', 'js', 'inject-html', ['images', 'copy'], 'update-version', 'filter-webfont-chars', cb);
});

// Run PageSpeed Insights
// Update `url` below to the public URL for your site
gulp.task('pagespeed', pagespeed.bind(null, {
  // By default, we use the PageSpeed Insights
  // free (no API key) tier. You can use a Google
  // Developer API key if you have one. See
  // http://goo.gl/RkN0vE for info key: 'YOUR_API_KEY'
  url: 'http://rplus.github.io/resume/',
  strategy: 'mobile'
}));

// Load custom tasks from the `tasks` directory
try { require('require-dir')('tasks'); } catch (err) {}
<commit_msg>fix coding style<commit_after>/**
 *
 *  Web Starter Kit
 *  Copyright 2014 Google Inc. All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 *
 */

'use strict';

// Include Gulp & Tools We'll Use
var gulp = require('gulp');
var fs = require('fs');
var $ = require('gulp-load-plugins')();
var del = require('del');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
var pagespeed = require('psi');
var reload = browserSync.reload;

var AUTOPREFIXER_BROWSERS = [
  'ie >= 9',
  'ie_mob >= 10',
  'ff >= 30',
  'chrome >= 34',
  'safari >= 7',
  'opera >= 12',
  'ios >= 7',
  'android >= 4.4',
  'bb >= 10'
];

var plumberOption = {
      errorHandler: function(err) {
        console.log(err);
        this.emit('end');
      }
    };

var loadJSON = function(path) {
  var data = fs.readFileSync(path, 'utf8');
  return JSON.parse(data);
};

var RplusConfig = loadJSON('./app/manifest.webapp');

gulp.task('filter-webfont-chars', function() {
  var rawHtml = fs.readFileSync('./app/index.html', 'utf8');
  var webFontChars = encodeURIComponent(rawHtml.match(/say\-hi[^>]+?>([^<]+)/).pop().replace(/\s/g, ''));

  var outputPath = ['.tmp', 'dist'];
  var changeWebFont = function($folder) {
    gulp.src([
        $folder + '/index.html'
      ])
      .pipe($.replace(/family=Courgette.*?"/, 'family=Courgette&text=' + webFontChars + '"'))
      .pipe(gulp.dest($folder));
  };

  for (var i = 0; i < outputPath.length; i++) {
    changeWebFont(outputPath[i]);
  }
});

gulp.task('update-version', function() {
  console.log(RplusConfig.version);
  var regPattern = /data-version="[\.\d]+?"/;
  var outputPath = ['.tmp', 'dist'];
  var changeVersion = function($folder) {
    gulp.src([
        $folder + '/index.html',
        $folder + '/offline.appcache'
      ])
      .pipe($.replace(regPattern, 'data-version="' + RplusConfig.version + '"'))
      .pipe(gulp.dest($folder));
  };

  for (var i = 0; i < outputPath.length; i++) {
    changeVersion(outputPath[i]);
  }
});

// JS task
gulp.task('js', function() {
  return gulp.src('app/scripts/*.js')
    .pipe($.plumber(plumberOption))
    .pipe($.jscs())
    .on('error', $.notify.onError(function() {
      return 'jscs error';
    }))
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.notify(function(file) {
      // ref: https://gist.github.com/rudijs/9148283
      if (!file.jshint.success) {
        return 'jshint error';
      }
    }))
    .pipe($.util.env.type !== 'dev' ? $.uglify({preserveComments: 'some'}) : $.util.noop())
    .pipe(gulp.dest('.tmp/scripts'))
    .pipe(gulp.dest('dist/scripts'))
    .pipe($.size({title: 'images'}));
});

// Optimize Images
gulp.task('images', function() {
  return gulp.src(['app/images/**/*', '!app/images/inject-svg/icons/*.svg'])
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('.tmp/images'))
    .pipe(gulp.dest('dist/images'))
    .pipe($.size({title: 'images'}));
});

// Copy All Files At The Root Level (app)
gulp.task('copy', function() {
  return gulp.src([
    'app/*',
    '!app/*.html',
    'node_modules/apache-server-configs/dist/.htaccess'
  ], {
    dot: true
  }).pipe(gulp.dest('.tmp'))
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'copy'}));
});

// Compile and Automatically Prefix Stylesheets
gulp.task('libsass', function() {
  // For best performance, don't add Sass partials to `gulp.src`
  return gulp.src([
      'app/styles/main.scss'
    ])
    .pipe($.plumber(plumberOption))
    .pipe($.changed('libsass', {extension: '.scss'}))
    .pipe($.sass())
    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
    // Concatenate And Minify Styles
    .pipe($.if('*.css', $.csso()))
    .pipe(gulp.dest('.tmp/styles'))
    .pipe(gulp.dest('dist/styles'))
    .pipe($.size({title: 'styles'}));
});

// Scan Your HTML For Assets & Optimize Them
gulp.task('html', function() {
  var assets = $.useref.assets({searchPath: '{.tmp,app}'});

  return gulp.src('app/**/*.html')
    .pipe($.plumber(plumberOption))
    .pipe(assets)
    // Concatenate And Minify JavaScript
    .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
    // Remove Any Unused CSS
    // Note: If not using the Style Guide, you can delete it from
    // the next line to only include styles your project uses.
    .pipe($.if('*.css', $.uncss({
      html: [
        'app/index.html'
      ],
      // CSS Selectors for UnCSS to ignore
      ignore: [
        /avatar/,
        /.contact-link/,
        /#card/,
        /.navdrawer-container.open/,
        /.app-bar.open/
      ]
    })))
    // Concatenate And Minify Styles
    // In case you are still using useref build blocks
    .pipe($.if('*.css', $.csso()))
    .pipe(assets.restore())
    .pipe($.useref())
    // Output Files: to .tmp folder
    .pipe(gulp.dest('.tmp'))
    .pipe($.size({title: 'html'}));
});

gulp.task('inject-html', ['html'], function() {
  return gulp.src('.tmp/**/*.html')
    .pipe($.plumber(plumberOption))
    // inject css into html inline style
    .pipe($.inject(gulp.src(['.tmp/styles/*.css', '.tmp/scripts/init.js']), {
      starttag: '<!-- inject:head:{{ext}} -->',
      transform: function(filePath, file) {
        // return file contents as string
        var _ext;
        var tags;
        _ext = filePath.split('.').reverse()[0];

        tags = ('js' === _ext ? 'script' : 'style');

        return '<' + tags + '>' + file.contents.toString('utf8') + '</' + tags + '>';
      }
    }))
    // Minify Any HTML
    .pipe($.if('*.html', $.minifyHtml({quotes: true})))
    // Output Files: to dist folder
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'inject-html'}));
});

gulp.task('svgicons', function() {
  function transformSvg ($svg, done) {
    $svg.attr('style', 'display:none');
    done(null, $svg);
  }

  gulp.src('./app/images/inject-svg/icons/*.svg')
    .pipe($.imagemin({
      svgoPlugins: [{removeViewBox: false}]
    }))
    .pipe($.svgstore({
      prefix: 'inject-icon-',
      transformSvg: transformSvg
    }))
    .pipe(gulp.dest('.tmp/images/inject-svg/'))
    .pipe(gulp.dest('dist/images/inject-svg/'));

  $.iconify({
    src: './app/images/inject-svg/icons/*.svg',
    pngOutput: './app/images/inject-svg/png',
    scssOutput: './.tmp/images/inject-svg/scss',
    cssOutput:  './app/images/inject-svg/css',
    styleTemplate: './app/styles/_icon_gen.scss.mustache'
  });
});

// Clean Output Directory
gulp.task('clean', del.bind(null, ['.tmp', 'dist']));

// Watch Files For Changes & Reload
gulp.task('serve', function() {
  browserSync({
    browser: 'google-chrome',
    notify: false,
    ghostMode: {
      clicks: false,
      forms: false,
      scroll: true
    },

    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    server: ['.tmp', 'app']
  });

  gulp.watch(['app/**/*.html'], ['html', reload]);
  gulp.watch(['app/styles/**/*.{scss,css}'], ['libsass', reload]);
  gulp.watch(['app/scripts/**/*.js'], ['js', reload]);
  gulp.watch(['app/images/**/*'], reload);
});

// Build and serve the output from the dist build
gulp.task('serve:dist', function() {
  browserSync({
    browser: 'google-chrome',
    notify: false,
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    port: 8000,
    server: 'dist'
  });

  gulp.watch(['app/**/*.html'], ['inject-html', reload]);
  gulp.watch(['app/styles/**/*.{scss,css}'], ['libsass', 'inject-html', reload]);
  gulp.watch(['app/scripts/**/*.js'], ['js', 'inject-html', reload]);
  gulp.watch(['app/images/**/*'], reload);
});

// deploy dist folder to github branch gh-pages
gulp.task('deploy', function() {
  return gulp.src('./dist/**/*')
    .pipe($.ghPages());
});

// Build Production Files, the Default Task
gulp.task('default', ['clean'], function(cb) {
  runSequence('svgicons',
              'libsass',
              'js',
              'inject-html',
              ['images', 'copy'],
              'update-version',
              'filter-webfont-chars',
              cb);
});

// Run PageSpeed Insights
// Update `url` below to the public URL for your site
gulp.task('pagespeed', pagespeed.bind(null, {
  // By default, we use the PageSpeed Insights
  // free (no API key) tier. You can use a Google
  // Developer API key if you have one. See
  // http://goo.gl/RkN0vE for info key: 'YOUR_API_KEY'
  url: 'http://rplus.github.io/resume/',
  strategy: 'mobile'
}));

// Load custom tasks from the `tasks` directory
try { require('require-dir')('tasks'); } catch (err) {}
<|endoftext|>


<commit_before>var
  expressValidator = require('express-validator'),
  lp = require('../lib/letterpress'),
  set = require('../lib/set');

// some extra filters for our processing
expressValidator.Filter.prototype.toLowerCase = function() {
  this.modify(this.str.toLowerCase());
  return this.str;
};

expressValidator.Filter.prototype.lettersOnly = function() {
  this.modify(this.str.replace(/[^a-z]/g, ''));
  return this.str;
};

expressValidator.Validator.prototype.isSubsetOf = function(supersetStr) {
  if (!set.isSubset(set.getCanonical(supersetStr), set.getCanonical(this.str))) {
    this.error(this.msg || this.str + ' is not a subset of ' + supersetStr);
  }
  return this;
};

/**
 * Actually serve requests
 */
exports.api = function(req, res, next) {
  req.assert('board', 'Board must exist').notEmpty();
  if (typeof req.param('board') !== 'undefined' && req.param('board') !== '') {
    req.sanitize('board').lettersOnly().toLowerCase();
    req.assert('board', 'Board must have ' + lp.BOARD_SIZE + ' letters').len(lp.BOARD_SIZE, lp.BOARD_SIZE);
  }

  if (typeof req.param('minFrequency') !== 'undefined') {
    req.sanitize('minFrequency').toInt();
    req.assert('minFrequency', 'Frequency must be between 0 and ' + lp.MAX_FREQUENCY)
      .min(0)
      .max(lp.MAX_FREQUENCY);
  }

  var errors = req.validationErrors() || [];
  if (errors.length) {
    // how do we get the default error-renderer to do the right thing?
    throw new Error( errors );
  } else {
    var board = req.param('board'); // guaranteed to exist
    var minFrequency = typeof req.param('minFrequency') !== 'undefined' ? req.param('minFrequency') : lp.DEFAULT_FREQUENCY;
    var moves = lp.getMovesForBoard(board, minFrequency);
    res.send(moves);
  }
}

exports.index = function(req, res, next) {
  var params = {
    'title': 'letterpress cheat! with API',
    'errors': [],
    'minFrequency': 16,
    'desired': '',
    'words': []
  };
  res.render('index', params);
}

<commit_msg>send only 10 words<commit_after>var
  expressValidator = require('express-validator'),
  lp = require('../lib/letterpress'),
  set = require('../lib/set');

// some extra filters for our processing
expressValidator.Filter.prototype.toLowerCase = function() {
  this.modify(this.str.toLowerCase());
  return this.str;
};

expressValidator.Filter.prototype.lettersOnly = function() {
  this.modify(this.str.replace(/[^a-z]/g, ''));
  return this.str;
};

expressValidator.Validator.prototype.isSubsetOf = function(supersetStr) {
  if (!set.isSubset(set.getCanonical(supersetStr), set.getCanonical(this.str))) {
    this.error(this.msg || this.str + ' is not a subset of ' + supersetStr);
  }
  return this;
};

/**
 * Actually serve requests
 */
exports.api = function(req, res, next) {
  req.assert('board', 'Board must exist').notEmpty();
  if (typeof req.param('board') !== 'undefined' && req.param('board') !== '') {
    req.sanitize('board').lettersOnly().toLowerCase();
    req.assert('board', 'Board must have ' + lp.BOARD_SIZE + ' letters').len(lp.BOARD_SIZE, lp.BOARD_SIZE);
  }

  if (typeof req.param('minFrequency') !== 'undefined') {
    req.sanitize('minFrequency').toInt();
    req.assert('minFrequency', 'Frequency must be between 0 and ' + lp.MAX_FREQUENCY)
      .min(0)
      .max(lp.MAX_FREQUENCY);
  }

  var errors = req.validationErrors() || [];
  if (errors.length) {
    // how do we get the default error-renderer to do the right thing?
    throw new Error( errors );
  } else {
    var board = req.param('board'); // guaranteed to exist
    var minFrequency = typeof req.param('minFrequency') !== 'undefined' ? req.param('minFrequency') : lp.DEFAULT_FREQUENCY;
    var moves = lp.getMovesForBoard(board, minFrequency);
    res.send(moves.slice(0, 9));
  }
}

exports.index = function(req, res, next) {
  var params = {
    'title': 'letterpress cheat! with API',
    'errors': [],
    'minFrequency': 16,
    'desired': '',
    'words': []
  };
  res.render('index', params);
}

<|endoftext|>


<commit_before>// ==[ Dependencies ]======================================
var gulp = require('gulp'),
    _ = require('underscore'),
    less = require('gulp-less'),
    path = require('path'),
    template = require('gulp-template'),
    jshint = require('gulp-jshint'),
    uglify = require('gulp-uglify'),
    imagemin = require('gulp-imagemin'),
    rename = require('gulp-rename'),
    concat = require('gulp-concat'),
    notify = require('gulp-notify'),
    cache = require('gulp-cache'),
    sourcemaps = require('gulp-sourcemaps'),
    vulcanize = require('gulp-vulcanize'),
    webserver = require('gulp-webserver'),
    config = require('./app/config.json'),
    pkg = require('./package.json'),
    yargs = require('yargs'),
    gutil = require('gulp-util'),
    plumber = require('gulp-plumber'),
    del = require('del');
// ========================================================

// ==[ Error Handling ]====================================
// `gulp --fatal=error` determines what kind of errors should be fatal
// see for more info: http://www.artandlogic.com/blog/2014/05/error-handling-in-gulp/

var fatalLevel = yargs.argv.fatal,
    ERROR_LEVELS = ['error', 'warning'];

function isFatal(level) {
  return ERROR_LEVELS.indexOf(level) <= ERROR_LEVELS.indexOf(fatalLevel || 'error');
}

function handleError(level, error) {
  notify.onError({
    title: "Gulp",
    subtitle: level + "!",
    message: "Error: <%= error.message %>",
    sound: "Sosumi"
  })(error);

  gutil.log(error.message);
  gutil.log(error.stack);

  if (isFatal(level)) {
    process.exit(1);
  }

  this.emit('end');
}

function onError(error) {
  handleError.call(this, 'error', error);
}
function onWarning(error) {
  handleError.call(this, 'warning', error);
}

// ========================================================

//TODO: pull out jshint task from js task
//TODO: common piped task for multi-env configuration?
//TODO: test livereload
//TODO: setup basic angular app
//TODO: task for angular templates [gulp-html2tpl](https://www.npmjs.org/package/gulp-html2tpl)
//TODO: alternate lib for angular templates [gulp-jst-concat](https://www.npmjs.org/package/gulp-jst-concat)
//TODO: errors task
//TODO: polymer js/platform.js
//TODO: google analytics config
//TODO: gulp rss?
//TODO: sitemap?
//TODO: asset fingerprinting?
//TODO: jshintrc - look at https://gist.github.com/connor/1597131
//TODO: add 404.html and other templates

//gulp-notify defaults for completed tasks
var notifyConf = {
  title: "Gulp",
  subtitle: "Finished",
  sound: "Tink" // refer to OSX Sound Preferences
}

//merge env config into common config
var node_env = process.env.NODE_ENV || 'development',
    conf = _.extend(
        _.pick(pkg, 'title', 'description'),
        config['common'],
        config[node_env]);

gulp.task('html', function () {
  return gulp.src('app/pages/**/*.html')
      .pipe(plumber({errorHandler: onError}))
      .pipe(template(conf))
      .pipe(gulp.dest('dist'))
      .pipe(notify(_.extend(notifyConf,{message: 'HTML task complete'})));
});

gulp.task('js', function () {
  return gulp.src('app/js/**/*.js')
      .pipe(plumber({errorHandler: onError}))
      .pipe(sourcemaps.init())
      .pipe(template(conf))
      .pipe(jshint('.jshintrc'))
      .pipe(jshint.reporter('default'))
      .pipe(concat('app.js'))
      .pipe(gulp.dest('dist/js'))
      .pipe(rename({suffix: '.min'}))
      .pipe(uglify())
      .pipe(sourcemaps.write())
      .pipe(gulp.dest('dist/js'))
      .pipe(notify(_.extend(notifyConf,{message: 'JS task complete'})));
});

gulp.task('less', function () {
  return gulp.src('./app/css/**/*.less')
      .pipe(sourcemaps.init())
      .pipe(less({
        paths: [path.join(__dirname, 'less', 'includes')]
      }))
      .pipe(sourcemaps.write())
      .pipe(gulp.dest('./dist/css'))
      .on('error', onError)
      .pipe(notify(_.extend(notifyConf,{message: 'LESS task complete'})));
});

gulp.task('img', function () {
  return gulp.src('app/img/**/*')
      .pipe(imagemin({optimizationLevel: 3, progressive: true, interlaced: true}))
      .pipe(gulp.dest('dist/img'))
      .pipe(notify(_.extend(notifyConf,{message: 'Img task complete'})));
});

gulp.task('vulcanize', function () {
  return gulp.src('app/components/build.html')
      .pipe(vulcanize({dest: 'dist/components'}))
      .pipe(gulp.dest('dist/components'))
      .on('error', onError)
      .pipe(notify(_.extend(notifyConf,{message: 'Vulcanize task complete'})));
});

gulp.task('clean', function (cb) {
  del(['dist/css', 'dist/js', 'dist/img', 'dist/components', 'dist/index.html'], cb)
});

gulp.task('default', ['clean'], function () {
  gulp.start('html', 'less', 'js', 'img', 'vulcanize');
});

gulp.task('watch', function () {
  fatalLevel = fatalLevel || 'off';
  gulp.watch('app/config.json', ['js', 'html']);
  gulp.watch('app/css/**/*.less', ['less']);
  gulp.watch('app/js/**/*.js', ['js']);
  gulp.watch('app/img/**/*', ['img']);
  gulp.watch('app/pages/**/*.html', ['html']);
  gulp.watch('app/components/build.html', ['vulcanize']);
});

gulp.task('webserver', function () {
  gulp.src('dist')
      .pipe(webserver({
        livereload: true,
        directoryListing: {
          enable: true,
          path: 'dist'
        },
        open: true
      }));
});<commit_msg>* added a separate jshint task<commit_after>// ==[ Dependencies ]======================================
var gulp = require('gulp'),
    _ = require('underscore'),
    less = require('gulp-less'),
    path = require('path'),
    template = require('gulp-template'),
    jshint = require('gulp-jshint'),
    uglify = require('gulp-uglify'),
    imagemin = require('gulp-imagemin'),
    rename = require('gulp-rename'),
    concat = require('gulp-concat'),
    notify = require('gulp-notify'),
    cache = require('gulp-cache'),
    sourcemaps = require('gulp-sourcemaps'),
    vulcanize = require('gulp-vulcanize'),
    webserver = require('gulp-webserver'),
    config = require('./app/config.json'),
    pkg = require('./package.json'),
    yargs = require('yargs'),
    gutil = require('gulp-util'),
    plumber = require('gulp-plumber'),
    del = require('del');
// ========================================================

// ==[ Error Handling ]====================================
// `gulp --fatal=error` determines what kind of errors should be fatal
// see for more info: http://www.artandlogic.com/blog/2014/05/error-handling-in-gulp/

var fatalLevel = yargs.argv.fatal,
    ERROR_LEVELS = ['error', 'warning'];

function isFatal(level) {
  return ERROR_LEVELS.indexOf(level) <= ERROR_LEVELS.indexOf(fatalLevel || 'error');
}

function handleError(level, error) {
  notify.onError({
    title: "Gulp",
    subtitle: level + "!",
    message: "Error: <%= error.message %>",
    sound: "Sosumi"
  })(error);

  gutil.log(error.message);
  gutil.log(error.stack);

  if (isFatal(level)) {
    process.exit(1);
  }

  this.emit('end');
}

function onError(error) {
  handleError.call(this, 'error', error);
}
function onWarning(error) {
  handleError.call(this, 'warning', error);
}

// ========================================================

//TODO: pull out jshint task from js task
//TODO: common piped task for multi-env configuration?
//TODO: test livereload
//TODO: setup basic angular app
//TODO: task for angular templates [gulp-html2tpl](https://www.npmjs.org/package/gulp-html2tpl)
//TODO: alternate lib for angular templates [gulp-jst-concat](https://www.npmjs.org/package/gulp-jst-concat)
//TODO: errors task
//TODO: polymer js/platform.js
//TODO: google analytics config
//TODO: gulp rss?
//TODO: sitemap?
//TODO: asset fingerprinting?
//TODO: jshintrc - look at https://gist.github.com/connor/1597131
//TODO: add 404.html and other templates

//gulp-notify defaults for completed tasks
var notifyConf = {
  title: "Gulp",
  subtitle: "Finished",
  sound: "Tink" // refer to OSX Sound Preferences
}

//merge env config into common config
var node_env = process.env.NODE_ENV || 'development',
    conf = _.extend(
        _.pick(pkg, 'title', 'description'),
        config['common'],
        config[node_env]);

gulp.task('html', function () {
  return gulp.src('app/pages/**/*.html')
      .pipe(plumber({errorHandler: onError}))
      .pipe(template(conf))
      .pipe(gulp.dest('dist'))
      .pipe(notify(_.extend(notifyConf,{message: 'HTML task complete'})));
});

//TODO: update jshint & js tasks so that one streams into the other, for efficiency
gulp.task('jshint', function () {
  return gulp.src('app/js/**/*.js')
      .pipe(plumber({errorHandler: onWarning}))
      .pipe(template(conf))
      .pipe(jshint('.jshintrc'))
      .pipe(jshint.reporter('default'))
      .pipe(notify(_.extend(notifyConf,{message: 'JSHint task complete'})));
});

gulp.task('js', function () {
  return gulp.src('app/js/**/*.js')
      .pipe(plumber({errorHandler: onError}))
      .pipe(sourcemaps.init())
      .pipe(template(conf))
      .pipe(concat('app.js'))
      .pipe(gulp.dest('dist/js'))
      .pipe(rename({suffix: '.min'}))
      .pipe(uglify())
      .pipe(sourcemaps.write())
      .pipe(gulp.dest('dist/js'))
      .pipe(notify(_.extend(notifyConf,{message: 'JS task complete'})));
});

gulp.task('less', function () {
  return gulp.src('./app/css/**/*.less')
      .pipe(plumber({errorHandler: onError}))
      .pipe(sourcemaps.init())
      .pipe(less({
        paths: [path.join(__dirname, 'less', 'includes')]
      }))
      .pipe(sourcemaps.write())
      .pipe(gulp.dest('./dist/css'))
      .pipe(notify(_.extend(notifyConf,{message: 'LESS task complete'})));
});

gulp.task('img', function () {
  return gulp.src('app/img/**/*')
      .pipe(plumber({errorHandler: onError}))
      .pipe(imagemin({optimizationLevel: 3, progressive: true, interlaced: true}))
      .pipe(gulp.dest('dist/img'))
      .pipe(notify(_.extend(notifyConf,{message: 'Img task complete'})));
});

gulp.task('vulcanize', function () {
  return gulp.src('app/components/build.html')
      .pipe(plumber({errorHandler: onError}))
      .pipe(vulcanize({dest: 'dist/components'}))
      .pipe(gulp.dest('dist/components'))
      .pipe(notify(_.extend(notifyConf,{message: 'Vulcanize task complete'})));
});

gulp.task('clean', function (cb) {
  del(['dist/css', 'dist/js', 'dist/img', 'dist/components', 'dist/index.html'], cb)
});

gulp.task('default', ['clean'], function () {
  gulp.start('html', 'less', 'jshint', 'js', 'img', 'vulcanize');
});

gulp.task('watch', function () {
  fatalLevel = fatalLevel || 'off';
  gulp.watch('app/config.json', ['js', 'html']);
  gulp.watch('app/css/**/*.less', ['less']);
  gulp.watch('app/js/**/*.js', ['jshint', 'js']);
  gulp.watch('app/img/**/*', ['img']);
  gulp.watch('app/pages/**/*.html', ['html']);
  gulp.watch('app/components/build.html', ['vulcanize']);
});

gulp.task('webserver', function () {
  gulp.src('dist')
      .pipe(webserver({
        livereload: true,
        directoryListing: {
          enable: true,
          path: 'dist'
        },
        open: true
      }));
});<|endoftext|>


<commit_before>'use strict';

// nitty gritty //
var express = require('express');
var braintree = require('braintree');
var router = express.Router(); // eslint-disable-line new-cap
var gateway = require('../lib/gateway');

var TRANSACTION_SUCCESS_STATUSES = [
  braintree.Transaction.Status.Authorizing,
  braintree.Transaction.Status.Authorized,
  braintree.Transaction.Status.Settled,
  braintree.Transaction.Status.Settling,
  braintree.Transaction.Status.SettlementConfirmed,
  braintree.Transaction.Status.SettlementPending,
  braintree.Transaction.Status.SubmittedForSettlement
];

function formatErrors(errors) {
  var formattedErrors = '';

  for (var i in errors) { // eslint-disable-line no-inner-declarations, vars-on-top
    if (errors.hasOwnProperty(i)) {
      formattedErrors += 'Error: ' + errors[i].code + ': ' + errors[i].message + '\n';
    }
  }
  return formattedErrors;
}

function createResultObject(transaction) {
  var result;
  var status = transaction.status;

  if (TRANSACTION_SUCCESS_STATUSES.indexOf(status) !== -1) {
    result = {
      header: 'Sweet Success!',
      icon: 'success',
      message: 'Your test transaction has been successfully processed. See the Braintree API response and try again.'
    };
  } else {
    result = {
      header: 'Transaction Failed',
      icon: 'fail',
      message: 'Your test transaction has a status of ' + status + '. See the Braintree API response and try again.'
    };
  }

  return result;
}

router.get('/', function (req, res) {
  res.redirect('/checkouts/new');
});

router.get('/checkouts/new', function (req, res) {
  gateway.clientToken.generate({}, function (err, response) {
    res.render('checkouts/new', {clientToken: response.clientToken, messages: req.flash('error')});
  });
});

router.get('/checkouts/:id', function (req, res) {
  var result;
  var transactionId = req.params.id;

  gateway.transaction.find(transactionId, function (err, transaction) {
    result = createResultObject(transaction);
    res.render('checkouts/show', {transaction: transaction, result: result});
  });
});

router.post('/checkouts', function (req, res) {
  var transactionErrors;
  var amount = req.body.amount; // In production you should not take amounts directly from clients
  var nonce = req.body.payment_method_nonce;
  var cardholderName = req.body.cardholderName;
  var startDate = new Date(Date.UTC(2016, 8, 6, 0, 0, 0));

  gateway.customer.create({
  paymentMethodNonce: nonce,
  firstName: "Carina",
  lastName: "Stevens"
  }, function (err, result) {
    if (result.success) {
      var token = result.customer.paymentMethods[0].token;
        gateway.subscription.create({
          paymentMethodToken: token,
          planId: "four_month_membership_id",
          firstBillingDate: startDate
        }, function (err, result) {
          result.success;
        });
       res.redirect('/');
    } else {
      // transactionErrors = result.errors.deepErrors();
      // req.flash('error', {msg: formatErrors(transactionErrors)});
      res.redirect('checkouts/new');
    }
  });

  // gateway.transaction.sale({
  //   amount: amount,
  //   paymentMethodNonce: nonce
  // }, function (err, result) {
  //   if (result.success || result.transaction) {
  //     res.redirect('checkouts/' + result.transaction.id);
  //   } else {
  //     transactionErrors = result.errors.deepErrors();
  //     req.flash('error', {msg: formatErrors(transactionErrors)});
  //     res.redirect('checkouts/new');
  //   }
  // });
});

module.exports = router;
<commit_msg>Update index.js<commit_after>'use strict';

// nitty gritty //
var express = require('express');
var braintree = require('braintree');
var router = express.Router(); // eslint-disable-line new-cap
var gateway = require('../lib/gateway');

var TRANSACTION_SUCCESS_STATUSES = [
  braintree.Transaction.Status.Authorizing,
  braintree.Transaction.Status.Authorized,
  braintree.Transaction.Status.Settled,
  braintree.Transaction.Status.Settling,
  braintree.Transaction.Status.SettlementConfirmed,
  braintree.Transaction.Status.SettlementPending,
  braintree.Transaction.Status.SubmittedForSettlement
];

function formatErrors(errors) {
  var formattedErrors = '';

  for (var i in errors) { // eslint-disable-line no-inner-declarations, vars-on-top
    if (errors.hasOwnProperty(i)) {
      formattedErrors += 'Error: ' + errors[i].code + ': ' + errors[i].message + '\n';
    }
  }
  return formattedErrors;
}

function createResultObject(transaction) {
  var result;
  var status = transaction.status;

  if (TRANSACTION_SUCCESS_STATUSES.indexOf(status) !== -1) {
    result = {
      header: 'Sweet Success!',
      icon: 'success',
      message: 'Your test transaction has been successfully processed. See the Braintree API response and try again.'
    };
  } else {
    result = {
      header: 'Transaction Failed',
      icon: 'fail',
      message: 'Your test transaction has a status of ' + status + '. See the Braintree API response and try again.'
    };
  }

  return result;
}

router.get('/', function (req, res) {
  res.redirect('/checkouts/new');
});

router.get('/checkouts/new', function (req, res) {
  gateway.clientToken.generate({}, function (err, response) {
    res.render('checkouts/new', {clientToken: response.clientToken, messages: req.flash('error')});
  });
});

router.get('/checkouts/:id', function (req, res) {
  var result;
  var transactionId = req.params.id;

  gateway.transaction.find(transactionId, function (err, transaction) {
    result = createResultObject(transaction);
    res.render('checkouts/show', {transaction: transaction, result: result});
  });
});

router.post('/checkouts', function (req, res) {
  var transactionErrors;
  var amount = req.body.amount; // In production you should not take amounts directly from clients
  var nonce = req.body.payment_method_nonce;
  var cardholderName = req.body.cardholderName;
  var startDate = new Date(Date.UTC(2016, 8, 6, 0, 0, 0));

  gateway.customer.create({
  paymentMethodNonce: nonce,
  firstName: "Cecilia",
  lastName: "Ramirez",
  customFields: {
    childfirstname: "Isabella",
    childlastname: "Ramirez",
    childage: "8",
    initialcourse: "Introduction to Scratch"
  }
  }, function (err, result) {
    if (result.success) {
      var token = result.customer.paymentMethods[0].token;
        gateway.subscription.create({
          paymentMethodToken: token,
          planId: "four_month_membership_id",
          firstBillingDate: startDate
        }, function (err, result) {
          result.success;
        });
       res.redirect('/');
    } else {
      // transactionErrors = result.errors.deepErrors();
      // req.flash('error', {msg: formatErrors(transactionErrors)});
      res.redirect('checkouts/new');
    }
  });

  // gateway.transaction.sale({
  //   amount: amount,
  //   paymentMethodNonce: nonce
  // }, function (err, result) {
  //   if (result.success || result.transaction) {
  //     res.redirect('checkouts/' + result.transaction.id);
  //   } else {
  //     transactionErrors = result.errors.deepErrors();
  //     req.flash('error', {msg: formatErrors(transactionErrors)});
  //     res.redirect('checkouts/new');
  //   }
  // });
});

module.exports = router;
<|endoftext|>