<commit_before>/**
 * Gulp File : studio90srls
 * Author    : dmike16
 * Email     : cipmiky@gmail.com
 * Version   : 3.0
 *
 */
//
// NodeJS dependencies
const gulp = require('gulp');
const gutil = require('gulp-util');
const header = require('gulp-header');
const csso = require('gulp-csso');
const uglify = require('gulp-uglify');
const sass = require('gulp-sass');
const pump = require('pump');
const os = require('os');
const fse = require('fs-extra');
const del = require('del');
const vinyl_paths = require('vinyl-paths');
const pkg = require('./package.json');
const sep = require('path').sep;
const broswerSync = require('browser-sync').create();
const broswerify = require('browserify');
const source = require('vinyl-source-stream');
const sourceMaps = require('gulp-sourcemaps');
const tsify = require('tsify');
const factorBundle = require('factor-bundle');
const watchify = require('watchify');
// Array of string containg all the task created
let phony = [];
// Type of build PRODACTION or SNAPSHOT
const SNAP = 'SNAPSHOT';
const PROD = 'PRODACTION';
// Parse the input argumnets
const args = _agumentsParse(gutil.env);
// Header banner
const BANNER = ['/**',
  ' * <%= pkg.name %> - <%= pkg.description %>',
  ' * @version v<%= pkg.version %>',
  ' * @license <%= pkg.license %>',
  ' * @link https://github.com/dmike16/agenzia90-WepPage.git',
  '**/'
].join('\n');
// Define project glob src
const gjs_min = ['src/assets/script/*.js'];
const gcss = ['src/assets/css/**/*.css'];
const gscss = ['src/app/mdl_studio90srls.scss'];
const gEntrify = ['src/main.ts', 'src/app/app.ts'];
const gts = ['src/main.ts', 'src/boot/*.ts','src/app/**/*.ts'];
const gfonts = ['src/assets/css/**/fonts/*'];
const gimages = ['src/assets/images/**/*.{svg,png,jpg,ico}'];
const ghtml = ['src/*.html'];
const g_to_install = [].concat(gimages, gfonts, gjs_min, gcss, ghtml);
const dist = 'dist';
//broswerify option
const optionify = {
  entries: ['src/main.ts','src/app/app.ts'],
  debug: true,
};

gulp.task('install', ['dist'], (cb) => {
  gutil.log('BUILD TYPE :', args.type);
  gutil.log('INSTALL in :', args.installDir);
  fse.copy(dist,args.installDir,cb);
});

gulp.task('dist',['js','sass']);

gulp.task('static-dist',(cb)=>{
  pump([
      gulp.src(g_to_install, {
        base: './src'
      }),
      gulp.dest(dist)
    ],
    cb);
});

gulp.task('sass',['static-dist'], (cb) => {
  _sassTranspiler(cb, gscss);
});

gulp.task('js',['static-dist'],(cb)=>{
  _broswerifyTs(cb,gts);
});

gulp.task('clean', () => {
  return new Promise((resolve, reject) => {
    gutil.log('Clean', args.installDir, '......');

    let vp = vinyl_paths();
    let g_to_clean = args.installDir + sep + '*';

    gulp.src(g_to_clean, {
        dot: true
      })
      .pipe(vp)
      .on('finish', () => {
        del(vp.paths, {
          force: true
        }).then(resolve).catch(reject);
      })
      .on('error', (err) => {
        reject(err);
      });
  });
});

gulp.task('clobber', ['clean'], () => {
  return new Promise((resolve, reject) => {
    gutil.log('Clobber', args.installDir, '......');
    fse.rmdir(args.installDir, (err) => {
      if (err) {
        reject(err);
      } else {
        resolve();
      }
    });
  });
});

gulp.task('broswersync', ['static-dist'],(cb) => {
  let params = {
    server: {
      baseDir: dist
    },
    ui: false,
    open: false,
    port: 4200
  };
  try {
    let ssl = require('./ssl.location.json');
    params.https = {
      key: ssl.key,
      cert: ssl.cert
    };
  } catch (e) {
    gutil.log('Fallback to http server:');
  }
  broswerSync.watch(gscss, (event, file) => {
    _sassTranspiler((err) => {
      if (err) {
        gutil.log(gutil.colors.red(err.message));
      }
    }, file);
  });
  broswerSync.watch('./src/index.html', (event, file) => {
    broswerSync.reload(file);
  });
  broswerSync.watch(gts, (event, file) => {
    if(event === 'add' && !optionify.entries.includes(file))return;
    _broswerifyTs((err) => {
      if (err) {
        gutil.log(gutil.colors.red(err.message));
      }
    }, file);
  });
  broswerSync.init(params);
});

gulp.task('default', () => {
  let data = {
    pkg: pkg,
    file: 'PLACEHOLDER'
  };
  gutil.log(gutil.template(BANNER, data));
});

/**
 * Parse the commnad line argumnets.
 *
 * @private
 * @param       {Object} genv Gulp env object
 * @return      {Object}      Object containg the parsed arguments.
 */
function _agumentsParse(genv) {
  let _prefix = genv.prefix || os.homedir() + sep + 'Sites';
  let _type = genv.type || SNAP;
  let _baseDirName = genv.basename || 'studio90srls';
  let _installDir = _prefix + sep + _baseDirName;

  return {
    prefix: _prefix,
    type: _type,
    basename: _baseDirName,
    installDir: _installDir
  };
}
/**
 * Parse scss files
 * @private
 */
function _sassTranspiler(cb, file) {
  gutil.log('PARSING SCSS FILE: ',file);
  pump([
    gulp.src(file),
    sass({
      outputStyle: (PROD === args.type ? 'compressed' : 'nested')
    }),
    gulp.dest(`${dist}/assets/css`),
    (PROD === args.type) ? gutil.noop() : broswerSync.stream()
  ], cb);
}

function _broswerifyTs(cb, file) {
  gutil.log('PARSING TS FILE: ',file);

  pump([broswerify(optionify).plugin(tsify)
    .plugin(factorBundle,{o:[`${dist}/main.js`,`${dist}/assets/script/app.js`]}).bundle(),
      source('./common.js'),
      gulp.dest(dist),
      (PROD === args.type) ? gutil.noop() : broswerSync.stream()
    ],
    cb);
}
<commit_msg>[MOD] remove unused task<commit_after>/**
 * Gulp File : studio90srls
 * Author    : dmike16
 * Email     : cipmiky@gmail.com
 * Version   : 3.0
 *
 */
//
// NodeJS dependencies
const gulp = require('gulp');
const gutil = require('gulp-util');
const header = require('gulp-header');
const csso = require('gulp-csso');
const uglify = require('gulp-uglify');
const sass = require('gulp-sass');
const pump = require('pump');
const os = require('os');
const fse = require('fs-extra');
const del = require('del');
const vinyl_paths = require('vinyl-paths');
const pkg = require('./package.json');
const sep = require('path').sep;
const broswerSync = require('browser-sync').create();
const broswerify = require('browserify');
const source = require('vinyl-source-stream');
const sourceMaps = require('gulp-sourcemaps');
const tsify = require('tsify');
const factorBundle = require('factor-bundle');
const watchify = require('watchify');
// Array of string containg all the task created
let phony = [];
// Type of build PRODACTION or SNAPSHOT
const SNAP = 'SNAPSHOT';
const PROD = 'PRODACTION';
// Parse the input argumnets
const args = _agumentsParse(gutil.env);
// Header banner
const BANNER = ['/**',
  ' * <%= pkg.name %> - <%= pkg.description %>',
  ' * @version v<%= pkg.version %>',
  ' * @license <%= pkg.license %>',
  ' * @link https://github.com/dmike16/agenzia90-WepPage.git',
  '**/'
].join('\n');
// Define project glob src
const gjs_min = ['src/assets/script/*.js'];
const gcss = ['src/assets/css/**/*.css'];
const gscss = ['src/app/mdl_studio90srls.scss'];
const gEntrify = ['src/main.ts', 'src/app/app.ts'];
const gts = ['src/main.ts', 'src/boot/*.ts','src/app/**/*.ts'];
const gfonts = ['src/assets/css/**/fonts/*'];
const gimages = ['src/assets/images/**/*.{svg,png,jpg,ico}'];
const ghtml = ['src/*.html'];
const g_to_install = [].concat(gimages, gfonts, gjs_min, gcss, ghtml);
const dist = 'dist';
//broswerify option
const optionify = {
  entries: ['src/main.ts','src/app/app.ts'],
  debug: true,
};

gulp.task('install', ['js','sass'], (cb) => {
  gutil.log('BUILD TYPE :', args.type);
  gutil.log('INSTALL in :', args.installDir);
  fse.copy(dist,args.installDir,cb);
});

gulp.task('static-dist',(cb)=>{
  pump([
      gulp.src(g_to_install, {
        base: './src'
      }),
      gulp.dest(dist)
    ],
    cb);
});

gulp.task('sass',['static-dist'], (cb) => {
  _sassTranspiler(cb, gscss);
});

gulp.task('js',['static-dist'],(cb)=>{
  _broswerifyTs(cb,gts);
});

gulp.task('clean', () => {
  return new Promise((resolve, reject) => {
    gutil.log('Clean', args.installDir, '......');

    let vp = vinyl_paths();
    let g_to_clean = args.installDir + sep + '*';

    gulp.src(g_to_clean, {
        dot: true
      })
      .pipe(vp)
      .on('finish', () => {
        del(vp.paths, {
          force: true
        }).then(resolve).catch(reject);
      })
      .on('error', (err) => {
        reject(err);
      });
  });
});

gulp.task('clobber', ['clean'], () => {
  return new Promise((resolve, reject) => {
    gutil.log('Clobber', args.installDir, '......');
    fse.rmdir(args.installDir, (err) => {
      if (err) {
        reject(err);
      } else {
        resolve();
      }
    });
  });
});

gulp.task('broswersync', ['static-dist'],(cb) => {
  let params = {
    server: {
      baseDir: dist
    },
    ui: false,
    open: false,
    port: 4200
  };
  try {
    let ssl = require('./ssl.location.json');
    params.https = {
      key: ssl.key,
      cert: ssl.cert
    };
  } catch (e) {
    gutil.log('Fallback to http server:');
  }
  broswerSync.watch(gscss, (event, file) => {
    _sassTranspiler((err) => {
      if (err) {
        gutil.log(gutil.colors.red(err.message));
      }
    }, file);
  });
  broswerSync.watch('./src/index.html', (event, file) => {
    broswerSync.reload(file);
  });
  broswerSync.watch(gts, (event, file) => {
    if(event === 'add' && !optionify.entries.includes(file))return;
    _broswerifyTs((err) => {
      if (err) {
        gutil.log(gutil.colors.red(err.message));
      }
    }, file);
  });
  broswerSync.init(params);
});

gulp.task('default', () => {
  let data = {
    pkg: pkg,
    file: 'PLACEHOLDER'
  };
  gutil.log(gutil.template(BANNER, data));
});

/**
 * Parse the commnad line argumnets.
 *
 * @private
 * @param       {Object} genv Gulp env object
 * @return      {Object}      Object containg the parsed arguments.
 */
function _agumentsParse(genv) {
  let _prefix = genv.prefix || os.homedir() + sep + 'Sites';
  let _type = genv.type || SNAP;
  let _baseDirName = genv.basename || 'studio90srls';
  let _installDir = _prefix + sep + _baseDirName;

  return {
    prefix: _prefix,
    type: _type,
    basename: _baseDirName,
    installDir: _installDir
  };
}
/**
 * Parse scss files
 * @private
 */
function _sassTranspiler(cb, file) {
  gutil.log('PARSING SCSS FILE: ',file);
  pump([
    gulp.src(file),
    sass({
      outputStyle: (PROD === args.type ? 'compressed' : 'nested')
    }),
    gulp.dest(`${dist}/assets/css`),
    (PROD === args.type) ? gutil.noop() : broswerSync.stream()
  ], cb);
}

function _broswerifyTs(cb, file) {
  gutil.log('PARSING TS FILE: ',file);

  pump([broswerify(optionify).plugin(tsify)
    .plugin(factorBundle,{o:[`${dist}/main.js`,`${dist}/assets/script/app.js`]}).bundle(),
      source('./common.js'),
      gulp.dest(dist),
      (PROD === args.type) ? gutil.noop() : broswerSync.stream()
    ],
    cb);
}
<|endoftext|>


<commit_before>var gulp = require('gulp'),
  concat = require('gulp-concat'),
  rename = require('gulp-rename'),
  cleanCss = require('gulp-clean-css'),
  prefixer = require('gulp-auto-prefixer'),
  uglify = require('gulp-uglify'),
  resize = require('gulp-image-resize');

gulp.task('styles', function() {});

gulp.task('scripts', function() {});

gulp.task('images', function() {});
<commit_msg>Adding task for styles and js.<commit_after>var gulp = require('gulp'),
  concat = require('gulp-concat'),
  rename = require('gulp-rename'),
  cleanCss = require('gulp-clean-css'),
  prefixer = require('gulp-autoprefixer'),
  uglify = require('gulp-uglify'),
  resize = require('gulp-image-resize');

// TODO: include source maps.

gulp.task('styles', function() {
  gulp.src('resources/styles/*.css')
    .pipe(concat())
    .pipe(prefixer({
      browsers: ['last 2 versions'],
      cascade: false
    }))
    .pipe(cleanCss())
    .pipe(rename('main.min.css'))
    .pipe(gulp.dest('build/'));
});

gulp.task('scripts', function() {
  gulp.src('js/*.js')
    .pipe(concat())
    .pipe(uglify())
    .pipe(rename('main.min.js'))
    .pipe(gulp.dest('build/'));
});

gulp.task('images', function() {});
<|endoftext|>


<commit_before>'use strict';

var { createCanvas, Canvas } = require('canvas');
var crypto = require('crypto');
var express = require('express');

var router = express.Router();

var COLORS = [
 '#BFD2D7', '#88CBD8', '#57828B', '#1D89A0', '#1F7081', '#8DA6AE', '#6EA3AF', '#0F5564'
];

function getAccentColor(query, text) {
  if (query.hex) {
    // color is defined
    return '#' + query.hex;
  } else if (query.seed) {
    // seed is defined and will determine the color chosen
    var md5 = crypto.createHash('md5');
    md5.update('' + text);
    md5.update(query.seed);
    return COLORS[parseInt(md5.digest('hex').substr(0, 8), 16) % COLORS.length];
  } else {
    // color is chosen randomly
    return COLORS[Math.floor(Math.random() * COLORS.length)];
  }
}

router.get('/', function(req, res) {
  // use only the first two characters of the text
  var text = req.query.text || '?';
  text = text.trim().substr(0, 2).toUpperCase();

  var fonts = '"Proxima Nova"';
  if (text[0] > '\u2E7F') {
    // only use 1st character for CJK because of space limitations
    text = text[0];
    fonts = '"WenQuanYi Zen Hei Sharp"';
  }

  // default size to 200px and allow up to 2048px
  var size = parseInt(req.query.size) || 200;
  size = Math.max(Math.min(2048, +size), 1);

  var fontSize = Math.ceil(size * 0.5);
  var strokeWidth = Math.round(fontSize * 0.08);

  var mainColor = 'white';
  var backgroundColor = getAccentColor(req.query, text);

  var haveBorder = req.query.border === 'true';
  if (haveBorder) {
    var tempColor = mainColor;
    mainColor = backgroundColor;
    backgroundColor = tempColor;
  }

  var canvas = createCanvas(size, size);
  var ctx = canvas.getContext('2d');

  // fill the background
  if (!haveBorder) {
    ctx.fillStyle = backgroundColor;
    ctx.rect(0, 0, size, size);
    ctx.fill();
  }

  // draw the containing circle
  if (haveBorder) {
    var arcRadius = Math.floor((size - strokeWidth) * 0.5);
    var middle = Math.floor(size * 0.5);
    ctx.beginPath();
    ctx.lineWidth = strokeWidth;
    ctx.arc(middle, middle, arcRadius, 0, 2*Math.PI, true);
    ctx.strokeStyle = mainColor;
    ctx.fillStyle   = 'white';
    ctx.fill();
    ctx.stroke();
  }

  // position the text
  ctx.font = fontSize + 'px ' + fonts;
  var textSize = ctx.measureText(text);
  var xPos = Math.round((size - textSize.width) * 0.5);
  var yPos = Math.round(size * 0.667);

  ctx.fillStyle = mainColor;
  ctx.fillText(text, xPos, yPos);

  res.setHeader('content-type', 'image/png');
  if (req.query.seed) {
    res.setHeader('cache-control', 'max-age=86400');
  }

  canvas.pngStream().pipe(res);
});

module.exports = router;
<commit_msg>feat: update colors for accessibility<commit_after>'use strict';

var { createCanvas, Canvas } = require('canvas');
var crypto = require('crypto');
var express = require('express');

var router = express.Router();

var COLORS = [
 '#4A148C', '#3F51B5', '#002E3D', '#0F5BCE', '#0F5BCE', '#037BA7'
];

function getAccentColor(query, text) {
  if (query.hex) {
    // color is defined
    return '#' + query.hex;
  } else if (query.seed) {
    // seed is defined and will determine the color chosen
    var md5 = crypto.createHash('md5');
    md5.update('' + text);
    md5.update(query.seed);
    return COLORS[parseInt(md5.digest('hex').substr(0, 8), 16) % COLORS.length];
  } else {
    // color is chosen randomly
    return COLORS[Math.floor(Math.random() * COLORS.length)];
  }
}

router.get('/', function(req, res) {
  // use only the first two characters of the text
  var text = req.query.text || '?';
  text = text.trim().substr(0, 2).toUpperCase();

  var fonts = '"Proxima Nova"';
  if (text[0] > '\u2E7F') {
    // only use 1st character for CJK because of space limitations
    text = text[0];
    fonts = '"WenQuanYi Zen Hei Sharp"';
  }

  // default size to 200px and allow up to 2048px
  var size = parseInt(req.query.size) || 200;
  size = Math.max(Math.min(2048, +size), 1);

  var fontSize = Math.ceil(size * 0.5);
  var strokeWidth = Math.round(fontSize * 0.08);

  var mainColor = 'white';
  var backgroundColor = getAccentColor(req.query, text);

  var haveBorder = req.query.border === 'true';
  if (haveBorder) {
    var tempColor = mainColor;
    mainColor = backgroundColor;
    backgroundColor = tempColor;
  }

  var canvas = createCanvas(size, size);
  var ctx = canvas.getContext('2d');

  // fill the background
  if (!haveBorder) {
    ctx.fillStyle = backgroundColor;
    ctx.rect(0, 0, size, size);
    ctx.fill();
  }

  // draw the containing circle
  if (haveBorder) {
    var arcRadius = Math.floor((size - strokeWidth) * 0.5);
    var middle = Math.floor(size * 0.5);
    ctx.beginPath();
    ctx.lineWidth = strokeWidth;
    ctx.arc(middle, middle, arcRadius, 0, 2*Math.PI, true);
    ctx.strokeStyle = mainColor;
    ctx.fillStyle   = 'white';
    ctx.fill();
    ctx.stroke();
  }

  // position the text
  ctx.font = fontSize + 'px ' + fonts;
  var textSize = ctx.measureText(text);
  var xPos = Math.round((size - textSize.width) * 0.5);
  var yPos = Math.round(size * 0.667);

  ctx.fillStyle = mainColor;
  ctx.fillText(text, xPos, yPos);

  res.setHeader('content-type', 'image/png');
  if (req.query.seed) {
    res.setHeader('cache-control', 'max-age=86400');
  }

  canvas.pngStream().pipe(res);
});

module.exports = router;
<|endoftext|>


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

var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var concat = require('gulp-concat');
var clean = require('gulp-clean');
var header = require('gulp-header');
var streamify = require('gulp-streamify');
var qunit = require('gulp-qunit');
var pkg = require('./package.json');
var shell = require('gulp-shell');

var banner = ['/**',
    ' * <%= pkg.name %> - <%= pkg.description %>',
    ' * @version v<%= pkg.version %>',
    ' * @link <%= pkg.homepage %>',
    ' * @license <%= pkg.license %>',
    ' */',
].join('\n');

var filePath = {
    src: './src/*.js',
    dest: './openui5/googlemaps'
};

gulp.task('clean', function() {
    return gulp.src(filePath.dest, {
        read: false
    }).pipe(clean());
});

//TODO - all scripts tasks with one stream
gulp.task('scripts-dbg', function() {
    gulp.src(filePath.src)
        .pipe(header(banner, {
            pkg: pkg
        }))
        .pipe(rename({
            suffix: '-dbg'
        }))
        .pipe(gulp.dest(filePath.dest));
});

gulp.task('scripts-min', function() {
    gulp.src(filePath.src)
        .pipe(streamify(uglify()))
        .pipe(gulp.dest(filePath.dest))
        .pipe(concat('library-all.js'))
        .pipe(gulp.dest(filePath.dest));
});

// JSHint task
gulp.task('lint', function() {
    gulp.src(filePath.src)
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

gulp.task('watch', function() {
    gulp.watch(filePath.src, ['lint']);
});

gulp.task('test', function() {
    return gulp.src('./test/*.qunit.html')
        .pipe(qunit());
});

gulp.task('commit',
    shell.task([
        'echo start',
        'git add ./src',
        'git add ./openui5/googlemaps',
        'git add ./samples',
        'git commit -a -m \"test gulp commit\"',
        'git push master',
        'echo update gh-pages',
        'git branch -f gh-pages master',
        'git push origin gh-pages'
    ])
);

gulp.task('develop ', ['build', 'watch']);
gulp.task('build', ['scripts-dbg', 'scripts-min']);
gulp.task('cleanbuild', ['clean']);<commit_msg>test gulp commit<commit_after>var gulp = require('gulp');

var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var concat = require('gulp-concat');
var clean = require('gulp-clean');
var header = require('gulp-header');
var streamify = require('gulp-streamify');
var qunit = require('gulp-qunit');
var pkg = require('./package.json');
var shell = require('gulp-shell');

var banner = ['/**',
    ' * <%= pkg.name %> - <%= pkg.description %>',
    ' * @version v<%= pkg.version %>',
    ' * @link <%= pkg.homepage %>',
    ' * @license <%= pkg.license %>',
    ' */',
].join('\n');

var filePath = {
    src: './src/*.js',
    dest: './openui5/googlemaps'
};

gulp.task('clean', function() {
    return gulp.src(filePath.dest, {
        read: false
    }).pipe(clean());
});

//TODO - all scripts tasks with one stream
gulp.task('scripts-dbg', function() {
    gulp.src(filePath.src)
        .pipe(header(banner, {
            pkg: pkg
        }))
        .pipe(rename({
            suffix: '-dbg'
        }))
        .pipe(gulp.dest(filePath.dest));
});

gulp.task('scripts-min', function() {
    gulp.src(filePath.src)
        .pipe(streamify(uglify()))
        .pipe(gulp.dest(filePath.dest))
        .pipe(concat('library-all.js'))
        .pipe(gulp.dest(filePath.dest));
});

// JSHint task
gulp.task('lint', function() {
    gulp.src(filePath.src)
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

gulp.task('watch', function() {
    gulp.watch(filePath.src, ['lint']);
});

gulp.task('test', function() {
    return gulp.src('./test/*.qunit.html')
        .pipe(qunit());
});

gulp.task('commit',
    shell.task([
        'echo start',
        'git add ./src',
        'git add ./openui5/googlemaps',
        'git add ./samples',
        'git commit -a -m \"test gulp commit\"',
        'git push --all',
        'echo update gh-pages',
        'git branch -f gh-pages master',
        'git push origin gh-pages'
    ])
);

gulp.task('develop ', ['build', 'watch']);
gulp.task('build', ['scripts-dbg', 'scripts-min']);
gulp.task('cleanbuild', ['clean']);<|endoftext|>


<commit_before>const path = require('path');
const gulp = require('gulp');
const keva = require('keva');
const decb = require('decb');
const fs = decb(require('fs'), {
  use: ['readFile', 'writeFile']
});
const postcss = require('gulp-postcss');
const connect = require('gulp-connect');
const Handlebars = require('handlebars');
const handlebars = require('gulp-compile-handlebars');
const rename = require('gulp-rename');
const imagemin = require('gulp-imagemin');
const posthtml = require('gulp-posthtml');
const inline = require('gulp-inline');
const watch = {
  css: 'src/style/**/*.css',
  html: 'src/markup/**/*.hbs'
}
const frix = require('frix');

let app = express();
frix.render().then(() => {
  console.log(frix);
});

Handlebars.registerHelper('tree', (context, options) => {
  return '
' +tree(context, 'ul');
});

function tree(context, ...closeTags) {
  let ret = '';

  for (let [key, val] of keva(context)) {
    if(val.value) {
      ret += `<li class="link" data-value="${val.value}" data-type="${val.type}">${key}</li>`;
    } else {
      ret += `<li>${key}<ul>`;
      ret += tree(val, 'li', 'ul');
    }
  }
  ret += closeTags.map(tag => `</${tag}>`).join('');
  return ret;
}

gulp.task('html', function () {
  let data = {};
  data.pages = frix.gui.getAllPages();
  data.content = frix.gui.getContentStructure();

  let bemData = {
        elemPrefix: '__',
        modPrefix: '--',
        modDlmtr: '_'
  };

  gulp.src(watch.html)
    .pipe(posthtml([
          require('posthtml-bem')(bemData)
    ]))
    .pipe(handlebars(data, {
      ignorePartials: true
    }))
    .pipe(rename({
      extname: '.html'
    }))
    .pipe(inline({
      base: 'src/images'
    }))
    .pipe(gulp.dest('build'))
    .pipe(connect.reload());
});

gulp.task('css', () => {
  gulp.src('src/style/main.css')
    .pipe(postcss([
      require('postcss-cssnext')
    ]))
    .pipe(gulp.dest('build'))
    .pipe(connect.reload());
});

gulp.task('connect', () => {
  connect.server({
    port: 8080,
    root: 'build',
    livereload: true
  });
});

gulp.task('watch', () => {
  for (let [key, val] of keva(watch)) {
    gulp.watch(val, [key]);
  }
});

gulp.task('default', ['connect'], () => {
  gulp.start('css', 'html', 'watch');
});
<commit_msg>removed invalid express call<commit_after>const path = require('path');
const gulp = require('gulp');
const keva = require('keva');
const decb = require('decb');
const fs = decb(require('fs'), {
  use: ['readFile', 'writeFile']
});
const postcss = require('gulp-postcss');
const connect = require('gulp-connect');
const Handlebars = require('handlebars');
const handlebars = require('gulp-compile-handlebars');
const rename = require('gulp-rename');
const imagemin = require('gulp-imagemin');
const posthtml = require('gulp-posthtml');
const inline = require('gulp-inline');
const watch = {
  css: 'src/style/**/*.css',
  html: 'src/markup/**/*.hbs'
}
const frix = require('frix');

frix.render().then(() => {
  console.log(frix);
});

Handlebars.registerHelper('tree', (context, options) => {
  return '
' +tree(context, 'ul');
});

function tree(context, ...closeTags) {
  let ret = '';

  for (let [key, val] of keva(context)) {
    if(val.value) {
      ret += `<li class="link" data-value="${val.value}" data-type="${val.type}">${key}</li>`;
    } else {
      ret += `<li>${key}<ul>`;
      ret += tree(val, 'li', 'ul');
    }
  }
  ret += closeTags.map(tag => `</${tag}>`).join('');
  return ret;
}

gulp.task('html', function () {
  let data = {};
  data.pages = frix.gui.getAllPages();
  data.content = frix.gui.getContentStructure();

  let bemData = {
        elemPrefix: '__',
        modPrefix: '--',
        modDlmtr: '_'
  };

  gulp.src(watch.html)
    .pipe(posthtml([
          require('posthtml-bem')(bemData)
    ]))
    .pipe(handlebars(data, {
      ignorePartials: true
    }))
    .pipe(rename({
      extname: '.html'
    }))
    .pipe(inline({
      base: 'src/images'
    }))
    .pipe(gulp.dest('build'))
    .pipe(connect.reload());
});

gulp.task('css', () => {
  gulp.src('src/style/main.css')
    .pipe(postcss([
      require('postcss-cssnext')
    ]))
    .pipe(gulp.dest('build'))
    .pipe(connect.reload());
});

gulp.task('connect', () => {
  connect.server({
    port: 8080,
    root: 'build',
    livereload: true
  });
});

gulp.task('watch', () => {
  for (let [key, val] of keva(watch)) {
    gulp.watch(val, [key]);
  }
});

gulp.task('default', ['connect'], () => {
  gulp.start('css', 'html', 'watch');
});
<|endoftext|>


<commit_before>var gulp = require('gulp');
var rimraf = require('rimraf-promise');
var colors = require('colors');
var exec = require('child-process-promise').exec;

gulp.task('build-dist', function () {
    return rimraf('./dist').then(function (error) {
        var webpackCli = 'webpack --config webpack.config.dist.js';
        return exec(webpackCli).fail(function (error) {
            console.log(colors.red(error))
        });
    });
});<commit_msg>Making it to build an ES5 compliant lib<commit_after>var gulp = require('gulp');
var rimraf = require('rimraf-promise');
var colors = require('colors');
var exec = require('child-process-promise').exec;

gulp.task('build-dist', function () {
    return rimraf('./dist').then(function (error) {
        var webpackCli = 'webpack --config webpack.config.dist.js';
        return exec(webpackCli).fail(function (error) {
            console.log(colors.red(error))
        });
    });
});

gulp.task('build-lib', function () {
    return rimraf('./lib')
        .then(function (error) {
            var babelCli = 'babel --optional es7.objectRestSpread ./src --out-dir ./lib';
            return exec(babelCli).fail(function (error) {
                console.log(colors.red(error))
            });
        });
});<|endoftext|>


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

require('./tasks/build');
require('./tasks/sass');
require('./tasks/watch');
require('./tasks/test');

gulp.task('build', ['browserify', 'sass', 'fonts', 'assets','templates']);
gulp.task('release', ['browserify:release', 'sass', 'fonts', 'assets','templates']);
gulp.task('default', ['sass']);<commit_msg>serve<commit_after>var gulp = require('gulp');

require('./tasks/build');
require('./tasks/sass');
require('./tasks/watch');
require('./tasks/test');
require('./tasks/serve');

gulp.task('build', ['browserify', 'sass', 'fonts', 'assets','templates']);
gulp.task('release', ['browserify:release', 'sass', 'fonts', 'assets','templates']);
gulp.task('default', ['sass']);<|endoftext|>


<commit_before>'use strict';

const debug = require('debug')('Backend-Portfolio:message-router.js');

const Router = require('express').Router;
const jsonParser = require('body-parser').json();
const createError = require('http-errors');

const bearerAuth = require('../lib/bearer-auth-middleware.js');
const Message = require('../model/Message.js');

const messageRouter = module.exports = Router();

messageRouter.post('/api/message', bearerAuth, jsonParser, (req, res, next) => {
  debug('POST: /api/message');

  if(!req.body || !req.body.id) return next(createError(400, 'missing id credentials'));

  let message = new Message({
    authorId: req.body.id,
    text: req.body.text || null,
    title: req.body.title || null,
    photos: req.body.photos || null,
    comments: []
  })
  .then((message) => res.json(message))
  .catch(next);
});

messageRouter.get('/api/message/all', bearerAuth, (req, res, next) => {
  debug('GET: /api/message/all');

  Message.find({})
  .then((messages) => {
    // NOTE: maybe we can just return messages????
    console.log(messages)
    let tempArr = [];
    messages.forEach((ele) => tempArr.push(ele))
    .then(() => res.json(tempArr))
  })
  .catch(next);
});

messageRouter.get('/api/message/self', bearerAuth, (req, res, next) => {
  debug('GET: /api/message/self');

  if(!req.body || !req.body.id) return next(createError(400, 'missing authorId field'));

  Message.find({authorId: req.body.id})
  .then((messages) => {
    console.log(messages)
    let tempArr = [];
    messages.forEach((ele) => tempArr.push(ele))
    .then(() => res.json(tempArr))
  })
  .catch(next);
});

messageRouter.get('/api/message/:id', bearerAuth, (req, res, next) => {
  debug('GET: /api/message/:id');

  if(!req.params.id) return next(createError(400, 'missing user\'s request id'));

  Message.findById(req.params.id)
  .then((message) => {
    res.json(message);
  })
  .catch(next);
});

messageRouter.put('/api/message/edit/:id', bearerAuth, jsonParser, (req, res, next) => {
  debug('PUT: /api/message/edit/:id');

  if(!req.params.id) return next(createError(400, 'missing user\'s request id'));

  Message.findOne(req.params.id)
  .then((message) => {

  })
  .catch(next);
});

messageRouter.delete('/api/message/remove/:id', bearerAuth, (req, res, next) => {
  debug('DELETE: /api/message/remove/:id');

  if(!req.params.id) return next(createError(400, 'missing user\'s request id'));

  Message.findByIdAndRemove(req.params.id)
  .then(() => res.status(204).send())
  .catch(next);
});
<commit_msg>fixed formating errors<commit_after>'use strict';

const debug = require('debug')('Backend-Portfolio:message-router.js');

const Router = require('express').Router;
const jsonParser = require('body-parser').json();
const createError = require('http-errors');

const bearerAuth = require('../lib/bearer-auth-middleware.js');
const Message = require('../model/Message.js');

const messageRouter = module.exports = Router();

messageRouter.post('/api/message', bearerAuth, jsonParser, (req, res, next) => {
  debug('POST: /api/message');

  if(!req.body || !req.body.id) return next(createError(400, 'missing id credentials'));

  let message = new Message({
    authorId: req.body.id,
    text: req.body.text || null,
    title: req.body.title || null,
    photos: req.body.photos || null,
    comments: []
  })
    .then((message) => res.json(message))
    .catch(next);
});

messageRouter.get('/api/message/all', bearerAuth, (req, res, next) => {
  debug('GET: /api/message/all');

  Message.find({})
    .then((messages) => {
      // NOTE: maybe we can just return messages????
      console.log(messages);
      let tempArr = [];
      messages.forEach((ele) => tempArr.push(ele))
        .then(() => res.json(tempArr));
    })
    .catch(next);
});

messageRouter.get('/api/message/self', bearerAuth, (req, res, next) => {
  debug('GET: /api/message/self');

  if(!req.body || !req.body.id) return next(createError(400, 'missing authorId field'));

  Message.find({authorId: req.body.id})
    .then((messages) => {
      console.log(messages);
      let tempArr = [];
      messages.forEach((ele) => tempArr.push(ele))
        .then(() => res.json(tempArr));
    })
    .catch(next);
});

messageRouter.get('/api/message/:id', bearerAuth, (req, res, next) => {
  debug('GET: /api/message/:id');

  if(!req.params.id) return next(createError(400, 'missing user\'s request id'));

  Message.findById(req.params.id)
    .then((message) => {
      res.json(message);
    })
    .catch(next);
});

messageRouter.put('/api/message/edit/:id', bearerAuth, jsonParser, (req, res, next) => {
  debug('PUT: /api/message/edit/:id');

  if(!req.params.id) return next(createError(400, 'missing user\'s request id'));

  Message.findOne(req.params.id)
    .then((message) => {

    })
    .catch(next);
});

messageRouter.delete('/api/message/remove/:id', bearerAuth, (req, res, next) => {
  debug('DELETE: /api/message/remove/:id');

  if(!req.params.id) return next(createError(400, 'missing user\'s request id'));

  Message.findByIdAndRemove(req.params.id)
    .then(() => res.status(204).send())
    .catch(next);
});
<|endoftext|>


<commit_before>var mongo;

exports.setDb = function(db){
    mongo = db;
};
/*
 * GET home page.
 */
exports.index = function(req, res){
    res.writeHead(200,{'Content-Type':'text/html'});
    res.sendfile('public/index.html');
    // res.render('index', { title: 'Express' });
};

exports.api = function(req, res){
    console.log('API');
    res.writeHead(200,{'Content-Type':'text/html'});
    res.end('API: v0.0.1');
};

/**
 * API method that returns all geo data.
 * It will group by session id.
 */
 //Filters for api mongo calls.
var filters = {};
filters.find = {loc:{$exists:true},payload:{$exists:true}};
filters.keys = {loc:1,payload:1,time:1,_id:0};
exports.api.getDarkness = function(req,res){
    console.log('API: Darkness');
    mongo.data.find(filters.find,filters.keys).toArray(function(error, data){
        if(error){
            //handle error!
            throw error;
        }

        //send data.
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "X-Requested-With");
        res.send(data);
    });
};

/**
 * API method to store sample data from device.
 * After storing in mongodb, it will dispatch
 * event to notify clients.
 */
exports.api.postDarkness = function(req, res){
    console.log("POST: ");
    console.log(req.body.data);
    console.log(typeof req.body.data);
    var posted = JSON.parse( req.body.data );
    mongo.data.insert(posted, function(err, payload){
        // console.log('Inserted our content');
        //Should we ensure data integrity?!
        res.send(payload);
    });
};

/**
 * MIDDLEWARE: Ensure that we trigger
 * a 404 since the route won't be matched
 * and we handle it on handle404.
 */
exports.e404 = function(req, res, next){
    next( );
};

/**
 * MIDDLEWARE: Trigger- next- a generic
 * 505 error. Handled by handle505.
 */
exports.e505 = function(req, res, next){
    next(new Error('keyboard cat!'));
};

/**
 * 404 error handler.
 * We set header status and serve content
 * based on request headers.
 * $ curl http://localhost:3000/notfound
 * $ curl http://localhost:3000/notfound -H "Accept: application/json"
 * $ curl http://localhost:3000/notfound -H "Accept: text/plain"
 */
exports.handle404 = function(req, res, next){
    res.status(404);

    if(req.accepts('html')){
        res.sendfile('public/404.html');
        return;
    }

    if(req.accepts('json')){
        res.send({error:'Not Found.'});
        return;
    }

    res.type('text').send('Not Found.');
};

exports.handle505 = function(err, req, res, next){
    // we may use properties of the error object
    // here and next(err) appropriately, or if
    // we possibly recovered from the error, simply next().
    res.status(err.status || 500);
    res.sendfile('public/505.html');
    // res.render('500', { error: err });
};<commit_msg>Removed comments.<commit_after>var mongo;

exports.setDb = function(db){
    mongo = db;
};
/*
 * GET home page.
 */
exports.index = function(req, res){
    res.writeHead(200,{'Content-Type':'text/html'});
    res.sendfile('public/index.html');
    // res.render('index', { title: 'Express' });
};

exports.api = function(req, res){
    console.log('API');
    res.writeHead(200,{'Content-Type':'text/html'});
    res.end('API: v0.0.1');
};

/**
 * API method that returns all geo data.
 * It will group by session id.
 */
 //Filters for api mongo calls.
var filters = {};
filters.find = {loc:{$exists:true},payload:{$exists:true}};
filters.keys = {loc:1,payload:1,time:1,_id:0};
exports.api.getDarkness = function(req,res){
    console.log('API: Darkness');
    mongo.data.find(filters.find,filters.keys).toArray(function(error, data){
        if(error){
            //handle error!
            throw error;
        }

        //send data.
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "X-Requested-With");
        res.send(data);
    });
};

/**
 * API method to store sample data from device.
 * After storing in mongodb, it will dispatch
 * event to notify clients.
 */
exports.api.postDarkness = function(req, res){
    // console.log("POST: ");
    // console.log(req.body.data);
    var posted = JSON.parse( req.body.data );
    mongo.data.insert(posted, function(err, payload){
        // console.log('Inserted our content');
        //Should we ensure data integrity?!
        res.send(payload);
    });
};

/**
 * MIDDLEWARE: Ensure that we trigger
 * a 404 since the route won't be matched
 * and we handle it on handle404.
 */
exports.e404 = function(req, res, next){
    next( );
};

/**
 * MIDDLEWARE: Trigger- next- a generic
 * 505 error. Handled by handle505.
 */
exports.e505 = function(req, res, next){
    next(new Error('keyboard cat!'));
};

/**
 * 404 error handler.
 * We set header status and serve content
 * based on request headers.
 * $ curl http://localhost:3000/notfound
 * $ curl http://localhost:3000/notfound -H "Accept: application/json"
 * $ curl http://localhost:3000/notfound -H "Accept: text/plain"
 */
exports.handle404 = function(req, res, next){
    res.status(404);

    if(req.accepts('html')){
        res.sendfile('public/404.html');
        return;
    }

    if(req.accepts('json')){
        res.send({error:'Not Found.'});
        return;
    }

    res.type('text').send('Not Found.');
};

exports.handle505 = function(err, req, res, next){
    // we may use properties of the error object
    // here and next(err) appropriately, or if
    // we possibly recovered from the error, simply next().
    res.status(err.status || 500);
    res.sendfile('public/505.html');
    // res.render('500', { error: err });
};<|endoftext|>


<commit_before>var async        = require('async');
var crypto       = require('crypto');
var countries    = require('country-data').countries;
var phone        = require('phone');
var data         = require('./data');
var ovh          = require('./ovhApi');
var recaptcha    = require('./recaptcha');
var newrelic     = require('./newrelicApi');
var serversModel = require('../models/servers');
var requestModel = require('../models/requests');

/*
 *  INDEX
 *  Route : /
 *  Methode : GET
 */
exports.index = function( req, res, next ) {

    data.settings(req, res, { shouldBeLogged:false, mayBeLogged:true }, function( settings ) {
        loadResources({ refs:false }, next, function( ressources ) {

            settings.formErrors     = {};
            settings.sysServersList = ressources.sysServersList;
            settings.kimServersList = ressources.kimServersList;
            settings.stats          = ressources.stats;
            settings.countries      = countries.all;
            settings.pushbullet     = ( req.session.pushbullet.token ) ? true : false;
            settings.values         = {
                mail: ( settings.pushbullet ) ? req.session.pushbullet.email : null
            };

            res.render('index', settings);

        });
    });

};

/*
 *  INDEX
 *  Route : /
 *  Methode : POST
 */
exports.run = function( req, res, next ) {

    data.settings(req, res, { shouldBeLogged:false, mayBeLogged:true }, function( settings ) {
        loadResources({ refs:true }, next, function( ressources ) {

            var invalid  = 'La valeur de ce champ est invalide.';
            var required = 'Ce champ est requis.';

            // Validation des valeurs contenues dans req.body
            req.checkBody('mail', invalid).isEmail().len(5, 100);
            req.checkBody('mail', required).notEmpty();
            req.checkBody('zone', invalid).isIn(['europe', 'canada', 'all']);
            req.checkBody('zone', required).notEmpty();
            req.checkBody('server', invalid).isIn( ressources.refsList );
            req.checkBody('server', required).notEmpty();

            if( req.body.phone )
                req.checkBody('country', required).notEmpty();

            if( req.body.country )
                req.checkBody('phone', required).notEmpty();

            var errors = req.validationErrors( true );

            async.waterfall([

                // Vérification du formulaire
                function( callback ) {

                    if( errors )
                        callback("Une erreur est survenue lors de la validation du formulaire, veuillez vérifier les données saisies.");
                    else
                        callback();

                },

                // Validation du numéro de téléphone
                function( callback ) {

                    if( req.body.phone ) {

                        var phoneNumber = phone( req.body.phone, req.body.country )[0];

                        if( ! phoneNumber ) {

                            callback("Votre numéro de téléphone est invalide.");

                        } else {

                            // Numéro de téléphone mobile au format international
                            // Norme : UIT-T E.164 (11/2010)
                            // Préfixe international + indicatif pays + numéro national significatif
                            // Exemple (france) : 003361601XXXX
                            req.session.phone = "00" + String( phoneNumber ).substring(1);
                            callback();

                        }

                    } else {

                        callback();

                    }

                },

                // Vérification du captcha
                function( callback ) {

                    recaptcha.verify(req, req.body["g-recaptcha-response"], next, function( result ) {

                        if( ! result )
                            callback("Veuillez cocher la case située à la fin du formulaire afin de prouver que vous êtes bien humain.");
                        else
                            callback();

                    });

                },

                // Vérification de l'unicité de la demande
                function( callback ) {

                    requestModel.unique({ ref:(req.body.server).toLowerCase(), mail:(req.body.mail).toLowerCase() }, next, function( unique ) {

                        if( ! unique )
                            callback("Votre demande est toujours en attente, vous ne pouvez pas en créer plusieurs à la fois. Merci d'attendre de recevoir la notification par mail / Pushbullet.");
                        else
                            callback();

                    });

                },

                // Vérification de la disponibilité de l'offre
                function( callback ) {

                    ovh.getJson(next, function( json ) {
                        ovh.checkOffer(json, req.body.server, req.body.zone, next, function( available ) {

                            if( available )
                                callback("Cette offre est déjà disponible, vous pouvez réserver votre serveur dès à présent.");
                            else
                                callback();

                        });
                    });

                },

                // Ajout de la demande au sein de la base de données
                function( callback ) {

                    crypto.randomBytes(24, function( ex, buffer ) {

                        var data = {
                            reference:req.body.server,
                            mail:req.body.mail,
                            token:buffer.toString('hex'),
                            phone: ( req.session.phone ) ? req.session.phone : null,
                            pushbulletToken: ( req.session.pushbullet.token ) ? req.session.pushbullet.token : null,
                            zone:req.body.zone
                        };

                        requestModel.add(data, next, function( result ) {

                            if( req.session.phone ) delete req.session.phone;

                            if( result ) {

                                callback();

                            } else {

                                next( new Error("Une erreur est survenue lors de l'enregistrement de votre demande dans la base de données.") );
                                return;

                            }

                        });
                    });

                }

            ], function( err, result ) {

                if( err ) {

                    settings.formError   = true;
                    settings.formMessage = err;

                } else {

                    var events = [];
                    var eventObject = {
                        "eventType":"availabilityRequest",
                        "reference":req.body.server,
                        "zone":req.body.zone
                    };

                    events.push( eventObject );
                    newrelic.submitEvents( events );

                    settings.formSuccess = true;
                    settings.formMessage = 'Votre demande a bien été prise en compte.';

                }

                settings.formErrors     = ( errors ) ? errors : {};
                settings.sysServersList = ressources.sysServersList;
                settings.kimServersList = ressources.kimServersList;
                settings.stats          = ressources.stats;
                settings.countries      = countries.all;
                settings.pushbullet     = ( req.session.pushbullet.token ) ? true : false;
                settings.values         = req.body;

                res.render('index', settings);

            });

        });

    });

};

/*
 *  INDEX
 *  Route : /request/reactivate/:token
 *  Methode : GET
 */
exports.reactivate = function( req, res, next ) {

    data.settings(req, res, { shouldBeLogged:false, mayBeLogged:true }, function( settings ) {
        requestModel.getRequestByToken(req.params.token, next, function( request ) {

            async.waterfall([

                // Vérification du token
                function( callback ) {

                    if( ! request )
                        callback("Impossible d'effectuer cette action, token invalide.");
                    else
                        callback();

                },

                // Vérification de l'état de la demande
                function( callback ) {

                    if( request.state == 'pending' )
                        callback("Impossible d'effectuer cette action, votre demande est toujours active.");
                    else
                        callback();

                },

                // Mise à jour de la demande
                function( callback ) {

                    crypto.randomBytes(24, function( ex, buffer ) {

                        var token = buffer.toString('hex');

                        requestModel.updateState('pending', request.id, next);
                        requestModel.updateToken(token, request.id, next);

                        callback();

                    });

                }

            ], function( err, result ) {

                if( err ) {

                    next( new Error( err ) );
                    return;

                } else {

                    settings.formSuccess = true;
                    settings.formMessage = 'Votre demande a bien été réactivée.';
                    settings.request     = request;

                }

                res.render('reactivate', settings);

            });

        });
    });
};

/*
 *  Charge toutes les ressources de manière asynchrone
 */
var loadResources = function( options, next, callback ) {

    async.parallel({

        // Liste des serveurs Kimsufi
        sysServersList: function( callback ) {
            serversModel.getServers('sys', next, function( sysServersList ) {
                callback(null, sysServersList);
            });
        },

        // Liste des serveurs SoYouStart
        kimServersList: function( callback ) {
            serversModel.getServers('kimsufi', next, function( kimServersList ) {
                callback(null, kimServersList);
            });
        },

        // Liste des références OVH
        refsList: function( callback ) {

            if( options.refs ) {

                serversModel.getAllRefs(next, function( refsList ) {
                    callback(null, refsList);
                });

            } else {

                callback();

            }

        },

        // Statistiques
        stats: function( callback ) {
            requestModel.getStatistics(next, function( stats ) {
                callback(null, stats);
            });
        }

    }, function( err, resources ) {

        if( err ) {

            next( new Error( err ) );
            return;

        }

        callback( resources );

    });

};
<commit_msg>Ajout d'une autre sonde NR<commit_after>var async        = require('async');
var crypto       = require('crypto');
var countries    = require('country-data').countries;
var phone        = require('phone');
var data         = require('./data');
var ovh          = require('./ovhApi');
var recaptcha    = require('./recaptcha');
var newrelic     = require('./newrelicApi');
var serversModel = require('../models/servers');
var requestModel = require('../models/requests');

/*
 *  INDEX
 *  Route : /
 *  Methode : GET
 */
exports.index = function( req, res, next ) {

    data.settings(req, res, { shouldBeLogged:false, mayBeLogged:true }, function( settings ) {
        loadResources({ refs:false }, next, function( ressources ) {

            settings.formErrors     = {};
            settings.sysServersList = ressources.sysServersList;
            settings.kimServersList = ressources.kimServersList;
            settings.stats          = ressources.stats;
            settings.countries      = countries.all;
            settings.pushbullet     = ( req.session.pushbullet.token ) ? true : false;
            settings.values         = {
                mail: ( settings.pushbullet ) ? req.session.pushbullet.email : null
            };

            res.render('index', settings);

        });
    });

};

/*
 *  INDEX
 *  Route : /
 *  Methode : POST
 */
exports.run = function( req, res, next ) {

    data.settings(req, res, { shouldBeLogged:false, mayBeLogged:true }, function( settings ) {
        loadResources({ refs:true }, next, function( ressources ) {

            var invalid  = 'La valeur de ce champ est invalide.';
            var required = 'Ce champ est requis.';

            // Validation des valeurs contenues dans req.body
            req.checkBody('mail', invalid).isEmail().len(5, 100);
            req.checkBody('mail', required).notEmpty();
            req.checkBody('zone', invalid).isIn(['europe', 'canada', 'all']);
            req.checkBody('zone', required).notEmpty();
            req.checkBody('server', invalid).isIn( ressources.refsList );
            req.checkBody('server', required).notEmpty();

            if( req.body.phone )
                req.checkBody('country', required).notEmpty();

            if( req.body.country )
                req.checkBody('phone', required).notEmpty();

            var errors = req.validationErrors( true );

            async.waterfall([

                // Vérification du formulaire
                function( callback ) {

                    if( errors )
                        callback("Une erreur est survenue lors de la validation du formulaire, veuillez vérifier les données saisies.");
                    else
                        callback();

                },

                // Validation du numéro de téléphone
                function( callback ) {

                    if( req.body.phone ) {

                        var phoneNumber = phone( req.body.phone, req.body.country )[0];

                        if( ! phoneNumber ) {

                            callback("Votre numéro de téléphone est invalide.");

                        } else {

                            // Numéro de téléphone mobile au format international
                            // Norme : UIT-T E.164 (11/2010)
                            // Préfixe international + indicatif pays + numéro national significatif
                            // Exemple (france) : 003361601XXXX
                            req.session.phone = "00" + String( phoneNumber ).substring(1);
                            callback();

                        }

                    } else {

                        callback();

                    }

                },

                // Vérification du captcha
                function( callback ) {

                    recaptcha.verify(req, req.body["g-recaptcha-response"], next, function( result ) {

                        if( ! result )
                            callback("Veuillez cocher la case située à la fin du formulaire afin de prouver que vous êtes bien humain.");
                        else
                            callback();

                    });

                },

                // Vérification de l'unicité de la demande
                function( callback ) {

                    requestModel.unique({ ref:(req.body.server).toLowerCase(), mail:(req.body.mail).toLowerCase() }, next, function( unique ) {

                        if( ! unique )
                            callback("Votre demande est toujours en attente, vous ne pouvez pas en créer plusieurs à la fois. Merci d'attendre de recevoir la notification par mail / Pushbullet.");
                        else
                            callback();

                    });

                },

                // Vérification de la disponibilité de l'offre
                function( callback ) {

                    ovh.getJson(next, function( json ) {
                        ovh.checkOffer(json, req.body.server, req.body.zone, next, function( available ) {

                            if( available )
                                callback("Cette offre est déjà disponible, vous pouvez réserver votre serveur dès à présent.");
                            else
                                callback();

                        });
                    });

                },

                // Ajout de la demande au sein de la base de données
                function( callback ) {

                    crypto.randomBytes(24, function( ex, buffer ) {

                        var data = {
                            reference:req.body.server,
                            mail:req.body.mail,
                            token:buffer.toString('hex'),
                            phone: ( req.session.phone ) ? req.session.phone : null,
                            pushbulletToken: ( req.session.pushbullet.token ) ? req.session.pushbullet.token : null,
                            zone:req.body.zone
                        };

                        requestModel.add(data, next, function( result ) {

                            if( req.session.phone ) delete req.session.phone;

                            if( result ) {

                                callback();

                            } else {

                                next( new Error("Une erreur est survenue lors de l'enregistrement de votre demande dans la base de données.") );
                                return;

                            }

                        });
                    });

                }

            ], function( err, result ) {

                if( err ) {

                    settings.formError   = true;
                    settings.formMessage = err;

                } else {

                    var events = [];
                    var eventObject = {
                        "eventType":"availabilityRequest",
                        "reference":req.body.server,
                        "zone":req.body.zone
                    };

                    events.push( eventObject );
                    newrelic.submitEvents( events );

                    settings.formSuccess = true;
                    settings.formMessage = 'Votre demande a bien été prise en compte.';

                }

                settings.formErrors     = ( errors ) ? errors : {};
                settings.sysServersList = ressources.sysServersList;
                settings.kimServersList = ressources.kimServersList;
                settings.stats          = ressources.stats;
                settings.countries      = countries.all;
                settings.pushbullet     = ( req.session.pushbullet.token ) ? true : false;
                settings.values         = req.body;

                res.render('index', settings);

            });

        });

    });

};

/*
 *  INDEX
 *  Route : /request/reactivate/:token
 *  Methode : GET
 */
exports.reactivate = function( req, res, next ) {

    data.settings(req, res, { shouldBeLogged:false, mayBeLogged:true }, function( settings ) {
        requestModel.getRequestByToken(req.params.token, next, function( request ) {

            async.waterfall([

                // Vérification du token
                function( callback ) {

                    if( ! request )
                        callback("Impossible d'effectuer cette action, token invalide.");
                    else
                        callback();

                },

                // Vérification de l'état de la demande
                function( callback ) {

                    if( request.state == 'pending' )
                        callback("Impossible d'effectuer cette action, votre demande est toujours active.");
                    else
                        callback();

                },

                // Mise à jour de la demande
                function( callback ) {

                    crypto.randomBytes(24, function( ex, buffer ) {

                        var token = buffer.toString('hex');

                        requestModel.updateState('pending', request.id, next);
                        requestModel.updateToken(token, request.id, next);

                        callback();

                    });

                }

            ], function( err, result ) {

                if( err ) {

                    next( new Error( err ) );
                    return;

                } else {

                    var events = [];
                    var eventObject = {
                        "eventType":"reactivateRequest",
                        "count":1
                    };

                    events.push( eventObject );
                    newrelic.submitEvents( events );

                    settings.formSuccess = true;
                    settings.formMessage = 'Votre demande a bien été réactivée.';
                    settings.request     = request;

                }

                res.render('reactivate', settings);

            });

        });
    });
};

/*
 *  Charge toutes les ressources de manière asynchrone
 */
var loadResources = function( options, next, callback ) {

    async.parallel({

        // Liste des serveurs Kimsufi
        sysServersList: function( callback ) {
            serversModel.getServers('sys', next, function( sysServersList ) {
                callback(null, sysServersList);
            });
        },

        // Liste des serveurs SoYouStart
        kimServersList: function( callback ) {
            serversModel.getServers('kimsufi', next, function( kimServersList ) {
                callback(null, kimServersList);
            });
        },

        // Liste des références OVH
        refsList: function( callback ) {

            if( options.refs ) {

                serversModel.getAllRefs(next, function( refsList ) {
                    callback(null, refsList);
                });

            } else {

                callback();

            }

        },

        // Statistiques
        stats: function( callback ) {
            requestModel.getStatistics(next, function( stats ) {
                callback(null, stats);
            });
        }

    }, function( err, resources ) {

        if( err ) {

            next( new Error( err ) );
            return;

        }

        callback( resources );

    });

};
<|endoftext|>


<commit_before>"use strict";

const gulp = require("gulp");
const git = require("gulp-git");
const path = require("path");
const typescript = require("typescript");
const ts = require("gulp-typescript");
const uglifyjs = require("uglify-js-harmony");
const minifier = require("gulp-uglify/minifier");
const source = require("vinyl-source-stream");
const del = require("del");
const browserify = require("browserify");
const gutil = require("gulp-util");
const _ = require("underscore");
const electron = require("gulp-atom-electron");
const vfs = require("vinyl-fs");
const shell = require("gulp-shell");
const product = require("./product.json");
const shrinkwrap = require("./shrinkwrap.json");

/*
 * Trusted_eSign | Trusted_Api
*/
const TARGET = "Trusted_eSign";
const ELECTRON_VERSION = "1.2.4";
let architecture;

const dependencies = Object.keys(shrinkwrap.dependencies);
const depsSrc = _.flatten(dependencies.map(d => [`node_modules/${d}/**`]));

const project = ts.createProject("tsconfig.json", { typescript });

gulp.task("set architecture x64", () => {
  architecture = "x64";
});

gulp.task("set architecture ia32", () => {
  architecture = "ia32";
});

gulp.task("clean", () => del(["build", "tmp", "tmp_app_build", "trusted-crypto"]));

gulp.task("compile", ["clean"], () => gulp.src([`src/${TARGET}/**/*.tsx`, `src/${TARGET}/**/*.ts`])
  .pipe(project())
  .pipe(gulp.dest("tmp")));

gulp.task("bundle", ["compile"], () => browserify("tmp/main.js")
  .bundle()
  .pipe(source(`bundle_${TARGET}.js`))
  .pipe(gulp.dest("tmp")));

gulp.task("minimize", ["bundle"], () => {
  const options = {
    preserveComments: "license"
  };

  return gulp.src([`tmp/bundle_${TARGET}.js`])
    .pipe(minifier(options, uglifyjs))
    .on("error", err => {
      gutil.log(gutil.colors.red("[Error]"), err.toString());
    })
    .pipe(gulp.dest(`resources/${TARGET}`));
});

gulp.task("resources copy", ["minimize"], () => gulp.src(["resources/**/**"])
    .pipe(gulp.dest(`./tmp_app_build/electron-${process.platform}-${architecture}`)));

gulp.task("module copy", ["resources copy"], () => gulp.src(depsSrc, { base: ".", dot: true })
    .pipe(gulp.dest(`./tmp_app_build/electron-${process.platform}-${architecture}/`)));

gulp.task("rebuild trusted-crypto", ["clean"], cb => {
  let task;

  git.clone("https://github.com/TrustedPlus/crypto.git", { args: "./trusted-crypto" }, err => {
    if (err) {
      gutil.log(gutil.colors.red("[Error]"), err.toString());
    } else {
      task = shell.task([
        `node-gyp rebuild --target=${ELECTRON_VERSION} --arch=${architecture} --dist-url=https://atom.io/download/electron`,
        "tsc"
      ], { cwd: path.join(`${process.cwd()}`, "trusted-crypto") });

      task(cb);
    }
  });
});

gulp.task("trusted-crypto copy", ["rebuild trusted-crypto"], () => gulp.src(["./trusted-crypto/**/**"])
    .pipe(gulp.dest(`./tmp_app_build/electron-${process.platform}-${architecture}/node_modules/trusted-crypto`)));

const config = {
  version: ELECTRON_VERSION,
  productAppName: product.nameLong,
  companyName: "Digt",
  copyright: "Copyright (C) 2017 Digt. All rights reserved",
  darwinIcon: "resources/Trusted_eSign/trusted-esign.icns",
  linuxExecutableName: product.applicationName,
  winIcon: "resources/Trusted_eSign/trusted-esign.ico",
  token: process.env.GITHUB_TOKEN || void 0
};

gulp.task("build electron", ["trusted-crypto copy", "module copy"], () => {
  const platform = process.platform;
  const arch = architecture;
  const opts = _.extend({}, config, { platform, arch, ffmpegChromium: true, keepDefaultApp: true });

  return gulp.src("./tmp_app_build/electron-win32-x64/**")
    .pipe(electron(opts))
    .pipe(vfs.dest(`build/${ELECTRON_VERSION}/${process.platform}-${architecture}`));
});

gulp.task("cert copy", ["build electron"], () => gulp.src(["./resources/Trusted_eSign/cert1.crt", "./resources/Trusted_eSign/cert1.key"])
    .pipe(gulp.dest(`./build/${ELECTRON_VERSION}/${process.platform}-${architecture}`)));

gulp.task("x64", ["set architecture x64",
  "build electron",
  "cert copy"
]);

gulp.task("ia32", ["set architecture ia32",
  "build electron",
  "cert copy"
]);

gulp.task("default", [
  "x64"
]);
<commit_msg>fix gulpfile<commit_after>"use strict";

const gulp = require("gulp");
const git = require("gulp-git");
const path = require("path");
const typescript = require("typescript");
const ts = require("gulp-typescript");
const uglifyjs = require("uglify-js-harmony");
const minifier = require("gulp-uglify/minifier");
const source = require("vinyl-source-stream");
const del = require("del");
const browserify = require("browserify");
const gutil = require("gulp-util");
const _ = require("underscore");
const electron = require("gulp-atom-electron");
const vfs = require("vinyl-fs");
const shell = require("gulp-shell");
const product = require("./product.json");
const shrinkwrap = require("./shrinkwrap.json");

/*
 * Trusted_eSign | Trusted_Api
*/
const TARGET = "Trusted_eSign";
const ELECTRON_VERSION = "1.2.4";
let architecture;

const dependencies = Object.keys(shrinkwrap.dependencies);
const depsSrc = _.flatten(dependencies.map(d => [`node_modules/${d}/**`]));

const project = ts.createProject("tsconfig.json", { typescript });

gulp.task("set architecture x64", () => {
  architecture = "x64";
});

gulp.task("set architecture ia32", () => {
  architecture = "ia32";
});

gulp.task("clean", () => del(["build", "tmp", "tmp_app_build", "trusted-crypto"]));

gulp.task("compile", ["clean"], () => gulp.src([`src/${TARGET}/**/*.tsx`, `src/${TARGET}/**/*.ts`])
  .pipe(project())
  .pipe(gulp.dest("tmp")));

gulp.task("bundle", ["compile"], () => browserify("tmp/main.js")
  .bundle()
  .pipe(source(`bundle_${TARGET}.js`))
  .pipe(gulp.dest("tmp")));

gulp.task("minimize", ["bundle"], () => {
  const options = {
    preserveComments: "license"
  };

  return gulp.src([`tmp/bundle_${TARGET}.js`])
    .pipe(minifier(options, uglifyjs))
    .on("error", err => {
      gutil.log(gutil.colors.red("[Error]"), err.toString());
    })
    .pipe(gulp.dest(`resources/${TARGET}`));
});

gulp.task("resources copy", ["minimize"], () => gulp.src(["resources/**/**"])
    .pipe(gulp.dest(`./tmp_app_build/electron-${process.platform}-${architecture}`)));

gulp.task("module copy", ["resources copy"], () => gulp.src(depsSrc, { base: ".", dot: true })
    .pipe(gulp.dest(`./tmp_app_build/electron-${process.platform}-${architecture}/`)));

gulp.task("rebuild trusted-crypto", ["clean"], cb => {
  let task;

  git.clone("https://github.com/TrustedPlus/crypto.git", { args: "./trusted-crypto" }, err => {
    if (err) {
      gutil.log(gutil.colors.red("[Error]"), err.toString());
    } else {
      task = shell.task([
        `node-gyp rebuild --target=${ELECTRON_VERSION} --arch=${architecture} --dist-url=https://atom.io/download/electron`,
        "tsc"
      ], { cwd: path.join(`${process.cwd()}`, "trusted-crypto") });

      task(cb);
    }
  });
});

gulp.task("trusted-crypto copy", ["rebuild trusted-crypto"], () => gulp.src(["./trusted-crypto/**/**"])
    .pipe(gulp.dest(`./tmp_app_build/electron-${process.platform}-${architecture}/node_modules/trusted-crypto`)));

const config = {
  version: ELECTRON_VERSION,
  productAppName: product.nameLong,
  companyName: "Digt",
  copyright: "Copyright (C) 2017 Digt. All rights reserved",
  darwinIcon: "resources/Trusted_eSign/trusted-esign.icns",
  linuxExecutableName: product.applicationName,
  winIcon: "resources/Trusted_eSign/trusted-esign.ico",
  token: process.env.GITHUB_TOKEN || void 0
};

gulp.task("build electron", ["trusted-crypto copy", "module copy"], () => {
  const platform = process.platform;
  const arch = architecture;
  const opts = _.extend({}, config, { platform, arch, ffmpegChromium: true, keepDefaultApp: true });

  return gulp.src(`./tmp_app_build/electron-${process.platform}-${architecture}/**`)
    .pipe(electron(opts))
    .pipe(vfs.dest(`build/${ELECTRON_VERSION}/${process.platform}-${architecture}`));
});

gulp.task("cert copy", ["build electron"], () => gulp.src(["./resources/Trusted_eSign/cert1.crt", "./resources/Trusted_eSign/cert1.key"])
    .pipe(gulp.dest(`./build/${ELECTRON_VERSION}/${process.platform}-${architecture}`)));

gulp.task("x64", ["set architecture x64",
  "build electron",
  "cert copy"
]);

gulp.task("ia32", ["set architecture ia32",
  "build electron",
  "cert copy"
]);

gulp.task("default", [
  "x64"
]);
<|endoftext|>


<commit_before>'use strict';

const del = require('del');
const gulp = require('gulp');
const gulpif = require('gulp-if');
const uglifyes = require('uglify-es');
const composer = require('gulp-uglify/composer');
const cssSlam = require('css-slam').gulp;
const mergeStream = require('merge-stream');
const polymerBuild = require('polymer-build');
const browserSync = require('browser-sync').create();
const history = require('connect-history-api-fallback');

const HtmlSplitter = polymerBuild.HtmlSplitter;
const PolymerProject = polymerBuild.PolymerProject;
const uglify = composer(uglifyes, console);

const logging = require('plylog');
// logging.setVerbose();

const config = {
  polymerJsonPath: './polymer.json',
  build: {
    rootDirectory: 'build'
  },
  swPrecacheConfigPath: './sw-precache-config.js',
  templateData: [
    'data/hoverboard.config',
    'data/resources'
  ],
  tempDirectory: '.temp'
};
const swPrecacheConfig = require(config.swPrecacheConfigPath);
const polymerJson = require(config.polymerJsonPath);
const buildPolymerJson = {
  entrypoint: prependPath(config.tempDirectory, polymerJson.entrypoint),
  shell: prependPath(config.tempDirectory, polymerJson.shell),
  fragments: polymerJson.fragments.reduce((res, el) => [...res, prependPath(config.tempDirectory, el)], []),
  sources: polymerJson.sources.reduce((res, el) => [...res, prependPath(config.tempDirectory, el)], []),
  extraDependencies: polymerJson.extraDependencies
};

const normalize = require('./gulp-tasks/normalize.js');
const template = require('./gulp-tasks/template.js');
const images = require('./gulp-tasks/images.js');
const html = require('./gulp-tasks/html.js');

function build() {
  return new Promise(resolve => {
    let polymerProject = null;
    console.log(`Deleting ${config.build.rootDirectory} and ${config.tempDirectory} directories...`);

    del([config.build.rootDirectory, config.tempDirectory])
      .then(() => {
        console.log(`Compiling template...`);

        const compileStream = template.compile(config, polymerJson)
          .on('end', () => {
            polymerProject = new PolymerProject(buildPolymerJson);
          });
        return waitFor(compileStream);
      })
      .then(() => {
        console.log(`Polymer building...`);

        const sourcesHtmlSplitter = new HtmlSplitter();
        const sourcesStream = polymerProject.sources()
          .pipe(sourcesHtmlSplitter.split())
          .pipe(gulpif(/\.js$/, uglify()))
          .pipe(gulpif(/\.(html|css)$/, cssSlam()))
          .pipe(gulpif(/\.html$/, html.minify()))
          .pipe(gulpif(/\.(png|gif|jpg|svg)$/, images.minify()))
          .pipe(sourcesHtmlSplitter.rejoin());

        const dependenciesHtmlSplitter = new HtmlSplitter();
        const dependenciesStream = polymerProject.dependencies()
          .pipe(dependenciesHtmlSplitter.split())
          // Doesn't work for now
          .pipe(gulpif(/\.js$/, uglify()))
          .pipe(gulpif(/\.(html|css)$/, cssSlam()))
          .pipe(gulpif(/\.html$/, html.minify()))
          .pipe(dependenciesHtmlSplitter.rejoin());

        let buildStream = mergeStream(sourcesStream, dependenciesStream)
          .once('data', () => {
            console.log('Analyzing and optimizing...');
          });

        buildStream = buildStream.pipe(polymerProject.bundler({
          stripComments: true
        }));
        buildStream = buildStream.pipe(gulp.dest(config.build.rootDirectory));
        return waitFor(buildStream);
      })
      .then(() => {
        console.log('Generating the Service Worker...');

        return polymerBuild.addServiceWorker({
          project: polymerProject,
          buildRoot: prependPath(config.build.rootDirectory, config.tempDirectory).replace('\\', '/'),
          bundled: config.build.bundled,
          swPrecacheConfig
        });
      })
      .then(() => {
        console.log('Normalizing...');

        const normalizeStream = normalize(config)
          .on('end', () => {
            del([prependPath(config.build.rootDirectory, config.tempDirectory)])
          });

        return waitFor(normalizeStream);
      })
      .then(() => {
        return gulp.src(prependPath(config.build.rootDirectory, 'service-worker.js'))
          .pipe(uglify())
          .pipe(gulp.dest(config.build.rootDirectory));
      })
      .then(() => {
        console.log('Build complete!');
        resolve();
      });
  });
}

function waitFor(stream) {
  return new Promise((resolve, reject) => {
    stream.on('end', resolve);
    stream.on('error', reject);
  });
}

function reload(done) {
  browserSync.reload();
  done();
}

function compileTemplate() {
  return del([config.tempDirectory])
    .then(() => {
      return waitFor(template.compile(config, polymerJson));
    });
}

function copyStatic() {
  return gulp.src([
    'data/**/*.{markdown,md}',
    'images/**/*.{png,gif,jpg,svg}'
  ], {base: '.'})
    .pipe(gulp.dest(config.tempDirectory));
}

function prependPath(pre, to) {
  return `${pre}/${to}`;
}

gulp.task('default', build);

gulp.task('serve', gulp.series(compileTemplate, () => {
  browserSync.init({
    logPrefix: 'Hoverboard 2',
    notify: false,
    server: {
      baseDir: [config.tempDirectory, './'],
      middleware: [history()]
    }
  });

  gulp.watch([
    'data/**/*.{markdown,md}',
    'images/**/*.{png,gif,jpg,svg}',
  ], gulp.series(copyStatic, reload));

  gulp.watch([
    'data/**/*.json',
    'scripts/**/*.js',
    'src/**/*.html',
    '*.{html,js}',
    'manifest.json'
  ], gulp.series(compileTemplate, reload));
}));

<commit_msg>Disable image optimization<commit_after>'use strict';

const del = require('del');
const gulp = require('gulp');
const gulpif = require('gulp-if');
const uglifyes = require('uglify-es');
const composer = require('gulp-uglify/composer');
const cssSlam = require('css-slam').gulp;
const mergeStream = require('merge-stream');
const polymerBuild = require('polymer-build');
const browserSync = require('browser-sync').create();
const history = require('connect-history-api-fallback');

const HtmlSplitter = polymerBuild.HtmlSplitter;
const PolymerProject = polymerBuild.PolymerProject;
const uglify = composer(uglifyes, console);

const logging = require('plylog');
// logging.setVerbose();

const config = {
  polymerJsonPath: './polymer.json',
  build: {
    rootDirectory: 'build'
  },
  swPrecacheConfigPath: './sw-precache-config.js',
  templateData: [
    'data/hoverboard.config',
    'data/resources'
  ],
  tempDirectory: '.temp'
};
const swPrecacheConfig = require(config.swPrecacheConfigPath);
const polymerJson = require(config.polymerJsonPath);
const buildPolymerJson = {
  entrypoint: prependPath(config.tempDirectory, polymerJson.entrypoint),
  shell: prependPath(config.tempDirectory, polymerJson.shell),
  fragments: polymerJson.fragments.reduce((res, el) => [...res, prependPath(config.tempDirectory, el)], []),
  sources: polymerJson.sources.reduce((res, el) => [...res, prependPath(config.tempDirectory, el)], []),
  extraDependencies: polymerJson.extraDependencies
};

const normalize = require('./gulp-tasks/normalize.js');
const template = require('./gulp-tasks/template.js');
const images = require('./gulp-tasks/images.js');
const html = require('./gulp-tasks/html.js');

function build() {
  return new Promise(resolve => {
    let polymerProject = null;
    console.log(`Deleting ${config.build.rootDirectory} and ${config.tempDirectory} directories...`);

    del([config.build.rootDirectory, config.tempDirectory])
      .then(() => {
        console.log(`Compiling template...`);

        const compileStream = template.compile(config, polymerJson)
          .on('end', () => {
            polymerProject = new PolymerProject(buildPolymerJson);
          });
        return waitFor(compileStream);
      })
      .then(() => {
        console.log(`Polymer building...`);

        const sourcesHtmlSplitter = new HtmlSplitter();
        const sourcesStream = polymerProject.sources()
          .pipe(sourcesHtmlSplitter.split())
          .pipe(gulpif(/\.js$/, uglify()))
          .pipe(gulpif(/\.(html|css)$/, cssSlam()))
          .pipe(gulpif(/\.html$/, html.minify()))
          // .pipe(gulpif(/\.(png|gif|jpg|svg)$/, images.minify()))
          .pipe(sourcesHtmlSplitter.rejoin());

        const dependenciesHtmlSplitter = new HtmlSplitter();
        const dependenciesStream = polymerProject.dependencies()
          .pipe(dependenciesHtmlSplitter.split())
          // Doesn't work for now
          .pipe(gulpif(/\.js$/, uglify()))
          .pipe(gulpif(/\.(html|css)$/, cssSlam()))
          .pipe(gulpif(/\.html$/, html.minify()))
          .pipe(dependenciesHtmlSplitter.rejoin());

        let buildStream = mergeStream(sourcesStream, dependenciesStream)
          .once('data', () => {
            console.log('Analyzing and optimizing...');
          });

        buildStream = buildStream.pipe(polymerProject.bundler({
          stripComments: true
        }));
        buildStream = buildStream.pipe(gulp.dest(config.build.rootDirectory));
        return waitFor(buildStream);
      })
      .then(() => {
        console.log('Generating the Service Worker...');

        return polymerBuild.addServiceWorker({
          project: polymerProject,
          buildRoot: prependPath(config.build.rootDirectory, config.tempDirectory).replace('\\', '/'),
          bundled: config.build.bundled,
          swPrecacheConfig
        });
      })
      .then(() => {
        console.log('Normalizing...');

        const normalizeStream = normalize(config)
          .on('end', () => {
            del([prependPath(config.build.rootDirectory, config.tempDirectory)])
          });

        return waitFor(normalizeStream);
      })
      .then(() => {
        return gulp.src(prependPath(config.build.rootDirectory, 'service-worker.js'))
          .pipe(uglify())
          .pipe(gulp.dest(config.build.rootDirectory));
      })
      .then(() => {
        console.log('Build complete!');
        resolve();
      });
  });
}

function waitFor(stream) {
  return new Promise((resolve, reject) => {
    stream.on('end', resolve);
    stream.on('error', reject);
  });
}

function reload(done) {
  browserSync.reload();
  done();
}

function compileTemplate() {
  return del([config.tempDirectory])
    .then(() => {
      return waitFor(template.compile(config, polymerJson));
    });
}

function copyStatic() {
  return gulp.src([
    'data/**/*.{markdown,md}',
    'images/**/*.{png,gif,jpg,svg}'
  ], {base: '.'})
    .pipe(gulp.dest(config.tempDirectory));
}

function prependPath(pre, to) {
  return `${pre}/${to}`;
}

gulp.task('default', build);

gulp.task('serve', gulp.series(compileTemplate, () => {
  browserSync.init({
    logPrefix: 'Hoverboard 2',
    notify: false,
    server: {
      baseDir: [config.tempDirectory, './'],
      middleware: [history()]
    }
  });

  gulp.watch([
    'data/**/*.{markdown,md}',
    'images/**/*.{png,gif,jpg,svg}',
  ], gulp.series(copyStatic, reload));

  gulp.watch([
    'data/**/*.json',
    'scripts/**/*.js',
    'src/**/*.html',
    '*.{html,js}',
    'manifest.json'
  ], gulp.series(compileTemplate, reload));
}));

<|endoftext|>


<commit_before>'use strict';
module.exports = function(express) {
  const router = express.Router();
  const async = require('async');
  let meals = require('../models/meals.js');
  let userMeals = require('../models/user_meals.js');
  let users = require('../models/users.js');
  const db = require('../server/db.js');

  router.route('/')

  .get((req, res) => {
    res.send('meals route is working.');
  })

  //If the user decides to remove a meal from their meal plan heres the http request to do that.
  .delete(function(req, res) {
    let data = req.body;

    async.waterfall([
      function(callback) {
        users.find({
          where: { userId: data.userId }
        }, function(err) {
          res.status(500).json({error: err})
        }, function(user) {
          callback(null, user);
        })
      }, function(user, callback) {
        user.removeMeal(data.mealId, function(err) {
          res.status(500).json({error: err})
        }, function(removedMeal) {
          callback(null, removedMeal)
        });
      }
    ],
    function(err, removedMeal) {
      if(err) {
        res.status(500).json({error: err});
      }
      res.status(200).json({
        mealType: data.mealType,
        mealId: removedMeal.mealId
      });
    });
  })

  //Put request to add a meal the user mealPlan
  .put(function(req, res) {
    let data = req.body;

    async.waterfall([
      (callback) => {
        users.find(data,
        (err) => {
          res.status(500).json({ error: err });
        },
        (user) => {
          db.meals.create({
            mealId: data.meal.id,
            name: data.meal.name,
            image: data.meal.image
          }).then((meal) => {
            user.addMeal(meal, {
              date: data.date,
              mealType: data.mealType
            }).then(() => {
              callback(null, user.getMeals());
            }).catch((err) => {
              res.status(500).json({ error: err });
            })
          }).catch((err) => {
            res.status(500).json({ error: err });
          })
        })
      }
    ],
    (err, result) => {
      if(err) {
        res.status(500).json({ error: err });
      }
      res.status(200).json({ result });
    });
  });

  router.route('/:userId')

  .get(function(req, res) {
    let userId = req.params.userId;
    users.find({
      where: { userId: userId },
      include: [ meals ]
    }, function(err) {
      res.status(500).json({ error: err });
    }, function(foundMeals) {
      res.status(200).json(foundMeals);
    })
  });

  return router;
};
<commit_msg>wrapping the addmeal in a callback to see if i can return the value<commit_after>'use strict';
module.exports = function(express) {
  const router = express.Router();
  const async = require('async');
  let meals = require('../models/meals.js');
  let userMeals = require('../models/user_meals.js');
  let users = require('../models/users.js');
  const db = require('../server/db.js');

  router.route('/')

  .get((req, res) => {
    res.send('meals route is working.');
  })

  //If the user decides to remove a meal from their meal plan heres the http request to do that.
  .delete(function(req, res) {
    let data = req.body;

    async.waterfall([
      function(callback) {
        users.find({
          where: { userId: data.userId }
        }, function(err) {
          res.status(500).json({error: err})
        }, function(user) {
          callback(null, user);
        })
      }, function(user, callback) {
        user.removeMeal(data.mealId, function(err) {
          res.status(500).json({error: err})
        }, function(removedMeal) {
          callback(null, removedMeal)
        });
      }
    ],
    function(err, removedMeal) {
      if(err) {
        res.status(500).json({error: err});
      }
      res.status(200).json({
        mealType: data.mealType,
        mealId: removedMeal.mealId
      });
    });
  })

  //Put request to add a meal the user mealPlan
  .put(function(req, res) {
    let data = req.body;

    async.waterfall([
      (callback) => {
        users.find(data,
        (err) => {
          res.status(500).json({ error: err });
        },
        (user) => {
          db.meals.create({
            mealId: data.meal.id,
            name: data.meal.name,
            image: data.meal.image
          }).then((meal) => {
            callback(null, user.addMeal(meal, {
              date: data.date,
              mealType: data.mealType
            }));
          }).catch((err) => {
            res.status(500).json({ error: err });
          })
        })
      }
    ],
    (err, result) => {
      if(err) {
        res.status(500).json({ error: err });
      }
      res.status(200).json({ result });
    });
  });

  router.route('/:userId')

  .get(function(req, res) {
    let userId = req.params.userId;
    users.find({
      where: { userId: userId },
      include: [ meals ]
    }, function(err) {
      res.status(500).json({ error: err });
    }, function(foundMeals) {
      res.status(200).json(foundMeals);
    })
  });

  return router;
};
<|endoftext|>


<commit_before>/*!
 * @author:    Divio AG
 * @copyright: http://www.divio.ch
 */

'use strict';

// #############################################################################
// IMPORTS
var gulp = require('gulp');
var gutil = require('gulp-util');
var karma = require('karma').server;
var protractor = require('gulp-protractor').protractor;
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');
var webdriverUpdate = require('gulp-protractor').webdriver_update;
var SauceTunnel = require('sauce-tunnel');
var tunnel;
var isTunnelCreated;

// #############################################################################
// SETTINGS
var PROJECT_ROOT = __dirname;
var PROJECT_PATH = {
    'js': PROJECT_ROOT + '/aldryn_newsblog/boilerplates/bootstrap3/static/js/',
    'tests': PROJECT_ROOT + '/aldryn_newsblog/tests/frontend'
};

var PROJECT_PATTERNS = {
    'lint': [
        PROJECT_PATH.js + '/addons/*.js',
        PROJECT_PATH.tests + '/**/*.js',
        '!' + PROJECT_PATH.tests + '/coverage/**/*.js',
        PROJECT_ROOT + '/gulpfile.js'
    ]
};

var PORT = parseInt(process.env.PORT, 10) || 8000;

// #############################################################################
// LINTING
gulp.task('lint', function () {
    return gulp.src(PROJECT_PATTERNS.lint)
        .pipe(jshint())
        .pipe(jscs())
        .on('error', function (error) {
            gutil.log('\n' + error.message);
            if (process.env.CI) {
                // Force the process to exit with error code
                process.exit(1);
            }
        })
        .pipe(jshint.reporter('jshint-stylish'));
});

// #########################################################
// TESTS
gulp.task('tests', ['tests:unit', 'tests:lint', 'tests:integration']);
gulp.task('tests:lint', ['lint']);
gulp.task('tests:unit', function (done) {
    // run javascript tests
    karma.start({
        configFile: PROJECT_PATH.tests + '/karma.conf.js',
        singleRun: true
    }, done);
});

gulp.task('tests:sauce:start', function (done) {
    if (!process.env.CI) {
        done();
        return;
    }
    tunnel = new SauceTunnel(
        process.env.SAUCE_USERNAME,
        process.env.SAUCE_ACCESS_KEY,
        process.env.TRAVIS_JOB_NUMBER
    );

    tunnel.start(function (isCreated) {
        isTunnelCreated = isCreated;
        if (!isCreated) {
            console.log('Failed to create Sauce tunnel, returning error code');
            // Force the process to exit with error code
            process.exit(1);
            return false;
        }
        console.log('Connected to Sauce Labs.');
        done();
    });
});

gulp.task('tests:sauce:end', function (done) {
    if (!process.env.CI) {
        done();
        return;
    }
    tunnel.stop(function () {
        console.log('Stopping the server.');
        done();
    });
});

gulp.task('tests:webdriver', webdriverUpdate);
gulp.task('tests:integration', ['tests:webdriver', 'tests:sauce:start'], function () {
    if (process.env.CI && !isTunnelCreated) {
        // Force the process to exit with error code if couldn't create the tunnel
        process.exit(1);
        return false;
    }
    return gulp.src([PROJECT_PATH.tests + '/integration/specs/*.js'])
        .pipe(protractor({
            configFile: PROJECT_PATH.tests + '/protractor.conf.js',
            args: ['--baseUrl', 'http://127.0.0.1:' + PORT]
        }))
        .on('error', function (error) {
            gutil.log(gutil.colors.red(
                'Error (' + error.plugin + '): ' + error.message
            ));
            // Force the process to exit with error code
            process.exit(1);
        })
        .on('end', function () {
            gulp.run('tests:sauce:end');
        });
});

gulp.task('tests:watch', function () {
    // run javascript tests
    karma.start({
        configFile: PROJECT_PATH.tests + '/karma.conf.js'
    });
});

// #############################################################################
// COMMANDS
gulp.task('default', ['lint']);
<commit_msg>Testing Sauce Labs tunnel<commit_after>/*!
 * @author:    Divio AG
 * @copyright: http://www.divio.ch
 */

'use strict';

// #############################################################################
// IMPORTS
var gulp = require('gulp');
var gutil = require('gulp-util');
var karma = require('karma').server;
var protractor = require('gulp-protractor').protractor;
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');
var webdriverUpdate = require('gulp-protractor').webdriver_update;
var SauceTunnel = require('sauce-tunnel');
var tunnel;
var isTunnelCreated;

// #############################################################################
// SETTINGS
var PROJECT_ROOT = __dirname;
var PROJECT_PATH = {
    'js': PROJECT_ROOT + '/aldryn_newsblog/boilerplates/bootstrap3/static/js/',
    'tests': PROJECT_ROOT + '/aldryn_newsblog/tests/frontend'
};

var PROJECT_PATTERNS = {
    'lint': [
        PROJECT_PATH.js + '/addons/*.js',
        PROJECT_PATH.tests + '/**/*.js',
        '!' + PROJECT_PATH.tests + '/coverage/**/*.js',
        PROJECT_ROOT + '/gulpfile.js'
    ]
};

var PORT = parseInt(process.env.PORT, 10) || 8000;

// #############################################################################
// LINTING
gulp.task('lint', function () {
    return gulp.src(PROJECT_PATTERNS.lint)
        .pipe(jshint())
        .pipe(jscs())
        .on('error', function (error) {
            gutil.log('\n' + error.message);
            if (process.env.CI) {
                // Force the process to exit with error code
                process.exit(1);
            }
        })
        .pipe(jshint.reporter('jshint-stylish'));
});

// #########################################################
// TESTS
gulp.task('tests', ['tests:unit', 'tests:lint', 'tests:integration']);
gulp.task('tests:lint', ['lint']);
gulp.task('tests:unit', function (done) {
    // run javascript tests
    karma.start({
        configFile: PROJECT_PATH.tests + '/karma.conf.js',
        singleRun: true
    }, done);
});

gulp.task('tests:sauce:start', function (done) {
    if (!process.env.CI) {
        done();
        return;
    }
    tunnel = new SauceTunnel(
        process.env.SAUCE_USERNAME,
        process.env.SAUCE_ACCESS_KEY,
        process.env.TRAVIS_JOB_NUMBER
    );

    tunnel.start(function (isCreated) {
        isTunnelCreated = isCreated;
        if (!isCreated) {
            console.log('Failed to create Sauce tunnel, returning error code');
            // Force the process to exit with error code if couldn't create the tunnel
            process.exit(1);
            return false;
        }
        console.log('Connected to Sauce Labs.');
        done();
    });
});

gulp.task('tests:sauce:end', function (done) {
    if (!process.env.CI) {
        done();
        return;
    }
    tunnel.stop(function () {
        console.log('Stopping the server.');
        done();
    });
});

gulp.task('tests:webdriver', webdriverUpdate);
gulp.task('tests:integration', ['tests:webdriver', 'tests:sauce:start'], function () {
    if (process.env.CI && !isTunnelCreated) {
        // Force the process to exit with error code if couldn't create the tunnel
        process.exit(1);
        return false;
    }
    return gulp.src([PROJECT_PATH.tests + '/integration/specs/*.js'])
        .pipe(protractor({
            configFile: PROJECT_PATH.tests + '/protractor.conf.js',
            args: ['--baseUrl', 'http://127.0.0.1:' + PORT]
        }))
        .on('error', function (error) {
            gutil.log(gutil.colors.red(
                'Error (' + error.plugin + '): ' + error.message
            ));
            // Force the process to exit with error code
            process.exit(1);
        })
        .on('end', function () {
            gulp.run('tests:sauce:end');
        });
});

gulp.task('tests:watch', function () {
    // run javascript tests
    karma.start({
        configFile: PROJECT_PATH.tests + '/karma.conf.js'
    });
});

// #############################################################################
// COMMANDS
gulp.task('default', ['lint']);
<|endoftext|>


<commit_before>'use strict';

var express = require('express');
var router = express.Router();
var passport = require('passport');

router.get('/google/callback',
    console.log('SOMETING@@@@');
  passport.authenticate('google', { failureRedirect: '/' }),
  function(req, res) {
    // Successful authentication, redirect home.
    // console.log('SESSION IS', req.session);
    var currentUser = req.session.passport.user.username;
    res.redirect('/users/'+ currentUser);
    //temp res.send for
    // res.send('OAUTH SIGNIN WORKED!')
  });

//? DO we want to do a logout button?
// router.get('/logout', function(req, res){
//   req.logout();
//   res.redirect('/');
// });

module.exports = router;
<commit_msg>made a stupid mistake<commit_after>'use strict';

var express = require('express');
var router = express.Router();
var passport = require('passport');

router.get('/google/callback',
  passport.authenticate('google', { failureRedirect: '/' }),
  function(req, res) {
    // Successful authentication, redirect home.
    // console.log('SESSION IS', req.session);
    var currentUser = req.session.passport.user.username;
    res.redirect('/users/'+ currentUser);
    //temp res.send for
    // res.send('OAUTH SIGNIN WORKED!')
  });

//? DO we want to do a logout button?
// router.get('/logout', function(req, res){
//   req.logout();
//   res.redirect('/');
// });

module.exports = router;
<|endoftext|>