<commit_before>'use strict';

var gulp = require('gulp');
var browserSync = require('browser-sync');
var reload = browserSync.reload;

// load plugins
var $ = require('gulp-load-plugins')();

gulp.task('styles', function () {
    return gulp.src('app/styles/main.scss')
        .pipe($.rubySass({
            style: 'expanded'
        }))
        .pipe($.autoprefixer('last 1 version'))
        .pipe(gulp.dest('.tmp/styles'))
        .pipe(reload({stream: true}))
        .pipe($.size());
});

gulp.task('scripts', function () {
    return gulp.src('app/scripts/**/*.js')
        .pipe($.jshint())
        .pipe($.jshint.reporter($.jshintStylish))
        .pipe(reload({stream: true, once: true}))
        .pipe($.size());
});

gulp.task('html', ['styles', 'scripts'], function () {
    var jsFilter = $.filter('**/*.js');
    var cssFilter = $.filter('**/*.css');

    return gulp.src('app/*.html')
        .pipe($.useref.assets())
        .pipe(jsFilter)
        .pipe($.uglify())
        .pipe(jsFilter.restore())
        .pipe(cssFilter)
        .pipe($.csso())
        .pipe(cssFilter.restore())
        .pipe($.useref.restore())
        .pipe($.useref())
        .pipe(gulp.dest('dist'))
        .pipe($.size());
});

gulp.task('images', function () {
    return gulp.src('app/images/**/*')
        .pipe($.cache($.imagemin({
            optimizationLevel: 3,
            progressive: true,
            interlaced: true
        })))
        .pipe(gulp.dest('dist/images'))
        .pipe(reload({stream: true, once: true}))
        .pipe($.size());
});

gulp.task('fonts', function () {
    return $.bowerFiles()
        .pipe($.filter('**/*.{eot,svg,ttf,woff}'))
        .pipe($.flatten())
        .pipe(gulp.dest('dist/fonts'))
        .pipe($.size());
});

gulp.task('clean', function () {
    return gulp.src(['.tmp', 'dist'], { read: false }).pipe($.clean());
});

gulp.task('build', ['html', 'images', 'fonts']);

gulp.task('default', ['clean'], function () {
    gulp.start('build');
});

gulp.task('serve', ['styles'], function () {
    browserSync.init(null, {
        server: {
            baseDir: ['app', '.tmp'],
            directory: true
        },
        debugInfo: false,
        open: false,
        host: 'localhost'
    }, function (err, bs) {
        require('opn')(bs.options.url);
        console.log('Started web server on ' + bs.options.url);
    });
});

gulp.task('watch', ['serve'], function () {

    gulp.watch(['app/*.html'], reload);

    gulp.watch('app/styles/**/*.scss', ['styles']);
    gulp.watch('app/scripts/**/*.js', ['scripts']);
    gulp.watch('app/images/**/*', ['images']);
    gulp.watch('bower.json', ['wiredep']);
});
<commit_msg>Close GH-13: Add PageSpeed task. Closes #12.<commit_after>'use strict';

var gulp = require('gulp');
var browserSync = require('browser-sync');
var reload = browserSync.reload;

// load plugins
var $ = require('gulp-load-plugins')();

// hosted URL for your page
var hostedUrl = '';

gulp.task('styles', function () {
    return gulp.src('app/styles/main.scss')
        .pipe($.rubySass({
            style: 'expanded'
        }))
        .pipe($.autoprefixer('last 1 version'))
        .pipe(gulp.dest('.tmp/styles'))
        .pipe(reload({stream: true}))
        .pipe($.size());
});

gulp.task('scripts', function () {
    return gulp.src('app/scripts/**/*.js')
        .pipe($.jshint())
        .pipe($.jshint.reporter($.jshintStylish))
        .pipe(reload({stream: true, once: true}))
        .pipe($.size());
});

gulp.task('html', ['styles', 'scripts'], function () {
    var jsFilter = $.filter('**/*.js');
    var cssFilter = $.filter('**/*.css');

    return gulp.src('app/*.html')
        .pipe($.useref.assets())
        .pipe(jsFilter)
        .pipe($.uglify())
        .pipe(jsFilter.restore())
        .pipe(cssFilter)
        .pipe($.csso())
        .pipe(cssFilter.restore())
        .pipe($.useref.restore())
        .pipe($.useref())
        .pipe(gulp.dest('dist'))
        .pipe($.size());
});

gulp.task('images', function () {
    return gulp.src('app/images/**/*')
        .pipe($.cache($.imagemin({
            optimizationLevel: 3,
            progressive: true,
            interlaced: true
        })))
        .pipe(gulp.dest('dist/images'))
        .pipe(reload({stream: true, once: true}))
        .pipe($.size());
});

gulp.task('fonts', function () {
    return $.bowerFiles()
        .pipe($.filter('**/*.{eot,svg,ttf,woff}'))
        .pipe($.flatten())
        .pipe(gulp.dest('dist/fonts'))
        .pipe($.size());
});

gulp.task('pagespeed', function () {
    opn('https://developers.google.com/speed/pagespeed/insights/?url=' + encodeURIComponent(hostedUrl));
});

gulp.task('clean', function () {
    return gulp.src(['.tmp', 'dist'], { read: false }).pipe($.clean());
});

gulp.task('build', ['html', 'images', 'fonts']);

gulp.task('default', ['clean'], function () {
    gulp.start('build');
});

gulp.task('serve', ['styles'], function () {
    browserSync.init(null, {
        server: {
            baseDir: ['app', '.tmp'],
            directory: true
        },
        debugInfo: false,
        open: false,
        host: 'localhost'
    }, function (err, bs) {
        require('opn')(bs.options.url);
        console.log('Started web server on ' + bs.options.url);
    });
});

gulp.task('watch', ['serve'], function () {

    gulp.watch(['app/*.html'], reload);

    gulp.watch('app/styles/**/*.scss', ['styles']);
    gulp.watch('app/scripts/**/*.js', ['scripts']);
    gulp.watch('app/images/**/*', ['images']);
    gulp.watch('bower.json', ['wiredep']);
});
<|endoftext|>


<commit_before>let path = require('path');
let cp = require('child_process');
let semver = require('semver');
let semverRegex = require('semver-regex');
let dargs = require('dargs');
let through = require('through2');
let concat = require('concat-stream');
import * as utils from './utils';
let which = utils.denodeify(require('which'));

const BIN = 'sass-convert';
const MINVERS = '>=3.4.5';

/**
 * Execute command in a child process.
 *
 * @see {@link http://nodejs.org/api/child_process.html}
 * @param {String} command
 * @param {Array} args
 * @return {Promise}
 */
function exec(command, ...args) {
  let deferred = utils.defer();
  let childProcess;

  args.push((err, stdout, stderr) => {
    if (err) {
      deferred.reject(Object.assign(err, {
        message: `${err.message} "${command}" exited with error code ${err.code}`,
        stdout,
        stderr,
      }));
    } else {
      deferred.resolve({
        childProcess,
        stdout,
        stderr,
      });
    }
  });

  childProcess = cp.exec(command, ...args);

  // process.nextTick(() => {
  //   deferred.notify(childProcess);
  // });

  return deferred.promise;
}

/**
 * Custom error for binary check.
 *
 * @param {String} message
 */
class BinaryError extends Error {
  constructor(message) {
    super(message);
    // http://bit.ly/1yMzARU
    this.message = message || `Could not find any executable for "${BIN}". Operation Aborted.`;
  }
  get name() {
    return 'BinaryError';
  }
}

/**
 * Custom error for version check.
 *
 * @param {String} message
 */
class VersionError extends Error {
  constructor(message) {
    super(message);
    // http://bit.ly/1yMzARU
    this.message = message || `Invalid "${BIN}" version, must be ${MINVERS}`;
  }
  get name() {
    return 'VersionError';
  }
}

/**
 * Check whether passed binary (Gem) is in $PATH,
 * and check its version.
 *
 * @param {String} bin
 * @return {Promise}
 */
function checkBinary(bin) {

  /**
   * Check for binary min-version.
   *
   * @param {String} str
   * @return {Boolean}
   */
  function checkVersion(str) {
    let version = str.match(semverRegex())[0];
    return semver.satisfies(version, MINVERS);
  }

  /**
   * Check for global binary and version.
   *
   * @return {Promise}
   */
  function checkGlobal() {
    return which(bin)
      .then(
        () => exec(`${bin} -v`),
        () => { throw new BinaryError(); }
      )
      .then(res => {
        if (!checkVersion(res.stdout)) {
          throw new VersionError();
        }
      });
  }

  /**
   * Check for bundled binary and version.
   *
   * @return {Promise}
   */
  function checkBundle() {
    return which('bundle')
      .then(() => exec(`bundle exec ${bin} -v`))
      .then(res => {
        if (!checkVersion(res.stdout)) {
          throw new VersionError();
        }
        return { bundler: true };
      }, err => { throw new BinaryError(); });
  }

  return checkBundle()
    .then(null, checkGlobal);
}

/**
 * Run binary checks only once.
 *
 * @return {Promise}
 */
function checkBinaryCache() {
  if (!('promise' in checkBinaryCache)) {
    checkBinaryCache.promise = checkBinary(BIN);
  }

  return checkBinaryCache.promise;
}

class Converter {
  constructor(options) {
    this.options = options || {};
    this.bundler = false;
  }

  /**
   * Format the `sass-convert` command string.
   *
   * @return {Object}
   */
  command() {
    let cmd = `${this.bundler ? 'bundle exec ' : ''}sass-convert`;

    // Add required args.
    let options = Object.assign(this.options, {
      'stdin': true,
      'no-cache': true,
    });

    // Filter unwanted or erroneous args.
    let allowed = [
      'from',
      'to',
      'dasherize',
      'indent',
      'old',
      'default-encoding',
      'unix-newlines',
      'stdin',
      'no-cache',
    ];

    let args = dargs(options, [], allowed);

    return { cmd, args };
  }

  /**
   * Returns whether chunk is eligible for convertion.
   *
   * @param {Buffer} chunk - Vinyl file
   * @return {Boolean}
   */
  isTransformable(chunk) {
    let ext = path.extname(chunk.path);
    return chunk.isBuffer() && ext.endsWith(this.options.from);
  }

  /**
   * Convert file Buffer through `sass-convert` binary.
   *
   * @param {Buffer} file - Vinyl file
   * @param {String} enc - encoding
   */
  convertFile(file, enc) {
    let deferred = utils.defer();
    let { cmd, args } = this.cmdCache = this.cmdCache || this.command();
    let child = cp.spawn(cmd, args);
    let converted;

    file.pipe(child.stdin);

    child.stdout.pipe(concat(data => {
      converted = data;
    }));

    child.on('error', err => {
      deferred.reject(err);
    });

    child.on('close', (code, signal) => {
      if (code === 0) {
        deferred.resolve(converted);
      }
    });

    return deferred.promise;
  }

  /**
   * Returns a transform stream meant to be piped to a stream
   * of Sass, SCSS or CSS files. Apply convertion if matches.
   *
   * @return {Object} - Stream
   */
  stream() {
    let self = this;

    return through.obj(function (chunk, enc, cb) {
      let stream = this;

      if (!self.isTransformable(chunk)) {
        // Pass-through.
        return cb(null, chunk);
      }

      // Matches `from`, let's convert it.
      checkBinaryCache()
        .then(res => {
          self.bundler = res ? res.bundler : false;

          return self.convertFile(chunk, enc);
        })
        .then(converted => {
          chunk.contents = new Buffer(converted);

          cb(null, chunk);
        }, err => {
          stream.emit('error', err);

          if (self.options.force) {
            // Continue stream chain,
            // but don't pass unconverted chunks.
            return cb();
          }

          // Stop stream chain.
          stream.destroy();
          stream.emit('end');
        });
    });
  }
}

module.exports = function (options) {
  return new Converter(options).stream();
};

// Expose custom error constructors.
module.exports.BinaryError = BinaryError;
module.exports.VersionError = VersionError;
<commit_msg>Improve code style<commit_after>let path = require('path');
let cp = require('child_process');
let semver = require('semver');
let semverRegex = require('semver-regex');
let dargs = require('dargs');
let through = require('through2');
let concat = require('concat-stream');
import * as utils from './utils';
let which = utils.denodeify(require('which'));

const BIN = 'sass-convert';
const MINVERS = '>=3.4.5';

/**
 * Execute command in a child process.
 *
 * @see {@link http://nodejs.org/api/child_process.html}
 * @param {String} command
 * @param {Array} args
 * @return {Promise}
 */
function exec(command, ...args) {
  let deferred = utils.defer();
  let childProcess;

  args.push((err, stdout, stderr) => {
    if (err) {
      Object.assign(err, {
        message: `${err.message} \`${command}\` exited with error code ${err.code}`,
        stdout,
        stderr,
      });

      deferred.reject(err);
    }
    else {
      deferred.resolve({
        childProcess,
        stdout,
        stderr,
      });
    }
  });

  childProcess = cp.exec(command, ...args);

  // process.nextTick(() => {
  //   deferred.notify(childProcess);
  // });

  return deferred.promise;
}

/**
 * Custom error for binary check.
 *
 * @param {String} message
 */
class BinaryError extends Error {
  constructor(message) {
    super(message);
    // http://bit.ly/1yMzARU
    this.message = message || `Could not find any executable for "${BIN}". Operation Aborted.`;
  }
  get name() {
    return 'BinaryError';
  }
}

/**
 * Custom error for version check.
 *
 * @param {String} message
 */
class VersionError extends Error {
  constructor(message) {
    super(message);
    // http://bit.ly/1yMzARU
    this.message = message || `Invalid "${BIN}" version, must be ${MINVERS}`;
  }
  get name() {
    return 'VersionError';
  }
}

/**
 * Check whether passed binary (Gem) is in $PATH,
 * and check its version.
 *
 * @param {String} bin
 * @return {Promise}
 */
function checkBinary(bin) {

  /**
   * Check for binary min-version.
   *
   * @param {String} str
   * @return {Boolean}
   */
  function checkVersion(str) {
    let version = str.match(semverRegex())[0];
    return semver.satisfies(version, MINVERS);
  }

  /**
   * Check for global binary and version.
   *
   * @return {Promise}
   */
  function checkGlobal() {
    return which(bin)
      .then(
        () => exec(`${bin} -v`),
        () => { throw new BinaryError(); }
      )
      .then(res => {
        if (!checkVersion(res.stdout)) {
          throw new VersionError();
        }
      });
  }

  /**
   * Check for bundled binary and version.
   *
   * @return {Promise}
   */
  function checkBundle() {
    return which('bundle')
      .then(() => exec(`bundle exec ${bin} -v`))
      .then(res => {
        if (!checkVersion(res.stdout)) {
          throw new VersionError();
        }
        return { bundler: true };
      }, err => { throw new BinaryError(); });
  }

  return checkBundle()
    .then(null, checkGlobal);
}

/**
 * Run binary checks only once.
 *
 * @return {Promise}
 */
function checkBinaryCache() {
  if (!('promise' in checkBinaryCache)) {
    checkBinaryCache.promise = checkBinary(BIN);
  }

  return checkBinaryCache.promise;
}

class Converter {
  constructor(options) {
    this.options = options || {};
    this.bundler = false;
  }

  /**
   * Format the `sass-convert` command string.
   *
   * @return {Object}
   */
  command() {
    let cmd = `${this.bundler ? 'bundle exec ' : ''}sass-convert`;

    // Add required args.
    let options = Object.assign(this.options, {
      'stdin': true,
      'no-cache': true,
    });

    // Filter unwanted or erroneous args.
    let allowed = [
      'from',
      'to',
      'dasherize',
      'indent',
      'old',
      'default-encoding',
      'unix-newlines',
      'stdin',
      'no-cache',
    ];

    let args = dargs(options, [], allowed);

    return { cmd, args };
  }

  /**
   * Returns whether chunk is eligible for convertion.
   *
   * @param {Buffer} chunk - Vinyl file
   * @return {Boolean}
   */
  isTransformable(chunk) {
    let ext = path.extname(chunk.path);
    return chunk.isBuffer() && ext.endsWith(this.options.from);
  }

  /**
   * Convert file Buffer through `sass-convert` binary.
   *
   * @param {Buffer} file - Vinyl file
   * @param {String} enc - encoding
   */
  convertFile(file, enc) {
    let deferred = utils.defer();
    let { cmd, args } = this.cmdCache || (this.cmdCache = this.command());
    let child = cp.spawn(cmd, args);
    let result;

    file.pipe(child.stdin);

    child.stdout.pipe(concat(data => {
      result = data;
    }));

    child.on('error', deferred.reject);

    child.on('close', (code, signal) => {
      if (code === 0) {
        deferred.resolve(result);
      }
    });

    return deferred.promise;
  }

  /**
   * Returns a transform stream meant to be piped to a stream
   * of Sass, SCSS or CSS files. Apply convertion if matches.
   *
   * @return {Object} - Stream
   */
  stream() {
    let self = this;

    return through.obj(function (chunk, enc, cb) {
      let stream = this;

      if (!self.isTransformable(chunk)) {
        // Pass-through.
        return cb(null, chunk);
      }

      // Matches `from`, let's convert it.
      checkBinaryCache()
        .then(res => {
          self.bundler = res ? res.bundler : false;

          return self.convertFile(chunk, enc);
        })
        .then(converted => {
          chunk.contents = new Buffer(converted);

          cb(null, chunk);
        }, err => {
          stream.emit('error', err);

          if (self.options.force) {
            // Continue stream chain,
            // but don't pass unconverted chunks.
            return cb();
          }

          // Stop stream chain.
          stream.destroy();
          stream.emit('end');
        });
    });
  }
}

module.exports = function (options) {
  return new Converter(options).stream();
};

// Expose custom error constructors.
module.exports.BinaryError = BinaryError;
module.exports.VersionError = VersionError;
<|endoftext|>


<commit_before>(function(ADL){
   ADL.activityTypes = {
      "assessment": "http://adlnet.gov/expapi/activities/assessment",
      "attempt": "http://adlnet.gov/expapi/activities/attempt",
      "course": "http://adlnet.gov/expapi/activities/course",
      "file": "http://adlnet.gov/expapi/activities/file",
      "interaction": "http://adlnet.gov/expapi/activities/interaction",
      "lesson": "http://adlnet.gov/expapi/activities/lesson",
      "link": "http://adlnet.gov/expapi/activities/link",
      "media": "http://adlnet.gov/expapi/activities/media",
      "meeting": "http://adlnet.gov/expapi/activities/meeting",
      "module": "http://adlnet.gov/expapi/activities/module",
      "objective": "http://adlnet.gov/expapi/activities/objective",
      "performance": "http://adlnet.gov/expapi/activities/performance",
      "profile": "http://adlnet.gov/expapi/activities/profile",
      "question": "http://adlnet.gov/expapi/activities/question",
      "simulation": "http://adlnet.gov/expapi/activities/simulation"
   };
}(window.ADL = window.ADL || {}));
<commit_msg>Resolves #152, adds support for cmi.interaction activity type<commit_after>(function(ADL){
   ADL.activityTypes = {
      "assessment": "http://adlnet.gov/expapi/activities/assessment",
      "attempt": "http://adlnet.gov/expapi/activities/attempt",
      "course": "http://adlnet.gov/expapi/activities/course",
      "file": "http://adlnet.gov/expapi/activities/file",
      "cmiInteraction": "http://adlnet.gov/expapi/activities/cmi.interaction",
      "interaction": "http://adlnet.gov/expapi/activities/interaction",
      "lesson": "http://adlnet.gov/expapi/activities/lesson",
      "link": "http://adlnet.gov/expapi/activities/link",
      "media": "http://adlnet.gov/expapi/activities/media",
      "meeting": "http://adlnet.gov/expapi/activities/meeting",
      "module": "http://adlnet.gov/expapi/activities/module",
      "objective": "http://adlnet.gov/expapi/activities/objective",
      "performance": "http://adlnet.gov/expapi/activities/performance",
      "profile": "http://adlnet.gov/expapi/activities/profile",
      "question": "http://adlnet.gov/expapi/activities/question",
      "simulation": "http://adlnet.gov/expapi/activities/simulation"
   };
}(window.ADL = window.ADL || {}));
<|endoftext|>


<commit_before>/**
 * Tangram
 * Copyright 2010 Baidu Inc. All rights reserved.
 * @path:data/dataSource.js
 * @author:walter
 * @version:1.0.0
 * @date:2010-11-30
 */

///import baidu.data;

/**
 * @namespace 定义命名空间
 */
baidu.data.dataSource = baidu.dataSource = baidu.data.dataSource || {};
<commit_msg>修正 dataSource 的位置<commit_after>/**
 * Tangram
 * Copyright 2010 Baidu Inc. All rights reserved.
 * @path:data/dataSource.js
 * @author:walter
 * @version:1.0.0
 * @date:2010-11-30
 */

///import baidu.data;

/**
 * 数据源类
 * @namespace baidu.data.dataSource
 */
baidu.data.dataSource = baidu.dataSource = baidu.data.dataSource || {};
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp'),
  concat = require('gulp-concat'),
  uglify = require('gulp-uglify'),
  rename = require('gulp-rename'),
    sass = require('gulp-sass'),
    maps = require('gulp-sourcemaps');

gulp.task('concatScripts', function() {
  return gulp.src(['./js/jquery.js', './js/sticky/jquery.sticky.js', './js/main.js'])
   .pipe(maps.init())
    .pipe(concat('app.js'))
   .pipe(maps.write('./'))
    .pipe(gulp.dest('./js'));
});

gulp.task('uglifyScripts', function() {
  return gulp.src('./js/app.js')
    .pipe(rename('app.min.js'))
    .pipe(uglify())
    .pipe(gulp.dest('./js'))
    .on('error', console.log);
});

gulp.task('compileSass', function() {
  return gulp.src("scss/application.scss")
      .pipe(maps.init())
      .pipe(sass())
      .pipe(maps.write('./'))
      .pipe(gulp.dest('css'));
});

gulp.task('watchFiles', function() {
  gulp.watch('scss/**/*.scss', ['compileSass']);
  gulp.watch('js/main.js', ['concatScripts']);
})

gulp.task('clean', function() {
  del(['dist', 'css/application.css*', 'js/app*.js*']);
});

gulp.task('serve', ['watchFiles']);

gulp.task("default", ["clean"], function() {
  gulp.start('build');
});

<commit_msg>final app<commit_after>'use strict';

var gulp = require('gulp'),
  concat = require('gulp-concat'),
  uglify = require('gulp-uglify'),
  rename = require('gulp-rename'),
    sass = require('gulp-sass'),
    maps = require('gulp-sourcemaps');

gulp.task('concatScripts', function() {
  return gulp.src(['./js/jquery.js', './js/sticky/jquery.sticky.js', './js/main.js'])
   .pipe(maps.init())
    .pipe(concat('app.js'))
   .pipe(maps.write('./'))
    .pipe(gulp.dest('./js'));
});

gulp.task('uglifyScripts', function() {
  return gulp.src('./js/app.js')
    .pipe(rename('app.min.js'))
    .pipe(uglify())
    .pipe(gulp.dest('./js'))
    .on('error', console.log);
});

gulp.task('compileSass', function() {
  return gulp.src("scss/application.scss")
      .pipe(maps.init())
      .pipe(sass())
      .pipe(maps.write('./'))
      .pipe(gulp.dest('css'));
});

gulp.task('watchFiles', function() {
  gulp.watch('scss/**/*.scss', ['compileSass']);
  gulp.watch('js/main.js', ['concatScripts']);
})

gulp.task('clean', function() {
  del(['dist', 'css/application.css*', 'js/app*.js*']);
});

gulp.task("build", ['minifyScripts', 'compileSass'], function() {
  return gulp.src(["css/application.css", "js/app.min.js", 'index.html',
                   "img/**", "fonts/**"], { base: './'})
            .pipe(gulp.dest('dist'));

gulp.task('serve', ['watchFiles']);

gulp.task("default", ["clean"], function() {
  gulp.start('build');
});

<|endoftext|>


<commit_before>var config = {};

config.slack_token = "";
config.slack_bot_name = "ypirqui";

config.bot_random = 0.80;

module.exports = config;<commit_msg>Added fringe cases for qu[aou] and z[aeou]. Feedback for replies. Minimum message length to encode is now configurable.<commit_after>var config = {};

config.slack_token = "";
config.slack_bot_name = "ypirqui";

config.bot_random = 0.80;

config.bot_min_string_length = 9;

module.exports = config;<|endoftext|>


<commit_before>// Dependencies
var request = require('request');

// Includes
var login = require('./util/login.js'),
  getSession = require('./util/getSession.js'),
  getCurrentUser = require('./util/getCurrentUser.js'),
  setRank = require('./setRank.js'),
  getRoles = require('./util/getRoles.js'),
  getToken = require('./util/getToken.js'),
  getInputs = require('./util/getInputs.js'),
  getVerificationInputs = require('./util/getVerificationInputs.js'),
  getRankInGroup = require('./util/getRankInGroup.js'),
  getRolesetInGroupWithJar = require('./util/getRolesetInGroupWithJar.js'),
  exile = require('./exile.js'),
  message = require('./message.js'),
  handleJoinRequest = require('./handleJoinRequest.js').handle,
  getRequestId = require('./handleJoinRequest.js').request,
  getUserId = require('./util/getUserId.js'),
  shout = require('./shout.js'),
  post = require('./post.js');

var cache = require('./cache/index.js');

var settings = require('../settings.json');

// Vars
var _jar = request.jar(); // Default cookie jar
var _cache = cache.new([{
  name: 'XCSRF',
  expire: settings.cache.XCSRF
}, {
  name: 'Roles',
  expire: settings.cache.Roles
}]);

// Define
function makeCallbackArray(options, success, failure, always) {
  return {success: options.success || success, failure: options.failure || failure, always: options.always || options.callback || always};
}

exports.login = function(options, password, jar, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  login(options.jar || jar || _jar, options.username || options, options.password || password, callbacks);
};

exports.getSession = function(options) {
  getSession(options.jar || options || _jar);
};

exports.getCurrentUser = function(options, jar, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  getCurrentUser(options.jar || jar || _jar, options.option || typeof options === 'string' && options, callbacks);
};

exports.getRoles = function(options, rank, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  getRoles(options.group || options, options.rank || rank, callbacks);
};

exports.getToken = function(options, jar, callback, failure) {
  var callbacks = {failure: options.failure || failure};
  getToken(options.jar || jar || _jar, options.url || options, callback, callbacks);
};

function setRankMain(options, target, roleset, token, jar, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  jar = options.jar || jar || _jar;
  var url = 'http://www.roblox.com/groups/api/change-member-rank?groupId=' + options.group || options + '&newRoleSetId=' + options.roleset || roleset + '&targetUserId=' + options.target || target;
  var run = function(token) {
    setRank(jar, url, token, callbacks);
  };
  if (token)
    run(token);
  else {
    cache.addIf(_cache, 'XCSRF', 'setRank', {
      done: run,
      add: function(done) {
        getToken(jar, url, done, callbacks);
      }
    });
  }
}

exports.setRank = function(options) {
  if (options.rank) {
    getRoles(options.group, options.rank, {success: function(role) {
      options.roleset = role;
      setRankMain(options);
    }, failure: options.failure});
  } else
    setRankMain.apply(undefined, arguments);
};

exports.message = function(options, subject, body, token, jar, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  jar = options.jar || jar || _jar;
  var run = function(token) {
    message(jar, options.recipient || options, options.subject || subject, options.body || body, token, callbacks);
  };
  if (token)
    run(token);
  else {
    cache.addIf(_cache, 'XCSRF', 'message', {
      done: run,
      add: function(done) {
        getToken(jar, 'http://www.roblox.com/messages/send', done, callbacks);
      }
    });
  }
};

exports.shout = function(options, message, jar, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  shout(options.jar || jar || _jar, options.group || options, options.message || message, callbacks);
};

exports.handleJoinRequest = function(options, username, accept, jar, token, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  jar = options.jar || jar || _jar;
  var form = {
    groupJoinRequestId: 0,
    accept: options.accept || accept
  };
  var run = function(token) {
    handleJoinRequest(jar, token, form, callbacks);
  };
  cache.addIf(_cache, 'XCSRF', 'handleJoinRequest', {
    done: run,
    add: function(done) {
      getRequestId(jar, options.group || options, options.username || username, function(id) {
        form.groupJoinRequestId = id;
        getToken(jar, 'http://www.roblox.com/group/handle-join-request', done, callbacks, form);
      }, callbacks);
    }
  });
};

exports.post = function(options, message, jar, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  post(options.jar || jar || _jar, options.group, options.message, callbacks);
};

exports.getRankInGroup = function(options, group, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  getRankInGroup(options.player || options, options.group || group, callbacks);
};

exports.getRolesetInGroup = function(options, group, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  getRankInGroup(options.player || options, options.group || group, {success: function(rank) {
    getRoles(options.group, rank, callbacks);
  }, failure: callbacks.failure});
};

exports.getRolesetInGroupWithJar = function(options, jar, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  getRolesetInGroupWithJar(options.jar || jar || _jar, options.group || options, callbacks);
};

function exileMain(options, json, token, jar, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  var run = function(token) {
    exile(options.jar || jar || _jar, token, json, callbacks);
  };
  if (options.token || token)
    run(options.token || token);
  else {
    cache.addIf(_cache, 'XCSRF', 'exile', {
      done: run,
      add: function(done) {
        getToken(jar, 'http://www.roblox.com/My/Groups.aspx/ExileUserAndDeletePosts', done, callbacks, undefined, json);
      }
    });
  }
}

exports.exile = function(options, target, senderRoleSetId, deleteAllPosts, token, jar, success, failure, always) {
  jar = options.jar || jar || _jar;
  var json = {
    userId: options.target || target,
    deleteAllPostsOption: options.deleteAllPosts || deleteAllPosts || false,
    rolesetId: options.senderRoleSetId || senderRoleSetId,
    selectedGroupId: options.group || options
  };
  if (!options.senderRoleSetId && !senderRoleSetId) {
    var opt = {
      group: options.group || options,
      jar: jar,
      success: function(roleset) {
        json.rolesetId = roleset;
        exileMain(options, json, token, jar, success, failure, always);
      },
      failure: options.failure || failure
    };
    exports.getRolesetInGroupWithJar(opt);
  } else
    exileMain(options, json, token, jar, success, failure, always);
};

exports.getJar = function() {
  return _jar;
};

exports.setJar = function(jar) {
  _jar = jar;
};

exports.getUserId = function(jar) {
  return getUserId(jar);
};

exports.getInputs = function(options, find) {
  return getInputs(options.html || options, options.find || find);
};

exports.getVerificationInputs = function(options) {
  return getVerificationInputs(options.html || options, array);
};
<commit_msg>Fix<commit_after>// Dependencies
var request = require('request');

// Includes
var login = require('./util/login.js'),
  getSession = require('./util/getSession.js'),
  getCurrentUser = require('./util/getCurrentUser.js'),
  setRank = require('./setRank.js'),
  getRoles = require('./util/getRoles.js'),
  getToken = require('./util/getToken.js'),
  getInputs = require('./util/getInputs.js'),
  getVerificationInputs = require('./util/getVerificationInputs.js'),
  getRankInGroup = require('./util/getRankInGroup.js'),
  getRolesetInGroupWithJar = require('./util/getRolesetInGroupWithJar.js'),
  exile = require('./exile.js'),
  message = require('./message.js'),
  handleJoinRequest = require('./handleJoinRequest.js').handle,
  getRequestId = require('./handleJoinRequest.js').request,
  getUserId = require('./util/getUserId.js'),
  shout = require('./shout.js'),
  post = require('./post.js');

var cache = require('./cache/index.js');

var settings = require('../settings.json');

// Vars
var _jar = request.jar(); // Default cookie jar
var _cache = cache.new([{
  name: 'XCSRF',
  expire: settings.cache.XCSRF
}, {
  name: 'Roles',
  expire: settings.cache.Roles
}]);

// Define
function makeCallbackArray(options, success, failure, always) {
  return {success: options.success || success, failure: options.failure || failure, always: options.always || options.callback || always};
}

exports.login = function(options, password, jar, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  login(options.jar || jar || _jar, options.username || options, options.password || password, callbacks);
};

exports.getSession = function(options) {
  getSession(options.jar || options || _jar);
};

exports.getCurrentUser = function(options, jar, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  getCurrentUser(options.jar || jar || _jar, options.option || typeof options === 'string' && options, callbacks);
};

exports.getRoles = function(options, rank, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  getRoles(options.group || options, options.rank || rank, callbacks);
};

exports.getToken = function(options, jar, callback, failure) {
  var callbacks = {failure: options.failure || failure};
  getToken(options.jar || jar || _jar, options.url || options, callback, callbacks);
};

function setRankMain(options, target, roleset, token, jar, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  jar = options.jar || jar || _jar;
  var url = 'http://www.roblox.com/groups/api/change-member-rank?groupId=' + (options.group || options) + '&newRoleSetId=' + (options.roleset || roleset) + '&targetUserId=' + (options.target || target);
  var run = function(token) {
    setRank(jar, url, token, callbacks);
  };
  if (token)
    run(token);
  else {
    cache.addIf(_cache, 'XCSRF', 'setRank', {
      done: run,
      add: function(done) {
        getToken(jar, url, done, callbacks);
      }
    });
  }
}

exports.setRank = function(options) {
  if (options.rank) {
    getRoles(options.group, options.rank, {success: function(role) {
      options.roleset = role;
      setRankMain(options);
    }, failure: options.failure});
  } else
    setRankMain.apply(undefined, arguments);
};

exports.message = function(options, subject, body, token, jar, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  jar = options.jar || jar || _jar;
  var run = function(token) {
    message(jar, options.recipient || options, options.subject || subject, options.body || body, token, callbacks);
  };
  if (token)
    run(token);
  else {
    cache.addIf(_cache, 'XCSRF', 'message', {
      done: run,
      add: function(done) {
        getToken(jar, 'http://www.roblox.com/messages/send', done, callbacks);
      }
    });
  }
};

exports.shout = function(options, message, jar, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  shout(options.jar || jar || _jar, options.group || options, options.message || message, callbacks);
};

exports.handleJoinRequest = function(options, username, accept, jar, token, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  jar = options.jar || jar || _jar;
  var form = {
    groupJoinRequestId: 0,
    accept: options.accept || accept
  };
  var run = function(token) {
    handleJoinRequest(jar, token, form, callbacks);
  };
  cache.addIf(_cache, 'XCSRF', 'handleJoinRequest', {
    done: run,
    add: function(done) {
      getRequestId(jar, options.group || options, options.username || username, function(id) {
        form.groupJoinRequestId = id;
        getToken(jar, 'http://www.roblox.com/group/handle-join-request', done, callbacks, form);
      }, callbacks);
    }
  });
};

exports.post = function(options, message, jar, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  post(options.jar || jar || _jar, options.group, options.message, callbacks);
};

exports.getRankInGroup = function(options, group, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  getRankInGroup(options.player || options, options.group || group, callbacks);
};

exports.getRolesetInGroup = function(options, group, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  getRankInGroup(options.player || options, options.group || group, {success: function(rank) {
    getRoles(options.group, rank, callbacks);
  }, failure: callbacks.failure});
};

exports.getRolesetInGroupWithJar = function(options, jar, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  getRolesetInGroupWithJar(options.jar || jar || _jar, options.group || options, callbacks);
};

function exileMain(options, json, token, jar, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  var run = function(token) {
    exile(options.jar || jar || _jar, token, json, callbacks);
  };
  if (options.token || token)
    run(options.token || token);
  else {
    cache.addIf(_cache, 'XCSRF', 'exile', {
      done: run,
      add: function(done) {
        getToken(jar, 'http://www.roblox.com/My/Groups.aspx/ExileUserAndDeletePosts', done, callbacks, undefined, json);
      }
    });
  }
}

exports.exile = function(options, target, senderRoleSetId, deleteAllPosts, token, jar, success, failure, always) {
  jar = options.jar || jar || _jar;
  var json = {
    userId: options.target || target,
    deleteAllPostsOption: options.deleteAllPosts || deleteAllPosts || false,
    rolesetId: options.senderRoleSetId || senderRoleSetId,
    selectedGroupId: options.group || options
  };
  if (!options.senderRoleSetId && !senderRoleSetId) {
    var opt = {
      group: options.group || options,
      jar: jar,
      success: function(roleset) {
        json.rolesetId = roleset;
        exileMain(options, json, token, jar, success, failure, always);
      },
      failure: options.failure || failure
    };
    exports.getRolesetInGroupWithJar(opt);
  } else
    exileMain(options, json, token, jar, success, failure, always);
};

exports.getJar = function() {
  return _jar;
};

exports.setJar = function(jar) {
  _jar = jar;
};

exports.getUserId = function(jar) {
  return getUserId(jar);
};

exports.getInputs = function(options, find) {
  return getInputs(options.html || options, options.find || find);
};

exports.getVerificationInputs = function(options) {
  return getVerificationInputs(options.html || options);
};
<|endoftext|>


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

var env = process.env.NODE_ENV || 'development';

var app = express();
var config = require('./server/config/config')[env];

require('./server/config/express')(app, config);
require('./server/config/mongoose')(config);
require('./server/config/passport')();
require('./server/config/router')(app);

app.listen(config.PORT);
console.log('Server running on port: ' + config.PORT);
console.log('Environment type: %s', env);<commit_msg>Minor changes<commit_after>var express = require('express');

var env = process.env.NODE_ENV || 'development';

console.log(process);
console.log(process.env);
console.log(process.env.NODE_ENV);

var app = express();
var config = require('./server/config/config')[env];

require('./server/config/express')(app, config);
require('./server/config/mongoose')(config);
require('./server/config/passport')();
require('./server/config/router')(app);

app.listen(config.PORT);
console.log('Server running on port: ' + config.PORT);
console.log('Environment type: %s', env);<|endoftext|>


<commit_before>/**
 * T'MediaArt library for JavaScript
 *  - MajVj extension - frame plugin - image -
 * @param options options (See MajVj.prototype.create)
 */
MajVj.frame.image = function(options) {
  this._screen = options.screen;
  this._mv = options.mv;
  this._width = options.width;
  this._height = options.height;
  this.properties = {
    scroll: [0, 0],  // base point in the original image pixel range
    scale: 1.0,
    volume: 1.0
  };
  this._texture = null;

  this._program = this._screen.createProgram(
    this._screen.compileShader(Tma3DScreen.VERTEX_SHADER,
      MajVj.frame.image._vertexShader),
    this._screen.compileShader(Tma3DScreen.FRAGMENT_SHADER,
      MajVj.frame.image._fragmentShader));
  this._coords = this._screen.createBuffer([0, 0, 0, 1, 1, 1, 1, 0])
  if (options.url) {
    MajVj.loadImageFrom(options.url).then(image => {
      this._texture = this._screen.createTexture(image, true);
    });
  }
};

// Shader programs.
MajVj.frame.image._vertexShader = null;
MajVj.frame.image._fragmentShader = null;

/**
 * Loads resource asynchronously.
 * @return a Promise object
 */
MajVj.frame.image.load = function() {
  return new Promise(function(resolve, reject) {
    Promise.all([
      MajVj.loadShader('frame', 'image', 'shaders.html', 'vertex'),
      MajVj.loadShader('frame', 'image', 'shaders.html', 'fragment')
    ]).then(function(results) {
      MajVj.frame.image._vertexShader = results[0];
      MajVj.frame.image._fragmentShader = results[1];
      resolve();
    }, function(error) {
      tma.log(error);
    });
  });
};

/**
 * Handles screen resize.
 * @param aspect screen aspect ratio
 */
MajVj.frame.image.prototype.onresize = function(aspect) {
  var size = this._mv.size();
  this._width = size.width;
  this._height = size.height;
};

/**
 * Draws a frame.
 * @param delta delta time from the last rendering
 */
MajVj.frame.image.prototype.draw = function(delta) {
  if (!this._texture)
    return;
  this._program.setAttributeArray('aCoord', this._coords, 0, 2, 0);
  this._program.setUniformVector('uScale', [
    this._texture.width / this._width * this.properties.scale,
    this._texture.height / this._height * this.properties.scale
  ]);
  this._program.setUniformVector('uOffset', [
    this.properties.scroll[0] / this._width,
    this.properties.scroll[1] / this._height
  ]);
  this._program.setUniformVector('uVolume', [this.properties.volume]);
  this._program.setTexture('uTexture', this._texture);
  this._program.drawArrays(Tma3DScreen.MODE_TRIANGLE_FAN, 0, 4);
};
<commit_msg>MajVj image frame: support to take an image object<commit_after>/**
 * T'MediaArt library for JavaScript
 *  - MajVj extension - frame plugin - image -
 * @param options options (See MajVj.prototype.create)
 */
MajVj.frame.image = function(options) {
  this._screen = options.screen;
  this._mv = options.mv;
  this._width = options.width;
  this._height = options.height;
  this.properties = {
    scroll: [0, 0],  // base point in the original image pixel range
    scale: 1.0,
    volume: 1.0
  };
  this._texture = null;

  this._program = this._screen.createProgram(
    this._screen.compileShader(Tma3DScreen.VERTEX_SHADER,
      MajVj.frame.image._vertexShader),
    this._screen.compileShader(Tma3DScreen.FRAGMENT_SHADER,
      MajVj.frame.image._fragmentShader));
  this._coords = this._screen.createBuffer([0, 0, 0, 1, 1, 1, 1, 0])
  if (options.url) {
    MajVj.loadImageFrom(options.url).then(image => {
      this._texture = this._screen.createTexture(image, true);
    });
  } else if (options.image) {
    this._texture = this._screen.createTexture(options.image, true);
  }
};

// Shader programs.
MajVj.frame.image._vertexShader = null;
MajVj.frame.image._fragmentShader = null;

/**
 * Loads resource asynchronously.
 * @return a Promise object
 */
MajVj.frame.image.load = function() {
  return new Promise(function(resolve, reject) {
    Promise.all([
      MajVj.loadShader('frame', 'image', 'shaders.html', 'vertex'),
      MajVj.loadShader('frame', 'image', 'shaders.html', 'fragment')
    ]).then(function(results) {
      MajVj.frame.image._vertexShader = results[0];
      MajVj.frame.image._fragmentShader = results[1];
      resolve();
    }, function(error) {
      tma.log(error);
    });
  });
};

/**
 * Handles screen resize.
 * @param aspect screen aspect ratio
 */
MajVj.frame.image.prototype.onresize = function(aspect) {
  var size = this._mv.size();
  this._width = size.width;
  this._height = size.height;
};

/**
 * Draws a frame.
 * @param delta delta time from the last rendering
 */
MajVj.frame.image.prototype.draw = function(delta) {
  if (!this._texture)
    return;
  this._program.setAttributeArray('aCoord', this._coords, 0, 2, 0);
  this._program.setUniformVector('uScale', [
    this._texture.width / this._width * this.properties.scale,
    this._texture.height / this._height * this.properties.scale
  ]);
  this._program.setUniformVector('uOffset', [
    this.properties.scroll[0] / this._width,
    this.properties.scroll[1] / this._height
  ]);
  this._program.setUniformVector('uVolume', [this.properties.volume]);
  this._program.setTexture('uTexture', this._texture);
  this._program.drawArrays(Tma3DScreen.MODE_TRIANGLE_FAN, 0, 4);
};
<|endoftext|>


<commit_before>
'use strict';

const config = require('./_gms/parseConfig.js');
const path = require('path');
const gulp = require('gulp');
const watch = require('gulp-watch');
const mcss = require('gulp-mcs');
const nodemon = require('gulp-nodemon');
const lr = require('tiny-lr')();
const iconfont = require('gulp-iconfont');
const iconfontCss = require('gulp-iconfont-css');
const gulpSequence = require('gulp-sequence').use(gulp);
const logger = require('./_gms/logger.js');
const _ = require('./_gms/util.js');
const express = require('express');
let app = express();

let allfms = config.allfms.slice();
allfms = allfms.map(function(af) {
    return path.join(config.fmSrc, af);
});

let runTimestamp = Math.round(Date.now()/1000);

// -------- 生成项目模板 ----------------
gulp.task('init', () => {
    _.mkdirs();
});

// -------- 服务器 ----------------
// nodemon 自动重启
// 自动刷新
gulp.task('server', () => {
    nodemon({
        script: './_gms/server.js',
        ignore: ['node_modules/', 'src/', 'dist/', 'gulpfile.js']
    }).on('restart', function() {
        logger.info('\n server restarted.. ');
    });
    startLivereload();
    gulp.watch(config.server.livereload.concat(_.handleUrlPath(config.distPath) + '/**/*.html'), notifyLivereload);
});

function startLivereload() {
    lr.listen(35729, function() {
        logger.muted('livereload listen at port ' + 35729);
    });
}
function notifyLivereload(event) {
    let fileName = path.relative(config.server.root, event.path);
    lr.changed({
        body: {
            files: [fileName]
        }
    });
}

// fmpp编译freemarker
// 第一次会把template下的ftl全部编译
// 之后watch改变的文件
gulp.task('fmpp:compile', () => {
    _.travelRouters();
});

gulp.task('fmpp', ['fmpp:compile'], () => {
    gulp.watch(allfms.concat(_.handleUrlPath(config.syncPath) + '/**/*.tdd'), (event) => {
        let pathname = event.path;
        let ext = path.extname(pathname);
        pathname = ext === '.tdd' ? path.relative(config.syncPath, pathname) : path.relative(config.fmSrc, pathname);
        pathname = _.handleFilePath(pathname);
        _.execFmpp(pathname, function(err) {
            if(err) logger.warning(err);
        });
    });
});

// ----------  style -------------------------
let mcssSrc = _.handleUrlPath(config.style.src);
gulp.task('mcss:compile', () => {
    return gulp.src([ mcssSrc + '/**/*.mcss', '!' + mcssSrc + '/**/_*.mcss' ])
        .pipe(mcss())
        .pipe(gulp.dest(config.style.dist));
});

gulp.task('mcss', ['mcss:compile'], () => {
    gulp.watch(mcssSrc + '/**/*.mcss', ['mcss:compile']);
});

// -------- iconfont -----------------------
let targetPath = path.relative(config.iconfont.dist, path.join(mcssSrc, config.iconfont.cssName));
let fontPath = path.relative(targetPath, config.iconfont.dist);
gulp.task('iconfont', () => {
    return gulp.src(config.iconfont.src)
        .pipe(iconfontCss({
            fontName: config.iconfont.fontName,
            path: config.iconfont.cssTpl,
            targetPath: targetPath,
            fontPath: fontPath,
            cssClass: config.iconfont.fontClass
        }))
        .pipe(iconfont({
            fontName: config.iconfont.fontName,
            prependUnicode: true,
            normalize: true,
            fontHeight: 1001,
            formats: ['svg', 'ttf', 'eot', 'woff', 'woff2'],
            timestamp: runTimestamp
        }))
        .pipe(gulp.dest(config.iconfont.dist));
});

// All gulp tasks
gulp.task('default', gulpSequence('mcss', 'fmpp', 'server'));<commit_msg>modify nodemon watch path<commit_after>
'use strict';

const config = require('./_gms/parseConfig.js');
const path = require('path');
const gulp = require('gulp');
const watch = require('gulp-watch');
const mcss = require('gulp-mcs');
const nodemon = require('gulp-nodemon');
const lr = require('tiny-lr')();
const iconfont = require('gulp-iconfont');
const iconfontCss = require('gulp-iconfont-css');
const gulpSequence = require('gulp-sequence').use(gulp);
const logger = require('./_gms/logger.js');
const _ = require('./_gms/util.js');
const express = require('express');
let app = express();

let allfms = config.allfms.slice();
allfms = allfms.map(function(af) {
    return path.join(config.fmSrc, af);
});

let runTimestamp = Math.round(Date.now()/1000);

// -------- 生成项目模板 ----------------
gulp.task('init', () => {
    _.mkdirs();
});

// -------- 服务器 ----------------
// nodemon 自动重启
// 自动刷新
gulp.task('server', () => {
    nodemon({
        script: './_gms/server.js',
        watch: [config.asyncPath]
    }).on('restart', function() {
        logger.info('\n server restarted.. ');
    });
    startLivereload();
    gulp.watch(config.server.livereload.concat(_.handleUrlPath(config.distPath) + '/**/*.html'), notifyLivereload);
});

function startLivereload() {
    lr.listen(35729, function() {
        logger.muted('livereload listen at port ' + 35729);
    });
}
function notifyLivereload(event) {
    let fileName = path.relative(config.server.root, event.path);
    lr.changed({
        body: {
            files: [fileName]
        }
    });
}

// fmpp编译freemarker
// 第一次会把template下的ftl全部编译
// 之后watch改变的文件
gulp.task('fmpp:compile', () => {
    _.travelRouters();
});

gulp.task('fmpp', ['fmpp:compile'], () => {
    gulp.watch(allfms.concat(_.handleUrlPath(config.syncPath) + '/**/*.tdd'), (event) => {
        let pathname = event.path;
        let ext = path.extname(pathname);
        pathname = ext === '.tdd' ? path.relative(config.syncPath, pathname) : path.relative(config.fmSrc, pathname);
        pathname = _.handleFilePath(pathname);
        _.execFmpp(pathname, function(err) {
            if(err) logger.warning(err);
        });
    });
});

// ----------  style -------------------------
let mcssSrc = _.handleUrlPath(config.style.src);
gulp.task('mcss:compile', () => {
    return gulp.src([ mcssSrc + '/**/*.mcss', '!' + mcssSrc + '/**/_*.mcss' ])
        .pipe(mcss())
        .pipe(gulp.dest(config.style.dist));
});

gulp.task('mcss', ['mcss:compile'], () => {
    gulp.watch(mcssSrc + '/**/*.mcss', ['mcss:compile']);
});

// -------- iconfont -----------------------
let targetPath = path.relative(config.iconfont.dist, path.join(mcssSrc, config.iconfont.cssName));
let fontPath = path.relative(targetPath, config.iconfont.dist);
gulp.task('iconfont', () => {
    return gulp.src(config.iconfont.src)
        .pipe(iconfontCss({
            fontName: config.iconfont.fontName,
            path: config.iconfont.cssTpl,
            targetPath: targetPath,
            fontPath: fontPath,
            cssClass: config.iconfont.fontClass
        }))
        .pipe(iconfont({
            fontName: config.iconfont.fontName,
            prependUnicode: true,
            normalize: true,
            fontHeight: 1001,
            formats: ['svg', 'ttf', 'eot', 'woff', 'woff2'],
            timestamp: runTimestamp
        }))
        .pipe(gulp.dest(config.iconfont.dist));
});

// All gulp tasks
gulp.task('default', gulpSequence('mcss', 'fmpp', 'server'));<|endoftext|>


<commit_before>// Copyright (c) Microsoft Open Technologies, Inc.  All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
(function () {
    "use strict";

    var config = {};
    module.exports = config;

    config.version = "2.1";
    config.buildDate = new Date();
    config.month = config.buildDate.getMonth() + 1;
    config.buildDateString = config.buildDate.getFullYear() + "." + config.month + "." + config.buildDate.getDate();
    config.localeFolder = "en-US";
    config.outputFolder = "bin/";

    config.testsOutput = "";

    if (process.env._NTTREE) {
        config.inRazzle = true;
        config.outputFolder = process.env._NTTREE + "/Corsica/";
        config.testsOutput = config.outputFolder + "other." + config.version + ".debug/tests/unittests/";
    } else {
        config.testsOutput = config.outputFolder + "tests/";
        config.inRazzle = false;
    }

    config.targetName = "WinJS." + config.version;
    config.targetFramework = "Microsoft.WinJS.2.1";
    config.desktopOutput = config.outputFolder + "Microsoft." + config.targetName + "/";
    config.phoneOutput = config.outputFolder + "Microsoft.Phone." + config.targetName + "/";

    config.baseJSFiles = [
        "src/js/build/Copyright.js",
        "src/js/build/writeProfilerMark.js",
        "src/js/build/startBase.js",
        "src/js/base/references.js",
        "src/js/base/base.js",
        "src/js/base/baseUtils.js",
        "src/js/base/log.js",
        "src/js/base/events.js",
        "src/js/base/resources.js",
        "src/js/base/promise.js",
        "src/js/base/scheduler.js",
        "src/js/base/errors.js",
        "src/js/base/xhr.js",
        "src/js/base/safeHTML.js",
        "src/js/base/getWinJSString.js",
        "src/js/base/dispose.js",

        "src/js/ui/control.js",
        "src/js/ui/declarativeControls.js",
        "src/js/ui/elementListUtilities.js",
        "src/js/ui/elementUtilities.js",
        "src/js/ui/fragmentControl.js",
        "src/js/ui/fragmentLoader.js",
        "src/js/ui/optionsLexer.js",
        "src/js/ui/optionsParser.js",
        "src/js/ui/tabManager.js",
        "src/js/ui/transitionAnimation.js",
        "src/js/ui/utilities.js",

        "src/js/wwa-app/application.js",
        "src/js/wwa-app/navigation2.js",
        "src/js/wwa-app/state.js",

        "src/js/binding/bindingParser.js",
        "src/js/binding/data.js",
        "src/js/binding/dataTemplate.js",
        "src/js/binding/declarative.js",
        "src/js/binding/DOMWeakRefTable.js",
        "src/js/binding/list.js",
        "src/js/binding/dataTemplateCompiler.js",

        "src/js/res/Res.js",

        "src/js/build/endBase.js"
    ];

    config.baseJSFilesPhone = [
        "src/js/build/Copyright.js",
        "src/js/build/writeProfilerMark.js",
        "src/js/build/startBase.js",
        "src/js/base/references.js",
        "src/js/base/base.js",
        "src/js/base/baseUtils.js",
        "src/js/base/baseUtils-phone.js",
        "src/js/base/log.js",
        "src/js/base/events.js",
        "src/js/base/resources.js",
        "src/js/base/promise.js",
        "src/js/base/scheduler.js",
        "src/js/base/errors.js",
        "src/js/base/xhr.js",
        "src/js/base/safeHTML.js",
        "src/js/base/getWinJSString.js",
        "src/js/base/dispose.js",

        "src/js/ui/control.js",
        "src/js/ui/declarativeControls.js",
        "src/js/ui/elementListUtilities.js",
        "src/js/ui/elementUtilities.js",
        "src/js/ui/fragmentControl.js",
        "src/js/ui/fragmentLoader.js",
        "src/js/ui/optionsLexer.js",
        "src/js/ui/optionsParser.js",
        "src/js/ui/tabManager.js",
        "src/js/ui/transitionAnimation.js",
        "src/js/ui/utilities.js",

        "src/js/wwa-app/application.js",
        "src/js/wwa-app/navigation2.js",
        "src/js/wwa-app/state.js",

        "src/js/binding/bindingParser.js",
        "src/js/binding/data.js",
        "src/js/binding/dataTemplate.js",
        "src/js/binding/declarative.js",
        "src/js/binding/DOMWeakRefTable.js",
        "src/js/binding/list.js",
        "src/js/binding/dataTemplateCompiler.js",

        "src/js/res/Res.js",

        "src/js/build/endBase.js"
    ];

    config.baseStringsFiles = [
        "src/js/build/Copyright.js",
        "src/js/library/stringsHeader.js",
        "src/js/library/stringsBlockHeader.js",
        "src/js/" + config.localeFolder + "/base.prefix.js",
        "src/js/" + config.localeFolder + "/base.resjson",
        "src/js/library/stringsBlockFooter.js",
        "src/js/library/stringsFooter.js"
    ];

    config.uiJSFiles = [
        "src/js/build/Copyright.js",
        "src/js/build/startUI.js",
        "src/js/animations/animations.js",
        "src/js/uicollections/Assert.js",
        "src/js/uicollections/ItemsManager/BindingListDataSource.js",
        "src/js/uicollections/ItemsManager/ListDataSource.js",
        "src/js/uicollections/ItemsManager/GroupDataSource.js",
        "src/js/uicollections/ItemsManager/GroupedItemDataSource.js",
        "src/js/uicollections/ItemsManager/StorageDataSource.js",
        "src/js/uicollections/ItemsManager/ItemsManager.js",
        "src/js/uicollections/ItemsManager/ParallelWorkQueue.js",
        "src/js/uicollections/ItemsManager/VersionManager.js",
        "src/js/uicollections/Flipper/Flipper.js",
        "src/js/uicollections/Flipper/FlipperPageManager.js",
        "src/js/uicollections/ListView/BrowseMode.js",
        "src/js/uicollections/ListView/Constants.js",
        "src/js/uicollections/ListView/ErrorMessages.js",
        "src/js/uicollections/ListView/GroupFocusCache.js",
        "src/js/uicollections/ListView/GroupsContainer.js",
        "src/js/uicollections/ListView/itemEventsHandler.js",
        "src/js/uicollections/ListView/ItemsContainer.js",
        "src/js/uicollections/ListView/Layouts2.js",
        "src/js/uicollections/ListView/ListViewImpl.js",
        "src/js/uicollections/Repeater/Repeater.js",
        "src/js/uicollections/ListView/SelectionManager.js",
        "src/js/uicollections/ListView/VirtualizeContentsView.js",
        "src/js/controls/DatePicker/datePicker.js",
        "src/js/controls/TimePicker/timePicker.js",
        "src/js/controls/Select/select.js",
        "src/js/controls/BackButton/BackButton.js",
        "src/js/controls/Rating/rating.js",
        "src/js/controls/Toggle/Toggle.js",
        "src/js/controls/SemanticZoom/SemanticZoom.js",
        "src/js/controls/Hub/hub.js",
        "src/js/controls/Hub/hubSection.js",
        "src/js/controls/AppBar/Overlay.js",
        "src/js/controls/AppBar/AppBarIcon.js",
        "src/js/controls/AppBar/AppBarCommand.js",
        "src/js/controls/AppBar/AppBar.js",
        "src/js/controls/AppBar/Flyout.js",
        "src/js/controls/AppBar/Menu.js",
        "src/js/controls/AppBar/MenuCommand.js",
        "src/js/controls/SearchBox/searchBox.js",
        "src/js/controls/AppBar/SettingsFlyout.js",
        "src/js/controls/ItemContainer/itemContainer.js",
        "src/js/controls/NavBar/keyboardBehavior.js",
        "src/js/controls/NavBar/navBar.js",
        "src/js/controls/NavBar/navBarContainer.js",
        "src/js/controls/NavBar/navBarCommand.js",
        "src/js/controls/Tooltip/tooltip.js",
        "src/js/controls/ViewBox/ViewBox.js",
        "src/js/build/endUI.js"
    ];

    config.uiJSFilesPhone = [
        "src/js/build/startUI.js",
        "src/js/uicollections/references.js",
        "src/js/animations/animations.js",
        "src/js/uicollections/Assert.js",
        "src/js/uicollections/ItemsManager/BindingListDataSource.js",
        "src/js/uicollections/ItemsManager/ListDataSource.js",
        "src/js/uicollections/ItemsManager/GroupDataSource.js",
        "src/js/uicollections/ItemsManager/GroupedItemDataSource.js",
        "src/js/uicollections/ItemsManager/StorageDataSource.js",
        "src/js/uicollections/ItemsManager/ItemsManager.js",
        "src/js/uicollections/ItemsManager/ParallelWorkQueue.js",
        "src/js/uicollections/ItemsManager/VersionManager.js",
        "src/js/uicollections/Flipper/Flipper.js",
        "src/js/uicollections/Flipper/FlipperPageManager.js",
        "src/js/uicollections/ListView/BrowseMode.js",
        "src/js/uicollections/ListView/Constants.js",
        "src/js/uicollections/ListView/ErrorMessages.js",
        "src/js/uicollections/ListView/GroupFocusCache.js",
        "src/js/uicollections/ListView/GroupsContainer.js",
        "src/js/uicollections/ListView/itemEventsHandler.js",
        "src/js/uicollections/ListView/ItemsContainer.js",
        "src/js/uicollections/ListView/Layouts2.js",
        "src/js/uicollections/ListView/ListViewImpl.js",
        "src/js/uicollections/Repeater/Repeater.js",
        "src/js/uicollections/ListView/SelectionManager.js",
        "src/js/uicollections/ListView/VirtualizeContentsView.js",
        "src/js/controls/AppBar/AppBarIcon.js",
        "src/js/controls/AppBar/AppBarCommand-phone.js",
        "src/js/controls/AppBar/AppBar-phone.js",
        "src/js/controls/Pivot/Pivot.js",
        "src/js/controls/Pivot/PivotItem.js",
        "src/js/controls/Toggle/Toggle.js",
        "src/js/controls/ItemContainer/itemContainer.js",
        "src/js/controls/SemanticZoom/SemanticZoom.js",
        "src/js/controls/ViewBox/ViewBox.js",
        "src/js/build/endUI.js",
    ];

    config.uiStringsFiles = [
        "src/js/build/Copyright.js",
        "src/js/library/stringsHeader.js",
        "src/js/library/stringsBlockHeader.js",
        "src/js/" + config.localeFolder + "/ui.prefix.js",
        "src/js/" + config.localeFolder + "/ui.resjson",
        "src/js/library/stringsBlockFooter.js",
        "src/js/library/stringsFooter.js"
    ];

    config.lint = {
        srcFiles: ["src/**/*.js"],
        buildFiles: ["gruntfile.js", "config.js", "tasks/**/*.js"],
        ignoreFiles: [
            "src/js/en-US/base.prefix.js",
            "src/js/en-US/ui.prefix.js",
            "src/js/library/stringsBlockFooter.js",
            "src/js/library/stringsBlockHeader.js",
            "src/js/library/stringsFooter.js",
            "src/js/library/stringsHeader.js",
        ],
    };

})();<commit_msg>More build fixes for case sensitive filesystems.<commit_after>// Copyright (c) Microsoft Open Technologies, Inc.  All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
(function () {
    "use strict";

    var config = {};
    module.exports = config;

    config.version = "2.1";
    config.buildDate = new Date();
    config.month = config.buildDate.getMonth() + 1;
    config.buildDateString = config.buildDate.getFullYear() + "." + config.month + "." + config.buildDate.getDate();
    config.localeFolder = "en-US";
    config.outputFolder = "bin/";

    config.testsOutput = "";

    if (process.env._NTTREE) {
        config.inRazzle = true;
        config.outputFolder = process.env._NTTREE + "/Corsica/";
        config.testsOutput = config.outputFolder + "other." + config.version + ".debug/tests/unittests/";
    } else {
        config.testsOutput = config.outputFolder + "tests/";
        config.inRazzle = false;
    }

    config.targetName = "WinJS." + config.version;
    config.targetFramework = "Microsoft.WinJS.2.1";
    config.desktopOutput = config.outputFolder + "Microsoft." + config.targetName + "/";
    config.phoneOutput = config.outputFolder + "Microsoft.Phone." + config.targetName + "/";

    config.baseJSFiles = [
        "src/js/build/Copyright.js",
        "src/js/build/writeProfilerMark.js",
        "src/js/build/startBase.js",
        "src/js/base/references.js",
        "src/js/base/base.js",
        "src/js/base/baseUtils.js",
        "src/js/base/log.js",
        "src/js/base/events.js",
        "src/js/base/resources.js",
        "src/js/base/promise.js",
        "src/js/base/scheduler.js",
        "src/js/base/errors.js",
        "src/js/base/xhr.js",
        "src/js/base/safeHTML.js",
        "src/js/base/getWinJSString.js",
        "src/js/base/dispose.js",

        "src/js/ui/control.js",
        "src/js/ui/declarativeControls.js",
        "src/js/ui/elementListUtilities.js",
        "src/js/ui/elementUtilities.js",
        "src/js/ui/fragmentControl.js",
        "src/js/ui/fragmentLoader.js",
        "src/js/ui/optionsLexer.js",
        "src/js/ui/optionsParser.js",
        "src/js/ui/tabManager.js",
        "src/js/ui/transitionAnimation.js",
        "src/js/ui/utilities.js",

        "src/js/wwa-app/application.js",
        "src/js/wwa-app/navigation2.js",
        "src/js/wwa-app/state.js",

        "src/js/binding/bindingParser.js",
        "src/js/binding/data.js",
        "src/js/binding/dataTemplate.js",
        "src/js/binding/declarative.js",
        "src/js/binding/DOMWeakRefTable.js",
        "src/js/binding/list.js",
        "src/js/binding/dataTemplateCompiler.js",

        "src/js/res/Res.js",

        "src/js/build/endBase.js"
    ];

    config.baseJSFilesPhone = [
        "src/js/build/Copyright.js",
        "src/js/build/writeProfilerMark.js",
        "src/js/build/startBase.js",
        "src/js/base/references.js",
        "src/js/base/base.js",
        "src/js/base/baseUtils.js",
        "src/js/base/baseUtils-phone.js",
        "src/js/base/log.js",
        "src/js/base/events.js",
        "src/js/base/resources.js",
        "src/js/base/promise.js",
        "src/js/base/scheduler.js",
        "src/js/base/errors.js",
        "src/js/base/xhr.js",
        "src/js/base/safeHTML.js",
        "src/js/base/getWinJSString.js",
        "src/js/base/dispose.js",

        "src/js/ui/control.js",
        "src/js/ui/declarativeControls.js",
        "src/js/ui/elementListUtilities.js",
        "src/js/ui/elementUtilities.js",
        "src/js/ui/fragmentControl.js",
        "src/js/ui/fragmentLoader.js",
        "src/js/ui/optionsLexer.js",
        "src/js/ui/optionsParser.js",
        "src/js/ui/tabManager.js",
        "src/js/ui/transitionAnimation.js",
        "src/js/ui/utilities.js",

        "src/js/wwa-app/application.js",
        "src/js/wwa-app/navigation2.js",
        "src/js/wwa-app/state.js",

        "src/js/binding/bindingParser.js",
        "src/js/binding/data.js",
        "src/js/binding/dataTemplate.js",
        "src/js/binding/declarative.js",
        "src/js/binding/DOMWeakRefTable.js",
        "src/js/binding/list.js",
        "src/js/binding/dataTemplateCompiler.js",

        "src/js/res/Res.js",

        "src/js/build/endBase.js"
    ];

    config.baseStringsFiles = [
        "src/js/build/Copyright.js",
        "src/js/library/stringsHeader.js",
        "src/js/library/stringsBlockHeader.js",
        "src/js/" + config.localeFolder + "/base.prefix.js",
        "src/js/" + config.localeFolder + "/base.resjson",
        "src/js/library/stringsBlockFooter.js",
        "src/js/library/stringsFooter.js"
    ];

    config.uiJSFiles = [
        "src/js/build/Copyright.js",
        "src/js/build/startUI.js",
        "src/js/animations/animations.js",
        "src/js/uicollections/Assert.js",
        "src/js/uicollections/ItemsManager/BindingListDataSource.js",
        "src/js/uicollections/ItemsManager/ListDataSource.js",
        "src/js/uicollections/ItemsManager/GroupDataSource.js",
        "src/js/uicollections/ItemsManager/GroupedItemDataSource.js",
        "src/js/uicollections/ItemsManager/StorageDataSource.js",
        "src/js/uicollections/ItemsManager/ItemsManager.js",
        "src/js/uicollections/ItemsManager/ParallelWorkQueue.js",
        "src/js/uicollections/ItemsManager/VersionManager.js",
        "src/js/uicollections/Flipper/Flipper.js",
        "src/js/uicollections/Flipper/FlipperPageManager.js",
        "src/js/uicollections/ListView/BrowseMode.js",
        "src/js/uicollections/ListView/Constants.js",
        "src/js/uicollections/ListView/ErrorMessages.js",
        "src/js/uicollections/ListView/GroupFocusCache.js",
        "src/js/uicollections/ListView/GroupsContainer.js",
        "src/js/uicollections/ListView/itemEventsHandler.js",
        "src/js/uicollections/ListView/ItemsContainer.js",
        "src/js/uicollections/ListView/Layouts2.js",
        "src/js/uicollections/ListView/ListViewImpl.js",
        "src/js/uicollections/Repeater/Repeater.js",
        "src/js/uicollections/ListView/SelectionManager.js",
        "src/js/uicollections/ListView/VirtualizeContentsView.js",
        "src/js/controls/DatePicker/datePicker.js",
        "src/js/controls/TimePicker/timePicker.js",
        "src/js/controls/Select/select.js",
        "src/js/controls/BackButton/BackButton.js",
        "src/js/controls/Rating/Rating.js",
        "src/js/controls/Toggle/Toggle.js",
        "src/js/controls/SemanticZoom/SemanticZoom.js",
        "src/js/controls/Hub/Hub.js",
        "src/js/controls/Hub/HubSection.js",
        "src/js/controls/AppBar/Overlay.js",
        "src/js/controls/AppBar/AppBarIcon.js",
        "src/js/controls/AppBar/AppBarCommand.js",
        "src/js/controls/AppBar/AppBar.js",
        "src/js/controls/AppBar/Flyout.js",
        "src/js/controls/AppBar/Menu.js",
        "src/js/controls/AppBar/MenuCommand.js",
        "src/js/controls/SearchBox/SearchBox.js",
        "src/js/controls/AppBar/SettingsFlyout.js",
        "src/js/controls/ItemContainer/itemContainer.js",
        "src/js/controls/NavBar/keyboardBehavior.js",
        "src/js/controls/NavBar/NavBar.js",
        "src/js/controls/NavBar/NavBarContainer.js",
        "src/js/controls/NavBar/NavBarCommand.js",
        "src/js/controls/Tooltip/Tooltip.js",
        "src/js/controls/ViewBox/ViewBox.js",
        "src/js/build/endUI.js"
    ];

    config.uiJSFilesPhone = [
        "src/js/build/startUI.js",
        "src/js/uicollections/references.js",
        "src/js/animations/animations.js",
        "src/js/uicollections/Assert.js",
        "src/js/uicollections/ItemsManager/BindingListDataSource.js",
        "src/js/uicollections/ItemsManager/ListDataSource.js",
        "src/js/uicollections/ItemsManager/GroupDataSource.js",
        "src/js/uicollections/ItemsManager/GroupedItemDataSource.js",
        "src/js/uicollections/ItemsManager/StorageDataSource.js",
        "src/js/uicollections/ItemsManager/ItemsManager.js",
        "src/js/uicollections/ItemsManager/ParallelWorkQueue.js",
        "src/js/uicollections/ItemsManager/VersionManager.js",
        "src/js/uicollections/Flipper/Flipper.js",
        "src/js/uicollections/Flipper/FlipperPageManager.js",
        "src/js/uicollections/ListView/BrowseMode.js",
        "src/js/uicollections/ListView/Constants.js",
        "src/js/uicollections/ListView/ErrorMessages.js",
        "src/js/uicollections/ListView/GroupFocusCache.js",
        "src/js/uicollections/ListView/GroupsContainer.js",
        "src/js/uicollections/ListView/itemEventsHandler.js",
        "src/js/uicollections/ListView/ItemsContainer.js",
        "src/js/uicollections/ListView/Layouts2.js",
        "src/js/uicollections/ListView/ListViewImpl.js",
        "src/js/uicollections/Repeater/Repeater.js",
        "src/js/uicollections/ListView/SelectionManager.js",
        "src/js/uicollections/ListView/VirtualizeContentsView.js",
        "src/js/controls/AppBar/AppBarIcon.js",
        "src/js/controls/AppBar/AppBarCommand-phone.js",
        "src/js/controls/AppBar/AppBar-phone.js",
        "src/js/controls/Pivot/Pivot.js",
        "src/js/controls/Pivot/PivotItem.js",
        "src/js/controls/Toggle/Toggle.js",
        "src/js/controls/ItemContainer/itemContainer.js",
        "src/js/controls/SemanticZoom/SemanticZoom.js",
        "src/js/controls/ViewBox/ViewBox.js",
        "src/js/build/endUI.js",
    ];

    config.uiStringsFiles = [
        "src/js/build/Copyright.js",
        "src/js/library/stringsHeader.js",
        "src/js/library/stringsBlockHeader.js",
        "src/js/" + config.localeFolder + "/ui.prefix.js",
        "src/js/" + config.localeFolder + "/ui.resjson",
        "src/js/library/stringsBlockFooter.js",
        "src/js/library/stringsFooter.js"
    ];

    config.lint = {
        srcFiles: ["src/**/*.js"],
        buildFiles: ["gruntfile.js", "config.js", "tasks/**/*.js"],
        ignoreFiles: [
            "src/js/en-US/base.prefix.js",
            "src/js/en-US/ui.prefix.js",
            "src/js/library/stringsBlockFooter.js",
            "src/js/library/stringsBlockHeader.js",
            "src/js/library/stringsFooter.js",
            "src/js/library/stringsHeader.js",
        ],
    };

})();<|endoftext|>


<commit_before>'use strict';

const Hapi = require('hapi');
const server = new Hapi.Server();
const nodemailer = require('nodemailer');
const https = require('https');
const config = require('./config');
const validator = require("email-validator");

let globalHeaders = {
    'Content-Type': 'application/json',
    'X-API-Key': config.application.apiKey
};

/******************************
 *
 * Mail server config
 *
 ******************************/
let transporter = nodemailer.createTransport({
    host: config.mail.host,
    port: config.mail.port,
    secure: config.mail.secure,
    auth: {
        user: config.mail.username,
        pass: config.mail.password
    }
});

/******************************
 *
 * Web server config
 *
 ******************************/

 if ( config.server.host ) {
    server.connection({ host: config.server.host, port: config.server.port, routes: { cors: true }  });
 } else {
    server.connection({ port: config.server.port, routes: { cors: true }  });
 }

server.register(require('inert'), (err) => {
    if (err) {
        throw err;
    }

    server.route({
        method: 'GET',
        path: '/',
        handler: function (request, reply) {
            reply.file('index.html');
        }
    });

    // Activate the user and returns their new authentication keys and JWT
    server.route({
        method: 'POST',
        path: '/activate/user',
        handler: function (request, reply) {
            console.info('Called POST /activate/user');
            callHaventecServer('/authenticate/authentication/activate/user', 'POST', request.payload, function (result) {
                reply(result);
            });
        }
    });

    // Activate the device and returns their new authentication keys and JWT
    server.route({
        method: 'POST',
        path: '/activate/device',
        handler: function (request, reply) {
            console.info('Called POST /activate/device');
            callHaventecServer('/authenticate/authentication/activate/device', 'POST', request.payload, function (result) {
                reply(result);
            });
        }
    });

    // Logs the user in and returns a new set of authentication keys and JWT
    server.route({
        method: 'POST',
        path: '/login',
        handler: function (request, reply) {
            console.info('Called POST /login');
            callHaventecServer('/authenticate/authentication/login', 'POST', request.payload, function (result) {
                reply(result);
            });
        }
    });

    // Logs the user out and invalidates their JWT
    server.route({
        method: 'DELETE',
        path: '/logout',
        handler: function (request, reply) {
            console.info('Called DELETE /logout');
            callHaventecServer('/authenticate/authentication/logout', 'DELETE', request.payload, function (result) {
                reply(result);
            });
        }
    });

    // Resets the user's PIN and returns their new authentication keys and JWT
    server.route({
        method: 'POST',
        path: '/reset-pin',
        handler: function (request, reply) {
            console.info('Called POST /reset-pin');
            callHaventecServer('/authenticate/authentication/reset-pin', 'POST', request.payload, function (result) {
                reply(result);
            });
        }
    });

    // Add a new device to the users account and email the activation code to their email address
    server.route({
        method: 'POST',
        path: '/device',
        handler: function (request, reply) {
            console.info('Called POST /self-service/device');

            callHaventecServer('/authenticate/self-service/device', 'POST', request.payload, function (result) {
                if (result.activationToken !== undefined && result.email !== undefined) {
                    console.info('Device Activation Token', result.activationToken);
                    sendEmail(result.email, 'My App - New Device Request', 'Device Activation code: ' + result.activationToken);
                    // We do not want to send the email or activationToken back to the client;
                    result.email = '';
                    result.activationToken = '';
                }

                reply(result);
            });
        }
    });

    // Calls forgot pin for a given user and returns a reset PIN token
    server.route({
        method: 'POST',
        path: '/forgot-pin',
        handler: function (request, reply) {
            console.info('Called POST /forgot-pin');

            callHaventecServer('/authenticate/authentication/forgot-pin', 'POST', request.payload, function (result) {
                if (result.resetPinToken !== undefined && result.email !== undefined) {
                    console.info('Reset Token', result.resetPinToken);
                    sendEmail(result.email, 'My App - Reset PIN', 'Reset PIN code: ' + result.resetPinToken);
                    // We do not want to send the email or resetPinToken back to the client;
                    result.email = '';
                    result.resetPinToken = '';
                }

                reply(result);
            });
        }
    });

    // Returns a registration token for a self-service created user
    server.route({
        method: 'POST',
        path: '/self-service/user',
        handler: function (request, reply) {
            console.info('Called POST /self-service/user');

            // Add the API key to the POST body
            request.payload.apiKey = config.application.apiKey;

            // Get the email address of the user signing up
            let email = request.payload.email;

            callHaventecServer('/authenticate/self-service/user', 'POST', request.payload, function (result) {
                if (result.activationToken !== undefined) {
                    console.info('Registration Token', result.activationToken);
                    sendEmail(email, 'My App - Activate your account', 'Activation code: ' + result.activationToken);
                    // We do not want to send the activationToken back to the client;
                    result.activationToken = '';
                }

                reply(result);
            });
        }
    });

    // Test email endpoint
    server.route({
        method: 'GET',
        path: '/test-email',
        handler: function (request, reply) {
            console.info('Called POST /test-email');

            let params = request.query;
            let result = 'Test failed: no email or invalid email address was supplied';

            if(config.mail.host === ''){
                result = ('Mail server is not configured. Please see the README file on how to configure your mail server');
            }
            else if (validator.validate(params.email)) {
                sendEmail(params.email, 'My App - Test email', 'Test email was successful');
                result = 'Email sent to ' + params.email + '. Please check your inbox';
            }
            reply(result);
        }
    });

    server.start(function (err) {
        console.log('Haventec Authenticate sample server started at: ' + server.info.uri);
        console.log('This server is NOT intended to be used in a Production environment.');
    });

});

function sendEmail(email, subject, body){
    let mailOptions = {
        from: config.mail.fromAddress,
        to: email,
        subject: subject,
        text: body
    };

    if(config.mail.host === ''){
        return console.log('Mail server is not configured');
    }
    else {
        transporter.sendMail(mailOptions, (error, info) => {
            if (info) {
                return console.log('Mail server info', info);
            }
            if (error) {
                return console.log(error);
            }
        });
    }
}

function callHaventecServer(path, method, payload, callback) {
    const postData = JSON.stringify(payload);
    const options = {
        hostname: config.application.haventecServer,
        path: path,
        method: method,
        headers: globalHeaders
    };

    const req = https.request(options, (res) => {
        res.setEncoding('utf8');
        res.on('data', (data) => {
            callback(JSON.parse(data));
        });
    });

    req.on('error', (e) => {
        console.error(`problem with request: ${e.message}`);
    });

    // write data to request body
    req.write(postData);
    req.end();
}<commit_msg>Updates URLs for 1.2.5 API<commit_after>'use strict';

const Hapi = require('hapi');
const server = new Hapi.Server();
const nodemailer = require('nodemailer');
const https = require('https');
const config = require('./config');
const validator = require("email-validator");

let globalHeaders = {
    'Content-Type': 'application/json',
    'x-api-key': config.application.apiKey
};

/******************************
 *
 * Mail server config
 *
 ******************************/
let transporter = nodemailer.createTransport({
    host: config.mail.host,
    port: config.mail.port,
    secure: config.mail.secure,
    auth: {
        user: config.mail.username,
        pass: config.mail.password
    }
});

/******************************
 *
 * Web server config
 *
 ******************************/

 if ( config.server.host ) {
    server.connection({ host: config.server.host, port: config.server.port, routes: { cors: true }  });
 } else {
    server.connection({ port: config.server.port, routes: { cors: true }  });
 }

server.register(require('inert'), (err) => {
    if (err) {
        throw err;
    }

    server.route({
        method: 'GET',
        path: '/',
        handler: function (request, reply) {
            reply.file('index.html');
        }
    });

    // Activate the user and returns their new authentication keys and JWT
    server.route({
        method: 'POST',
        path: '/activate/user',
        handler: function (request, reply) {
            console.info('Called POST /activate/user');
            callHaventecServer('/authenticate/v1-2/authentication/activate/user', 'POST', request.payload, function (result) {
                reply(result);
            });
        }
    });

    // Activate the device and returns their new authentication keys and JWT
    server.route({
        method: 'POST',
        path: '/activate/device',
        handler: function (request, reply) {
            console.info('Called POST /activate/device');
            callHaventecServer('/authenticate/v1-2/authentication/activate/device', 'POST', request.payload, function (result) {
                reply(result);
            });
        }
    });

    // Logs the user in and returns a new set of authentication keys and JWT
    server.route({
        method: 'POST',
        path: '/login',
        handler: function (request, reply) {
            console.info('Called POST /login');
            callHaventecServer('/authenticate/v1-2/authentication/login', 'POST', request.payload, function (result) {
                reply(result);
            });
        }
    });

    // Logs the user out and invalidates their JWT
    server.route({
        method: 'DELETE',
        path: '/logout',
        handler: function (request, reply) {
            console.info('Called DELETE /logout');
            callHaventecServer('/authenticate/v1-2/authentication/logout', 'DELETE', request.payload, function (result) {
                reply(result);
            });
        }
    });

    // Resets the user's PIN and returns their new authentication keys and JWT
    server.route({
        method: 'POST',
        path: '/reset-pin',
        handler: function (request, reply) {
            console.info('Called POST /reset-pin');
            callHaventecServer('/authenticate/v1-2/authentication/reset-pin', 'POST', request.payload, function (result) {
                reply(result);
            });
        }
    });

    // Add a new device to the users account and email the activation code to their email address
    server.route({
        method: 'POST',
        path: '/device',
        handler: function (request, reply) {
            console.info('Called POST /self-service/device');

            callHaventecServer('/authenticate/v1-2/self-service/device', 'POST', request.payload, function (result) {
                if (result.activationToken !== undefined && result.userEmail !== undefined) {
                    console.info('Device Activation Token', result.activationToken);
                    sendEmail(result.userEmail, 'My App - New Device Request', 'Device Activation code: ' + result.activationToken);
                    // We do not want to send the email or activationToken back to the client;
                    result.userEmail = '';
                    result.activationToken = '';
                }

                reply(result);
            });
        }
    });

    // Calls forgot pin for a given user and returns a reset PIN token
    server.route({
        method: 'POST',
        path: '/forgot-pin',
        handler: function (request, reply) {
            console.info('Called POST /forgot-pin');

            callHaventecServer('/authenticate/v1-2/authentication/forgot-pin', 'POST', request.payload, function (result) {
                if (result.resetPinToken !== undefined && result.userEmail !== undefined) {
                    console.info('Reset Token', result.resetPinToken);
                    sendEmail(result.userEmail, 'My App - Reset PIN', 'Reset PIN code: ' + result.resetPinToken);
                    // We do not want to send the email or resetPinToken back to the client;
                    result.userEmail = '';
                    result.resetPinToken = '';
                }

                reply(result);
            });
        }
    });

    // Returns a registration token for a self-service created user
    server.route({
        method: 'POST',
        path: '/self-service/user',
        handler: function (request, reply) {
            console.info('Called POST /self-service/user');

            // Get the email address of the user signing up
            let email = request.payload.email;

            callHaventecServer('/authenticate/v1-2/self-service/user', 'POST', request.payload, function (result) {
                if (result.activationToken !== undefined) {
                    console.info('Activation Token', result.activationToken);
                    sendEmail(email, 'My App - Activate your account', 'Activation code: ' + result.activationToken);
                    // We do not want to send the activationToken back to the client;
                    result.activationToken = '';
                }

                reply(result);
            });
        }
    });

    // Test email endpoint
    server.route({
        method: 'GET',
        path: '/test-email',
        handler: function (request, reply) {
            console.info('Called POST /test-email');

            let params = request.query;
            let result = 'Test failed: no email or invalid email address was supplied';

            if(config.mail.host === ''){
                result = ('Mail server is not configured. Please see the README file on how to configure your mail server');
            }
            else if (validator.validate(params.email)) {
                sendEmail(params.email, 'My App - Test email', 'Test email was successful');
                result = 'Email sent to ' + params.email + '. Please check your inbox';
            }
            reply(result);
        }
    });

    server.start(function (err) {
        console.log('Haventec Authenticate sample server started at: ' + server.info.uri);
        console.log('This server is NOT intended to be used in a Production environment.');
    });

});

function sendEmail(email, subject, body){
    let mailOptions = {
        from: config.mail.fromAddress,
        to: email,
        subject: subject,
        text: body
    };

    if(config.mail.host === ''){
        return console.log('Mail server is not configured');
    }
    else {
        transporter.sendMail(mailOptions, (error, info) => {
            if (info) {
                return console.log('Mail server info', info);
            }
            if (error) {
                return console.log(error);
            }
        });
    }
}

function callHaventecServer(path, method, payload, callback) {
    const postData = JSON.stringify(payload);
    const options = {
        hostname: config.application.haventecServer,
        path: path,
        method: method,
        headers: globalHeaders
    };

    const req = https.request(options, (res) => {
        res.setEncoding('utf8');
        res.on('data', (data) => {
            callback(JSON.parse(data));
        });
    });

    req.on('error', (e) => {
        console.error(`problem with request: ${e.message}`);
    });

    // write data to request body
    req.write(postData);
    req.end();
}<|endoftext|>


<commit_before>/*jslint browser: true*/
'use strict';
/**
 * Created by ermaldo on 25.11.15.
 */

// for new menu items just add thuse below by adding or acting as shown
document.getElementById("nav01").innerHTML =
    ""+
    "
"+
    "
"+
    "

" +
    "
Home
" +
    "
Universal Summary" +
    "
"+
    "
Perfect Forward Secrecy Support
"+
    "
Diffie Hellman Keygroups
"+
    "
Elliptic Curve Diffie Hellman
"+
    "
Cipher Suites
"+
    "
MAC Distribution
"+
    "

"+
    "
Logjam Attack
"+
    "
"+
    "
"+
    "
Detailed Filter
" +
    "
Worldmap
" +
    "
Analyse Me
" +
    "

"+
    "
Last Scan: DD.MM.YYYY
"+
    "
"+
    "
"+
    "";

// for footer menu
var n = new Date();
var d = n.getFullYear(); // dynamic Date
document.getElementById("footer").innerHTML =
    "
"+
    " © "+d+" 2015 "+
    " HfT Stuttgart "+
    " | Subscribe  "+
    "
";

// open Subscribe Modal and this modal will open the subscriber count modal on subscribe.php file
document.getElementById("subscribe").innerHTML =
    "<form id='formCheck' method='post' action='./php/subscribe.php'>"+
    "
"+
    "
"+
    "
"+
    "
"+
    "
"+
    "               <button type='button' class='close' data-dismiss='modal'>×</button>"+
    "
Subscribe for e-mail:
"+
    "
"+
    "
"+
    "
"+
    "                   Full Name:"+
    "                   <input type='text' class='form-control' name='name' id='name' placeholder='Your Name' required>" +
    "                   " +
    "
"+
    "
"+
    "                   @"+
    "                   " +
    "                   <input type='email' class='form-control' name='email' id='email' placeholder='Email' aria-describedby='sizing-addon1' required>"+
    "                   " +
    "

"+
    "
"+
    "
" +
    "
" +
    "                           " +
    "
" +
    "
" +
    "
" +
    "
" +
    "                                               I accept the Terms & Conditions" +
    "
" +
    "
" +
    "
" +
    "
" +
    "                                                   By clicking the Subscribe Button bellow you agree that your Name and e-mail Address" +
    "                                                   will be saved into our Database. We are using those to send you monthly an e-mail " +
    "                                                   about the last CRAWLING results. We assure you that your Name and e-mail address" +
    "                                                   will not be disclosed to third parties!" +
    "
" +
    "
" +
    "
" +
    "
" +
    "                           	" +
    "
" +
    "
" +
    "
"+
    "
"+
    "
" +
    "
" +
    "
" +
    "
" +
    "           " +
    "               <button type='button' class='btn btn-default' data-dismiss='modal'>Close</button>"+
    "               <button type='submit' class='btn btn-success' data-toggle='modal' data-target='#subModal' id='save' disabled>Subscribe</button>" +
    "           	" +
    "
" +
    "
" +
    "
"+
    "
"+
    "
"+
    "
"+
    "
"+
    "</form>";

// enable the Subscribe
$("#t-c").click(function(){
    $("#save").removeAttr("disabled");
});

// Validate
/* form validation */
$(document).ready(function(){
    $("#name").keyup(function(){
        if(/^[a-zA-Z ]+$/.test($(this).val()) && $(this).val().trim() !== "")
        {
            $(this).css("border-color", "#0F0");
        } else {
            $(this).css("border-color", "#F00");
        }
    });
    $("#email").keyup(function(){
        if(/^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/.test($(this).val()) && $(this).val().trim() !== "")
        {
            $(this).css("border-color", "#0F0");
        } else {
            $(this).css("border-color", "#F00");
        }
    });
});
<commit_msg>Update menu.js<commit_after>/*jslint browser: true*/
'use strict';
/**
 * Created by ermaldo on 25.11.15.
 */

// for new menu items just add thuse below by adding or acting as shown
document.getElementById("nav01").innerHTML =
    ""+
    "
"+
    "
"+
    "

" +
    "
Home
" +
    "
Universal Summary" +
    "
"+
    "
Perfect Forward Secrecy Support
"+
    "
Diffie Hellman Keygroups
"+
    "
Elliptic Curve Diffie Hellman
"+
    "
Cipher Suites
"+
    "
MAC Distribution
"+
    "

"+
    "
Logjam Attack
"+
    "
"+
    "
"+
    "
Detailed Filter
" +
    "
Worldmap
" +
    "
Analyse Me
" +
    "

"+
    "
Last Scan: DD.MM.YYYY
"+
    "
"+
    "
"+
    "";

// for footer menu
var n = new Date();
var d = n.getFullYear(); // dynamic Date
document.getElementById("footer").innerHTML =
    "
"+
    " © 2015 -"+d+" "+
    " HfT Stuttgart "+
    " | Subscribe  "+
    "
";

// open Subscribe Modal and this modal will open the subscriber count modal on subscribe.php file
document.getElementById("subscribe").innerHTML =
    "<form id='formCheck' method='post' action='./php/subscribe.php'>"+
    "
"+
    "
"+
    "
"+
    "
"+
    "
"+
    "               <button type='button' class='close' data-dismiss='modal'>×</button>"+
    "
Subscribe for e-mail:
"+
    "
"+
    "
"+
    "
"+
    "                   Full Name:"+
    "                   <input type='text' class='form-control' name='name' id='name' placeholder='Your Name' required>" +
    "                   " +
    "
"+
    "
"+
    "                   @"+
    "                   " +
    "                   <input type='email' class='form-control' name='email' id='email' placeholder='Email' aria-describedby='sizing-addon1' required>"+
    "                   " +
    "

"+
    "
"+
    "
" +
    "
" +
    "                           " +
    "
" +
    "
" +
    "
" +
    "
" +
    "                                               I accept the Terms & Conditions" +
    "
" +
    "
" +
    "
" +
    "
" +
    "                                                   By clicking the Subscribe Button bellow you agree that your Name and e-mail Address" +
    "                                                   will be saved into our Database. We are using those to send you monthly an e-mail " +
    "                                                   about the last CRAWLING results. We assure you that your Name and e-mail address" +
    "                                                   will not be disclosed to third parties!" +
    "
" +
    "
" +
    "
" +
    "
" +
    "                           	" +
    "
" +
    "
" +
    "
"+
    "
"+
    "
" +
    "
" +
    "
" +
    "
" +
    "           " +
    "               <button type='button' class='btn btn-default' data-dismiss='modal'>Close</button>"+
    "               <button type='submit' class='btn btn-success' data-toggle='modal' data-target='#subModal' id='save' disabled>Subscribe</button>" +
    "           	" +
    "
" +
    "
" +
    "
"+
    "
"+
    "
"+
    "
"+
    "
"+
    "</form>";

// enable the Subscribe
$("#t-c").click(function(){
    $("#save").removeAttr("disabled");
});

// Validate
/* form validation */
$(document).ready(function(){
    $("#name").keyup(function(){
        if(/^[a-zA-Z ]+$/.test($(this).val()) && $(this).val().trim() !== "")
        {
            $(this).css("border-color", "#0F0");
        } else {
            $(this).css("border-color", "#F00");
        }
    });
    $("#email").keyup(function(){
        if(/^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/.test($(this).val()) && $(this).val().trim() !== "")
        {
            $(this).css("border-color", "#0F0");
        } else {
            $(this).css("border-color", "#F00");
        }
    });
});
<|endoftext|>