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

'use strict';

const E2EBridge = require('e2e-bridge-lib');
const util = require('util');
const argv = require('minimist')(process.argv.slice(2));
const prompt = require('prompt');
const path = require('path');

const XUML_SERVICE_TYPE = 'xUML';
const NODE_SERVICE_TYPE = 'node';
const JAVA_SERVICE_TYPE = 'java';

if(argv['help']) {
    showHelp();
    process.exit(0);
}

const settings = {};
let requiredProp = {};

function incorrectNbOfArgs(){
    showHelp('Incorrect number of arguments');
    process.exit(1);
}

function unknownOp(op){
    showHelp('Unknown operation "' + op + '"');
    process.exit(1);
}

let positionalArgs = argv._.slice();

if( positionalArgs.length < 1 ) {
    incorrectNbOfArgs();
} else {
    (function(){
        const value = ('' + positionalArgs[0]).toLowerCase();

        switch(value){
            case 'start':
            case 'stop':
            case 'kill':
            case 'remove':
                if(positionalArgs.length !== 2) {
                    incorrectNbOfArgs();
                }
                requiredProp = { user: { required: true }, password: { required: true, hidden: true } };
                break;

            case 'deploy':
                if(positionalArgs.length > 2) {
                    incorrectNbOfArgs();
                }
                requiredProp = { user: { required: true }, password: { required: true, hidden: true } };
                break;
            case 'pack':
                if(positionalArgs.length > 3) {
                    incorrectNbOfArgs();
                }
                break;
            case 'settings':
            case 'preferences':
                if(positionalArgs.length < 2 || (positionalArgs.length - 2) % 3 !== 0) {
                    incorrectNbOfArgs();
                }
                requiredProp = { user: { required: true }, password: { required: true, hidden: true } };
                break;
            default :
                unknownOp(positionalArgs[0]);
                break;

        }

        settings['operation'] = value;
        positionalArgs.shift();
    })();

    if(settings['operation'] === 'deploy'){
        settings['file'] = path.resolve(process.cwd(), '' + (positionalArgs.shift() || '.'));
    } else if(settings['operation'] === 'pack'){
        settings['directory'] = path.resolve(process.cwd(), '' + (positionalArgs.shift() || '.'));

        let out = positionalArgs.shift();
        settings['output'] = out
            ? path.resolve(process.cwd(), '' + out)
            : null;
    } else {
        settings['service'] = '' + positionalArgs.shift();
    }

    if(settings['operation'] === 'preferences') {
        // scan for properties one may want to set
        if (positionalArgs.indexOf('pref') > -1 && positionalArgs.length >= 3) {
            const nPref = {};
            for (let i=0; i<positionalArgs.length;i++) {
                if (positionalArgs[i] === 'pref') {
                    let setName = positionalArgs[i + 1];
                    let setValue = positionalArgs[i + 2];

                    if (setValue === 'true') {
                        nPref[setName] = true;
                    } else if (setValue === 'false') {
                        nPref[setName] = false;
                    } else {
                        nPref[setName] = setValue;
                    }
                    i += 2;
                }
            }
            settings['preferences'] = nPref;
        }
    }

    if(settings['operation'] ==='settings') {
        // scan for settings that should be changed
        if (positionalArgs.indexOf('set') > -1 && positionalArgs.length >= 3) {
            const nSet = {};
            for (let i=0; i<positionalArgs.length; i++) {
                if (positionalArgs[i] === 'set') {
                    let setName = positionalArgs[i + 1];
                    nSet[setName] = positionalArgs[i + 2];
                    i += 2;
                }
            }
            settings['settings'] = nSet;
        }
    }
}

if( argv['u'] || argv['user']){
    settings['user'] = argv['u'] || argv['user'];
}
if( argv['P'] || argv['password']){
    settings['password'] = argv['P'] || argv['password'];
}

settings['host'] = argv['h'] || argv['host'] || 'localhost';
settings['node'] =  argv['n'] || argv['node'] || settings['host'];

if( argv['p'] || argv['port']){
    (function(){
        const port = parseInt(argv['p'] || argv['port']);
        if(isNaN(port)){
            showHelp('Port has to be an integer number.');
            process.exit(1);
        } else {
            settings['port'] = port || 8080;
        }
    })();
} else {
    settings['port'] = 8080;
}

if( argv['N'] || argv['nodejs']){
    settings['nodejs'] = true;
}

settings['git'] = argv['g'] || argv['git'];
settings['shrinkwrap'] = argv['s'] || argv['shrinkwrap'];

if( argv['j'] || argv['java']){
    settings['java'] = true;
}

// Deployment options
settings['options'] = {
    startup:                 false,
    overwrite:               false,
    overwrite_settings:      false,
    npm_install:             false,
    npm_install_run_scripts: false
};

if( settings['operation'] === 'deploy'){
    if(argv['o'] || argv['option'] || argv['options']){
        (function(){
            const options = (argv['o'] || argv['option'] || argv['options']).split(',');
            if(options.length){
                options.forEach(function(option){
                    const o = option.split('=');
                    switch(o[0]){
                        case 'startup' :
                            settings['options'].startup = true;
                            break;
                        case 'overwrite':
                            settings['options'].overwrite = true;
                            break;
                        case 'settings':
                            settings['options'].overwrite_settings = true;
                            break;
                        case 'npm_install_run_scripts':
                            settings['options'].npm_install_run_scripts = true;
                        //noinspection FallThroughInSwitchStatementJS
                        case 'npm_install':
                            settings['options'].npm_install = true;
                            break;
                        case 'instance_name':
                            settings['options'].instance_name = o[1];
                            break;
                        default:
                            showHelp('Unknown option "' + option + '".');
                            process.exit(1);
                    }
                });
            }
        })();
    }
} else {
    if (settings['nodejs'] && settings['java']) {
        showHelp('You must not use Node.js and Java mode simultaneously.')
    }
}

prompt.override = settings;
prompt.message = "Bridge";
prompt.delimiter = ' ';

// Ask user for missing required options.
// The more convenient prompt#addProperties API is broken
prompt.start().get({ properties: requiredProp }, function (err, result) {

    // if all options given on command line, we get the original object as error. From my point of view it's stupid
    // but we have to deal with it.
    if(err) {
        process.stderr.write(JSON.stringify(err, null, '\t'));
        process.exit(3);
    } else {
        Object.keys(result).forEach(function(key){
            settings[key] = result[key];
        })
    }

    process.stdout.write('Working, please wait.\n');

    perform(settings, function (error, result) {
        let out = [settings.operation, ' ', settings.service || settings.file, ': '].join('');
        let err = '';
        if (error) {
            out += 'FAILED\n'.red;
            if (error.errorType) {
                err += 'Type: ' + error.errorType + '\n';
                if (error.error && error.error.message) {
                    err += 'Message: ' + error.error.message;
                } else {
                    err += util.inspect(error, {depth:3});
                }
            } else {
                err += util.inspect(error, {depth:3});
            }
            err += '\n';
            process.stdout.write(out);
            process.stderr.write(err);
            process.exit(2);
        } else {
            out += 'SUCCESS\n'.green;
            process.stdout.write(out);
            if(result) {
                process.stdout.write(util.inspect(result, {depth: 3}) + '\n');
            }
            process.exit(0);
        }
    });
});

/**
 * Displays usage help.
 * @param {?string=} message Additional message to display
 */
function showHelp(message) {
    if( message){
        process.stdout.write(message + '\n');
    }

    process.stdout.write(
        'Usage:\n' +
        'start|stop|remove ${ServiceName} [[-N|--nodejs]|[-j|--java]] [settings]\n' +
        'kill ${ServiceName} [settings]\n' +
        'deploy [${path/to/repository}|${path/to/directory}] [settings] [-o options]\n'+
        'pack [${path/to/directory}] [${path/to/repository}] [-g|--git] [-s|--shrinkwrap]\n'+
        'preferences ${ServiceName} [pref ${PreferenceName} ${PreferenceValue}]... [settings]\n' +
        'settings ${ServiceName} [set ${SettingsName} ${SettingValue}]... [settings]\n' +
        '--help\n\n' +
            'settings:\n' +
            '\t-h|--host <FQDN bridge host> The host, that runs the bridge. Defaults to localhost.\n' +
            '\t-p|--port <bridge port> The port of the bridge. Defaults to 8080.\n' +
            '\t-n|--node <node name> The name of bridge node. Ignored for deployment. Defaults to ${host}.\n' +
            "\t-u|--user <bridge user> User that has the right to perform operation on bridge.\n" +
            "\t\tRequired. If not given, you'll be prompted for it.\n" +
            "\t-P|--password <password for bridge user> Password for the user.\n" +
            "\t\tRequired. If not given, you'll prompted for it, what is recommended as giving your password\n" +
            "\t\tin command line will expose it in your shell's history. Password is masked during prompt.\n\n" +
            'options:\n' +
            '\tstartup|overwrite|settings Multiple options can be separated by comma, like: "-o startup,overwrite"+\n' +
            '\t\tstartup: Launch service after deployment.\n' +
            '\t\toverwrite: Overwrite existing service if one already exists.\n' +
            '\t\tsettings: Overwrite settings and preferences too.\n' +
            "\t\tnpm_install: Run 'npm install' (Applies to Node.js services only).\n" +
            "\t\tnpm_install_run_scripts: Run 'npm install' (running scripts too) (Applies to Node.js services" +
            " only).\n\n" +
            'Other:\n' +
            '\t-N|--nodejs Assume that the service is a Node.js service. This is ignored for "deploy" and illegal for "kill".\n\n\n' +
            '\t-j|--java Assume that the service is a Java service. This is ignored for "deploy" and illegal for "kill".\n\n\n' +
            '\t-g|--git Use "git archive" for building the repository. This is ignored for all commands but "pack".\n\n\n' +
            '\t-s|--shrinkwrap Execute "npm shrinkwrap" before creating the repository. This is ignored for all commands but "pack".\n\n\n'

    );
}

/**
 * Do the actual work.
 * Take the options we have calculated and do something useful at last.
 * @param options   Set of known options. Calculated from command line and prompt.
 * @param callback  Let others know, that we're done here.
 * @returns {*} Null or whatever the callback returns.
 */
function perform(options, callback){
    const bridgeInstance = new E2EBridge(options.host, options.port, options.user, options.password);
    // noinspection FallThroughInSwitchStatementJS
    switch(options.operation){
        case 'kill':
            if(options.nodejs){
                return callback({ errorType: 'Logic error', error: 'Kill operation is not supported for Node.js services'});
            }
        case 'start':
        case 'stop':
            bridgeInstance.setServiceStatus(options.operation, options.service, getMode(options), options.node, callback);
            return null;

        case 'remove':
            bridgeInstance.removeService(options.service, getMode(options), options.node, callback);
            return null;

        case 'deploy':
            bridgeInstance.deployService(options.file, options.options, callback);
            return null;

        case 'pack':
            E2EBridge.pack(options.directory, options, callback);
            return null;

        case 'preferences':
            if(options.preferences) {
                bridgeInstance.setServicePreferences(options.service, getMode(options), options.preferences, callback);
            } else {
                bridgeInstance.getServicePreferences(options.service, getMode(options), callback);
            }
            return null;
        case 'settings':
            if(options.settings) {
                bridgeInstance.setServiceSettings(options.service, getMode(options), options.settings, callback);
            } else {
                bridgeInstance.getServiceSettings(options.service, getMode(options), callback);
            }
            return null;
    }
    // Should not happen
    return callback({
        errorType: 'BUG',
        error: '"perform" fed with incorrect operation. Please report the problem. Please attach your command line invocation.'
    });
}

function getMode(options) {
    return options.nodejs ? NODE_SERVICE_TYPE : options.java ? JAVA_SERVICE_TYPE : XUML_SERVICE_TYPE;
}

<commit_msg>refactor: app.js: remove redundant process.cwd() for path.resolve()<commit_after>#!/usr/bin/env node

'use strict';

const E2EBridge = require('e2e-bridge-lib');
const util = require('util');
const argv = require('minimist')(process.argv.slice(2));
const prompt = require('prompt');
const path = require('path');

const XUML_SERVICE_TYPE = 'xUML';
const NODE_SERVICE_TYPE = 'node';
const JAVA_SERVICE_TYPE = 'java';

if(argv['help']) {
    showHelp();
    process.exit(0);
}

const settings = {};
let requiredProp = {};

function incorrectNbOfArgs(){
    showHelp('Incorrect number of arguments');
    process.exit(1);
}

function unknownOp(op){
    showHelp('Unknown operation "' + op + '"');
    process.exit(1);
}

let positionalArgs = argv._.slice();

if( positionalArgs.length < 1 ) {
    incorrectNbOfArgs();
} else {
    (function(){
        const value = ('' + positionalArgs[0]).toLowerCase();

        switch(value){
            case 'start':
            case 'stop':
            case 'kill':
            case 'remove':
                if(positionalArgs.length !== 2) {
                    incorrectNbOfArgs();
                }
                requiredProp = { user: { required: true }, password: { required: true, hidden: true } };
                break;

            case 'deploy':
                if(positionalArgs.length > 2) {
                    incorrectNbOfArgs();
                }
                requiredProp = { user: { required: true }, password: { required: true, hidden: true } };
                break;
            case 'pack':
                if(positionalArgs.length > 3) {
                    incorrectNbOfArgs();
                }
                break;
            case 'settings':
            case 'preferences':
                if(positionalArgs.length < 2 || (positionalArgs.length - 2) % 3 !== 0) {
                    incorrectNbOfArgs();
                }
                requiredProp = { user: { required: true }, password: { required: true, hidden: true } };
                break;
            default :
                unknownOp(positionalArgs[0]);
                break;

        }

        settings['operation'] = value;
        positionalArgs.shift();
    })();

    if(settings['operation'] === 'deploy'){
        settings['file'] = path.resolve('' + (positionalArgs.shift() || '.'));
    } else if(settings['operation'] === 'pack'){
        settings['directory'] = path.resolve('' + (positionalArgs.shift() || '.'));

        let out = positionalArgs.shift();
        settings['output'] = out
            ? path.resolve('' + out)
            : null;
    } else {
        settings['service'] = '' + positionalArgs.shift();
    }

    if(settings['operation'] === 'preferences') {
        // scan for properties one may want to set
        if (positionalArgs.indexOf('pref') > -1 && positionalArgs.length >= 3) {
            const nPref = {};
            for (let i=0; i<positionalArgs.length;i++) {
                if (positionalArgs[i] === 'pref') {
                    let setName = positionalArgs[i + 1];
                    let setValue = positionalArgs[i + 2];

                    if (setValue === 'true') {
                        nPref[setName] = true;
                    } else if (setValue === 'false') {
                        nPref[setName] = false;
                    } else {
                        nPref[setName] = setValue;
                    }
                    i += 2;
                }
            }
            settings['preferences'] = nPref;
        }
    }

    if(settings['operation'] ==='settings') {
        // scan for settings that should be changed
        if (positionalArgs.indexOf('set') > -1 && positionalArgs.length >= 3) {
            const nSet = {};
            for (let i=0; i<positionalArgs.length; i++) {
                if (positionalArgs[i] === 'set') {
                    let setName = positionalArgs[i + 1];
                    nSet[setName] = positionalArgs[i + 2];
                    i += 2;
                }
            }
            settings['settings'] = nSet;
        }
    }
}

if( argv['u'] || argv['user']){
    settings['user'] = argv['u'] || argv['user'];
}
if( argv['P'] || argv['password']){
    settings['password'] = argv['P'] || argv['password'];
}

settings['host'] = argv['h'] || argv['host'] || 'localhost';
settings['node'] =  argv['n'] || argv['node'] || settings['host'];

if( argv['p'] || argv['port']){
    (function(){
        const port = parseInt(argv['p'] || argv['port']);
        if(isNaN(port)){
            showHelp('Port has to be an integer number.');
            process.exit(1);
        } else {
            settings['port'] = port || 8080;
        }
    })();
} else {
    settings['port'] = 8080;
}

if( argv['N'] || argv['nodejs']){
    settings['nodejs'] = true;
}

settings['git'] = argv['g'] || argv['git'];
settings['shrinkwrap'] = argv['s'] || argv['shrinkwrap'];

if( argv['j'] || argv['java']){
    settings['java'] = true;
}

// Deployment options
settings['options'] = {
    startup:                 false,
    overwrite:               false,
    overwrite_settings:      false,
    npm_install:             false,
    npm_install_run_scripts: false
};

if( settings['operation'] === 'deploy'){
    if(argv['o'] || argv['option'] || argv['options']){
        (function(){
            const options = (argv['o'] || argv['option'] || argv['options']).split(',');
            if(options.length){
                options.forEach(function(option){
                    const o = option.split('=');
                    switch(o[0]){
                        case 'startup' :
                            settings['options'].startup = true;
                            break;
                        case 'overwrite':
                            settings['options'].overwrite = true;
                            break;
                        case 'settings':
                            settings['options'].overwrite_settings = true;
                            break;
                        case 'npm_install_run_scripts':
                            settings['options'].npm_install_run_scripts = true;
                        //noinspection FallThroughInSwitchStatementJS
                        case 'npm_install':
                            settings['options'].npm_install = true;
                            break;
                        case 'instance_name':
                            settings['options'].instance_name = o[1];
                            break;
                        default:
                            showHelp('Unknown option "' + option + '".');
                            process.exit(1);
                    }
                });
            }
        })();
    }
} else {
    if (settings['nodejs'] && settings['java']) {
        showHelp('You must not use Node.js and Java mode simultaneously.')
    }
}

prompt.override = settings;
prompt.message = "Bridge";
prompt.delimiter = ' ';

// Ask user for missing required options.
// The more convenient prompt#addProperties API is broken
prompt.start().get({ properties: requiredProp }, function (err, result) {

    // if all options given on command line, we get the original object as error. From my point of view it's stupid
    // but we have to deal with it.
    if(err) {
        process.stderr.write(JSON.stringify(err, null, '\t'));
        process.exit(3);
    } else {
        Object.keys(result).forEach(function(key){
            settings[key] = result[key];
        })
    }

    process.stdout.write('Working, please wait.\n');

    perform(settings, function (error, result) {
        let out = [settings.operation, ' ', settings.service || settings.file, ': '].join('');
        let err = '';
        if (error) {
            out += 'FAILED\n'.red;
            if (error.errorType) {
                err += 'Type: ' + error.errorType + '\n';
                if (error.error && error.error.message) {
                    err += 'Message: ' + error.error.message;
                } else {
                    err += util.inspect(error, {depth:3});
                }
            } else {
                err += util.inspect(error, {depth:3});
            }
            err += '\n';
            process.stdout.write(out);
            process.stderr.write(err);
            process.exit(2);
        } else {
            out += 'SUCCESS\n'.green;
            process.stdout.write(out);
            if(result) {
                process.stdout.write(util.inspect(result, {depth: 3}) + '\n');
            }
            process.exit(0);
        }
    });
});

/**
 * Displays usage help.
 * @param {?string=} message Additional message to display
 */
function showHelp(message) {
    if( message){
        process.stdout.write(message + '\n');
    }

    process.stdout.write(
        'Usage:\n' +
        'start|stop|remove ${ServiceName} [[-N|--nodejs]|[-j|--java]] [settings]\n' +
        'kill ${ServiceName} [settings]\n' +
        'deploy [${path/to/repository}|${path/to/directory}] [settings] [-o options]\n'+
        'pack [${path/to/directory}] [${path/to/repository}] [-g|--git] [-s|--shrinkwrap]\n'+
        'preferences ${ServiceName} [pref ${PreferenceName} ${PreferenceValue}]... [settings]\n' +
        'settings ${ServiceName} [set ${SettingsName} ${SettingValue}]... [settings]\n' +
        '--help\n\n' +
            'settings:\n' +
            '\t-h|--host <FQDN bridge host> The host, that runs the bridge. Defaults to localhost.\n' +
            '\t-p|--port <bridge port> The port of the bridge. Defaults to 8080.\n' +
            '\t-n|--node <node name> The name of bridge node. Ignored for deployment. Defaults to ${host}.\n' +
            "\t-u|--user <bridge user> User that has the right to perform operation on bridge.\n" +
            "\t\tRequired. If not given, you'll be prompted for it.\n" +
            "\t-P|--password <password for bridge user> Password for the user.\n" +
            "\t\tRequired. If not given, you'll prompted for it, what is recommended as giving your password\n" +
            "\t\tin command line will expose it in your shell's history. Password is masked during prompt.\n\n" +
            'options:\n' +
            '\tstartup|overwrite|settings Multiple options can be separated by comma, like: "-o startup,overwrite"+\n' +
            '\t\tstartup: Launch service after deployment.\n' +
            '\t\toverwrite: Overwrite existing service if one already exists.\n' +
            '\t\tsettings: Overwrite settings and preferences too.\n' +
            "\t\tnpm_install: Run 'npm install' (Applies to Node.js services only).\n" +
            "\t\tnpm_install_run_scripts: Run 'npm install' (running scripts too) (Applies to Node.js services" +
            " only).\n\n" +
            'Other:\n' +
            '\t-N|--nodejs Assume that the service is a Node.js service. This is ignored for "deploy" and illegal for "kill".\n\n\n' +
            '\t-j|--java Assume that the service is a Java service. This is ignored for "deploy" and illegal for "kill".\n\n\n' +
            '\t-g|--git Use "git archive" for building the repository. This is ignored for all commands but "pack".\n\n\n' +
            '\t-s|--shrinkwrap Execute "npm shrinkwrap" before creating the repository. This is ignored for all commands but "pack".\n\n\n'

    );
}

/**
 * Do the actual work.
 * Take the options we have calculated and do something useful at last.
 * @param options   Set of known options. Calculated from command line and prompt.
 * @param callback  Let others know, that we're done here.
 * @returns {*} Null or whatever the callback returns.
 */
function perform(options, callback){
    const bridgeInstance = new E2EBridge(options.host, options.port, options.user, options.password);
    // noinspection FallThroughInSwitchStatementJS
    switch(options.operation){
        case 'kill':
            if(options.nodejs){
                return callback({ errorType: 'Logic error', error: 'Kill operation is not supported for Node.js services'});
            }
        case 'start':
        case 'stop':
            bridgeInstance.setServiceStatus(options.operation, options.service, getMode(options), options.node, callback);
            return null;

        case 'remove':
            bridgeInstance.removeService(options.service, getMode(options), options.node, callback);
            return null;

        case 'deploy':
            bridgeInstance.deployService(options.file, options.options, callback);
            return null;

        case 'pack':
            E2EBridge.pack(options.directory, options, callback);
            return null;

        case 'preferences':
            if(options.preferences) {
                bridgeInstance.setServicePreferences(options.service, getMode(options), options.preferences, callback);
            } else {
                bridgeInstance.getServicePreferences(options.service, getMode(options), callback);
            }
            return null;
        case 'settings':
            if(options.settings) {
                bridgeInstance.setServiceSettings(options.service, getMode(options), options.settings, callback);
            } else {
                bridgeInstance.getServiceSettings(options.service, getMode(options), callback);
            }
            return null;
    }
    // Should not happen
    return callback({
        errorType: 'BUG',
        error: '"perform" fed with incorrect operation. Please report the problem. Please attach your command line invocation.'
    });
}

function getMode(options) {
    return options.nodejs ? NODE_SERVICE_TYPE : options.java ? JAVA_SERVICE_TYPE : XUML_SERVICE_TYPE;
}

<|endoftext|>


<commit_before>var _ = require('underscore'),
  fs = require('fs');

function Writer() {

  function gen(templates, numSegments, params, outFile, cb) {
    var stream = fs.createWriteStream(outFile,
        { flags: 'w', encoding: 'utf-8' }),
      segmentId = 0,
      segment;

    stream.on('error', function (err) {
      console.error('Error: ' + err);
    });

    stream.on('close', function () {
      cb();
    });

    stream.write(templates.header);

    while (segmentId++ < numSegments) {
      segment = templates.segment;
      params.segment_id = segmentId;

      function _apply(param) {
        segment = segment.replace(new RegExp('{' + param + '}', 'g'), params[param]);
      }

      _.keys(params).forEach(_apply);
      stream.write(segment);
    }

    stream.end(templates.footer);
  }

  return {
    gen: gen
  };
}

exports.Writer = Writer;<commit_msg>Clean up lint violations.<commit_after>var _ = require('underscore'),
  fs = require('fs');

function Writer() {

  function gen(templates, numSegments, params, outFile, cb) {
    var stream = fs.createWriteStream(outFile,
        { flags: 'w', encoding: 'utf-8' }),
      segmentId = 0;

    stream.on('error', function (err) {
      console.error('Error: ' + err);
    });

    stream.on('close', function () {
      cb();
    });

    stream.write(templates.header);

    function _writeSegment(segmentId) {
      var segment = templates.segment;
      params.segment_id = segmentId;

      function _apply(param) {
        segment = segment.replace(new RegExp('{' + param + '}', 'g'), params[param]);
      }

      _.keys(params).forEach(_apply);
      stream.write(segment);
    }

    while (segmentId++ < numSegments) {
      _writeSegment(segmentId);
    }

    stream.end(templates.footer);
  }

  return {
    gen: gen
  };
}

exports.Writer = Writer;<|endoftext|>


<commit_before>const dotenv = require('dotenv');
const express = require('express');
const app = express();
const api = require('./ApiRequest');
const actions = require('./utils/actions');
const bodyParser = require('body-parser');
const imageURL = 'https://emojis-as-a-service.herokuapp.com/images/'
dotenv.config({
    silent: true
});
var path = require('path');
var formidable = require('formidable');
var fs = require('fs');
const ROOT = "./public_html";
app.use(function (req, res, next) {
    console.log(req.method + " request for " + req.url);
    next();
});
app.use(bodyParser.json());

function process(res, data) {
    if (!data.status_code) {
        console.log(data);
        res.send(data);
    }
    if (data.status_code === 4 && data.frames) {
        actions.getAllEmojis(data.frames[0], () => {
            console.log(`EMOJI: ${data.frames[0]}`);
        })
    } else if (data.status_code === 2) {
      setTimeout(() => {
        api.get(data.id, (newData) => {
          process(res, newData)
        });
      }, 500);
    } else {
        console.log(data);
        // this is purely a safety net
    }
}

app.post('/upload', function (req, res) {
    // create an incoming form object
    var form = new formidable.IncomingForm();
    // specify that we want to allow the user to upload multiple files in a single request
    form.multiples = true;
    // store all uploads in the /uploads directory
    form.uploadDir = path.join(__dirname, '/uploads');
    // every time a file has been uploaded successfully,
    // rename it to it's orignal name
    form.on('file', function (field, file) {
        fs.rename(file.path, file.path + path.extname(file.name), function (err) {
            if (err) return res.send(err);
            file.path = file.path + path.extname(file.name);
            file.name = path.basename(file.path);
            res.send(imageURL + file.name);
            api.post(imageURL + file.name).then((data) => {
              process(res, data);
            }).catch((error) => {
                console.log(error);
                res.send(error);
            });
        });
    });

    // log any errors that occur
    form.on('error', function (err) {
        console.log('An error has occured: \n' + err);
    });
    // once all the files have been uploaded, send a response to the client
    form.on('end', function () {
        // res.end('success');
    });
    // parse the incoming request containing the form data
    form.parse(req);
});
app.post('/slack', function (req, res) {
    console.log(req.body.image_url);
    api(req.body.image_url).then((imageData) => {
        /*actions.getAllEmojis(imageData.frames[0], () => {
        res.sendFilexfile.path);
      })*/
        res.json({
            url: 'http://static6.businessinsider.com/image/55918b77ecad04a3465a0a63/nbc-fires-donald-trump-after-he-calls-mexicans-rapists-and-drug-runners.jpg'
        });
    }).catch((error) => {
        console.log(error);
        res.send(error);
    });
});
app.use('/images', express.static('./uploads'));
app.use(express.static(ROOT)); //handle all static requests
app.all("*", function (req, res) {
    res.sendStatus(404);
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
    console.log(`Express server listening on port ${port}`);
})
<commit_msg>resolved symbol conflict<commit_after>const dotenv = require('dotenv');
const express = require('express');
const app = express();
const api = require('./ApiRequest');
const actions = require('./utils/actions');
const bodyParser = require('body-parser');
const imageURL = 'https://emojis-as-a-service.herokuapp.com/images/'
dotenv.config({
    silent: true
});
var path = require('path');
var formidable = require('formidable');
var fs = require('fs');
const ROOT = "./public_html";
app.use(function (req, res, next) {
    console.log(req.method + " request for " + req.url);
    next();
});
app.use(bodyParser.json());

function processAPIData(res, data) {
    if (!data.status_code) {
        console.log(data);
        res.send(data);
    }
    if (data.status_code === 4 && data.frames) {
        actions.getAllEmojis(data.frames[0], () => {
            console.log(`EMOJI: ${data.frames[0]}`);
        })
    } else if (data.status_code === 2) {
      setTimeout(() => {
        api.get(data.id, (newData) => {
          processAPIData(res, newData)
        });
      }, 500);
    } else {
        console.log(data);
        // this is purely a safety net
    }
}

app.post('/upload', function (req, res) {
    // create an incoming form object
    var form = new formidable.IncomingForm();
    // specify that we want to allow the user to upload multiple files in a single request
    form.multiples = true;
    // store all uploads in the /uploads directory
    form.uploadDir = path.join(__dirname, '/uploads');
    // every time a file has been uploaded successfully,
    // rename it to it's orignal name
    form.on('file', function (field, file) {
        fs.rename(file.path, file.path + path.extname(file.name), function (err) {
            if (err) return res.send(err);
            file.path = file.path + path.extname(file.name);
            file.name = path.basename(file.path);
            res.send(imageURL + file.name);
            api.post(imageURL + file.name).then((data) => {
              processAPIData(res, data);
            }).catch((error) => {
                console.log(error);
                res.send(error);
            });
        });
    });

    // log any errors that occur
    form.on('error', function (err) {
        console.log('An error has occured: \n' + err);
    });
    // once all the files have been uploaded, send a response to the client
    form.on('end', function () {
        // res.end('success');
    });
    // parse the incoming request containing the form data
    form.parse(req);
});
app.post('/slack', function (req, res) {
    console.log(req.body.image_url);
    api(req.body.image_url).then((imageData) => {
        /*actions.getAllEmojis(imageData.frames[0], () => {
        res.sendFilexfile.path);
      })*/
        res.json({
            url: 'http://static6.businessinsider.com/image/55918b77ecad04a3465a0a63/nbc-fires-donald-trump-after-he-calls-mexicans-rapists-and-drug-runners.jpg'
        });
    }).catch((error) => {
        console.log(error);
        res.send(error);
    });
});
app.use('/images', express.static('./uploads'));
app.use(express.static(ROOT)); //handle all static requests
app.all("*", function (req, res) {
    res.sendStatus(404);
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
    console.log(`Express server listening on port ${port}`);
})
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs');
var sets = require('simplesets');
var os = require('os');

app.use(express.static('static'));
app.set('view engine', 'jade');

// Create a set to hold the names added to the tree
var names = new sets.Set();

// TODO: Create a queue of dictionaries(name: socket) to
// collect the names to be moderated

// Initialize whitelist and black list
var white_list = new sets.Set();
load_file(white_list, 'special_names/whitelist.txt');
var black_list = new sets.Set();
load_file(black_list, 'special_names/blacklist.txt');

// Load the given file and put the content into the given set
function load_file(s, file) {
  fs.readFile(file, 'utf8', function(err, data) {
    if (err) {
      return console.log(err);
    }
    t = data.split(/\r?\n/);
    for (var i = 0; i < t.length; i++) {
      s.add(t[i].toLowerCase());
    }
    console.log("Finished loading " + file);
  });
};

// Handle when a person goes to the index page
app.get('/', function (req, res){
  res.render('index');
});

// Handle when someone goes to the tree page
app.get('/tree', function (req, res){
  res.render('tree', {names: names});
});

// Handle when someone goes to the moderator page
app.get('/moderator', function (req, res){
  res.render('moderator', {names: names});
});

io.on('connection', function(socket){
  console.log('A user connected from: ' + socket.handshake.address);

  // Handle when the user sends a name to be verified
  socket.on('verify name', function(msg){
    console.log('Attempting to add name ' + msg);

    // Create variables to assess the validity of the name
    var nameElements = msg.split(/[-\s]/);
    var nameScore = 0;
    var nameInfo = {"name":"", "accepted":""};
    nameInfo['name'] = msg;
    nameInfo['action'] = "denied";

    // Notify the user that they cannot use the name they have
    // provided because it contains illegal characters
    var englishLetters = /[^a-zA-Z]/;
    var cNum;
    for(cNum = 0; cNum < msg.length; cNum++)
    {
      if(englishLetters.test(msg[cNum]) && (msg[cNum] !== "-") && (msg[cNum] !== "'") && (msg[cNum] !== " "))
      {
        // Update the tree and thank the user
        nameInfo['action'] = "illegal";

        socket.emit('end interaction', nameInfo);

        console.log('The name ' + msg + ' contains an illegal character');

        return;
      }
    }

    // TODO: Inform the user that their name is already on the tree
    // Inform the user that their name is already on the tree
    // or (TODO) on the queue of names for the moderator
    if(names.has(msg))
    {
      // Update the tree and thank the user
      nameInfo['action'] = "duplicate";

      socket.emit('end interaction', nameInfo);

      console.log('The name ' + msg + ' is a duplicate');

      return;
    }

    // Verify that the name as a whole is on the blacklist
    if (black_list.has(msg.toLowerCase())) {
      // Update the tree and thank the user
      nameInfo['action'] = "declined";

      socket.emit('end interaction', nameInfo);

      console.log('The word ' + msg + ' is on the blacklist');

      return;
    }

    // Verify that all of the separate words in the name are
    // on the whitelist
    var i;
    var numElements = nameElements.length;

    for(i = 0; i < numElements; i++)
    {
      if(white_list.has(nameElements[i].toLowerCase()))
      {
        nameScore += 1;
      }
    }

    if(nameScore == nameElements.length)
    {
      // Update the tree and thank the user
      nameInfo['action'] = "accepted";

      socket.emit('end interaction', nameInfo);

      // Add the current name to the list of names
      names.add(msg);

      // Push the name to the tree
      socket.emit('add name', msg);

      console.log('The name ' + msg + ' is on the whitelist');

      return;
    }

    // TODO: Send the name to a queue

    // Send the name to the moderator to verify
    io.emit('moderate name', msg);

    console.log('The name ' + msg + ' was sent to the moderator');
  });

  // TODO: Add functionality to give the moderator a name when asked

  // Submit the name to be added to the proper lists and/or the tree
  socket.on('submit name info', function(msgInfo){
    // Get the name from the parameter
    var name = msgInfo['name'];

    // Check if the name was accepted by the moderator
    if(msgInfo['action'] == 'accepted')
    {
      // Add the various words in the name to the whitelist
      whitelistName(name);

      // Add the current name to the list of names
      names.add(msg);

      // Push the name to the tree
      socket.emit('add name', name);

      console.log('The name ' + name + ' has been whitelisted');
    }
    else
    {
      // Add the name to the blacklist
      black_list.add(name);

      // TODO: Display the error notification to the user

      console.log('The name ' + name + ' has been blacklisted');
    }

    // Update the tree and thank the user
    socket.emit('end interaction', msgInfo);
  });
});

// Add the words in the provided name to the whitelist
function whitelistName(name)
{
  var nameElements = name.split(" ");
  var i;
  var numEleNames = nameElements.length;

  // Go through all of the words in the name
  for(i = 0; i < numEleNames; i++)
  {
    // Verify whether the word is greater than 3 characters
    var word = nameElements[i];
    if(word.length > 2)
    {
      // Add the current word to the whitelist
      white_list.add(word.toLowerCase());
    }
  }
}

http.listen(3000, function(){
  console.log('Listening on port 3000!');
});
<commit_msg>Bug Fix: Fix moderation output<commit_after>var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs');
var sets = require('simplesets');
var os = require('os');

app.use(express.static('static'));
app.set('view engine', 'jade');

// Create a set to hold the names added to the tree
var names = new sets.Set();

// TODO: Create a queue of dictionaries(name: socket) to
// collect the names to be moderated
var userList = {};

// Initialize whitelist and black list
var white_list = new sets.Set();
load_file(white_list, 'special_names/whitelist.txt');
var black_list = new sets.Set();
load_file(black_list, 'special_names/blacklist.txt');

// Load the given file and put the content into the given set
function load_file(s, file) {
  fs.readFile(file, 'utf8', function(err, data) {
    if (err) {
      return console.log(err);
    }
    t = data.split(/\r?\n/);
    for (var i = 0; i < t.length; i++) {
      s.add(t[i].toLowerCase());
    }
    console.log("Finished loading " + file);
  });
};

// Handle when a person goes to the index page
app.get('/', function (req, res){
  res.render('index');
});

// Handle when someone goes to the tree page
app.get('/tree', function (req, res){
  res.render('tree', {names: names});
});

// Handle when someone goes to the moderator page
app.get('/moderator', function (req, res){
  res.render('moderator', {names: names});
});

io.on('connection', function(socket){
  console.log('A user connected from: ' + socket.handshake.address);

  // Handle when the user sends a name to be verified
  socket.on('verify name', function(msg){
    console.log('Attempting to add name ' + msg);

    // Create variables to assess the validity of the name
    var nameElements = msg.split(/[-\s]/);
    var nameScore = 0;
    var nameInfo = {"name":"", "accepted":""};
    nameInfo['name'] = msg;
    nameInfo['action'] = "denied";

    // Notify the user that they cannot use the name they have
    // provided because it contains illegal characters
    var englishLetters = /[^a-zA-Z]/;
    var cNum;
    for(cNum = 0; cNum < msg.length; cNum++)
    {
      if(englishLetters.test(msg[cNum]) && (msg[cNum] !== "-") && (msg[cNum] !== "'") && (msg[cNum] !== " "))
      {
        // Update the tree and thank the user
        nameInfo['action'] = "illegal";

        socket.emit('end interaction', nameInfo);

        console.log('The name ' + msg + ' contains an illegal character');

        return;
      }
    }

    // TODO: Inform the user that their name is already on the tree
    // Inform the user that their name is already on the tree
    // or (TODO) on the queue of names for the moderator
    if(names.has(msg))
    {
      // Update the tree and thank the user
      nameInfo['action'] = "duplicate";

      socket.emit('end interaction', nameInfo);

      console.log('The name ' + msg + ' is a duplicate');

      return;
    }

    // Verify that the name as a whole is on the blacklist
    if (black_list.has(msg.toLowerCase())) {
      // Update the tree and thank the user
      nameInfo['action'] = "declined";

      socket.emit('end interaction', nameInfo);

      console.log('The word ' + msg + ' is on the blacklist');

      return;
    }

    // Verify that all of the separate words in the name are
    // on the whitelist
    var i;
    var numElements = nameElements.length;

    for(i = 0; i < numElements; i++)
    {
      if(white_list.has(nameElements[i].toLowerCase()))
      {
        nameScore += 1;
      }
    }

    if(nameScore == nameElements.length)
    {
      // Update the tree and thank the user
      nameInfo['action'] = "accepted";

      socket.emit('end interaction', nameInfo);

      // Add the current name to the list of names
      names.add(msg);

      // Push the name to the tree
      socket.emit('add name', msg);

      console.log('The name ' + msg + ' is on the whitelist');

      return;
    }

    // TODO: Send the name to a queue
    // Add the current name and socket info to the list
    userList[msg] = socket;

    // Send the name to the moderator to verify
    io.emit('moderate name', msg);

    console.log('The name ' + msg + ' was sent to the moderator');
  });

  // TODO: Add functionality to give the moderator a name when asked

  // Submit the name to be added to the proper lists and/or the tree
  socket.on('submit name info', function(msgInfo){
    // Get the name from the parameter
    var name = msgInfo['name'];
    var curSocket = userList[name];

    // Check if the name is in the list of names
    if(curSocket === undefined)
    {
      console.log('Error: Name not in list.');
      return;
    }

    // Check if the name was accepted by the moderator
    if(msgInfo['action'] == 'accepted')
    {
      // Add the various words in the name to the whitelist
      whitelistName(name);

      // Add the current name to the list of names
      names.add(name);

      // Push the name to the tree
      socket.emit('add name', name);

      console.log('The name ' + name + ' has been whitelisted');
    }
    else
    {
      // Add the name to the blacklist
      black_list.add(name);

      // TODO: Display the error notification to the user

      console.log('The name ' + name + ' has been blacklisted');
    }

    // Update the tree and thank the user
    curSocket.emit('end interaction', msgInfo);
  });
});

// Add the words in the provided name to the whitelist
function whitelistName(name)
{
  var nameElements = name.split(" ");
  var i;
  var numEleNames = nameElements.length;

  // Go through all of the words in the name
  for(i = 0; i < numEleNames; i++)
  {
    // Verify whether the word is greater than 3 characters
    var word = nameElements[i];
    if(word.length > 2)
    {
      // Add the current word to the whitelist
      white_list.add(word.toLowerCase());
    }
  }
}

http.listen(3000, function(){
  console.log('Listening on port 3000!');
});
<|endoftext|>


<commit_before>'use babel';

import YeomanView from './yeoman-view';
import { CompositeDisposable } from 'atom';
import {React, ReactDOM} from 'react-for-atom'
import YeomanRightPanel from './components/YeomanRightPanel';
import YeomanModalPanel from './components/YeomanModalPanel';

export default {

  yeomanView: null,
  rightPanel: null,
  modalPanel: null,
  subscriptions: null,
  modalYeomanView: null,

  activate(state) {
    this.yeomanView = new YeomanView(state.yeomanViewState);
    this.rightPanel = atom.workspace.addRightPanel({
      item: this.yeomanView.getElement(),
      visible: false
    });
    this.modalYeomanView = new YeomanView(state.yeomanModalViewState);
    this.modalPanel = atom.workspace.addModalPanel({
      item: this.modalYeomanView.getElement(),
      visible: false
    });
    ReactDOM.render(<YeomanRightPanel/>, this.yeomanView.getElement());
    // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
    this.subscriptions = new CompositeDisposable();

    // Register command that toggles this view
    this.subscriptions.add(atom.commands.add('atom-workspace', {
      'yeoman:toggle': () => this.toggle(),
    }));
  },

  deactivate() {
    this.rightPanel.destroy();
    this.modalPanel.destroy();
    this.subscriptions.dispose();
    this.yeomanView.destroy();
  },

  serialize() {
    return {
      yeomanViewState: this.yeomanView.serialize(),
      yeomanModalViewState: this.modalYeomanView.serialize(),
    };
  },

  consumeTaskRunner: function(taskRunner) {
    this.taskRunner = taskRunner;
  },

  toggle() {
    console.log('Yeoman was toggled!');
    return (
      this.rightPanel.isVisible() ?
      this.rightPanel.hide() :
      this.rightPanel.show()
    );
  }

};
<commit_msg>Adds task-runner checker<commit_after>'use babel';

import YeomanView from './yeoman-view';
import { CompositeDisposable } from 'atom';
import {React, ReactDOM} from 'react-for-atom'
import YeomanRightPanel from './components/YeomanRightPanel';
import YeomanModalPanel from './components/YeomanModalPanel';

export default {

  yeomanView: null,
  rightPanel: null,
  modalPanel: null,
  subscriptions: null,
  modalYeomanView: null,

  activate(state) {
    if (!atom.packages.getActivePackage("task-runner")) {
      atom.notifications.addError("Yeoman Package cannot be activated", {detail: "task-runner package not installed"});
      return;
    }
    this.yeomanView = new YeomanView(state.yeomanViewState);
    this.rightPanel = atom.workspace.addRightPanel({
      item: this.yeomanView.getElement(),
      visible: false
    });
    this.modalYeomanView = new YeomanView(state.yeomanModalViewState);
    this.modalPanel = atom.workspace.addModalPanel({
      item: this.modalYeomanView.getElement(),
      visible: false
    });
    ReactDOM.render(<YeomanRightPanel/>, this.yeomanView.getElement());
    // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
    this.subscriptions = new CompositeDisposable();

    // Register command that toggles this view
    this.subscriptions.add(atom.commands.add('atom-workspace', {
      'yeoman:toggle': () => this.toggle(),
    }));
  },

  deactivate() {
    this.rightPanel.destroy();
    this.modalPanel.destroy();
    this.subscriptions.dispose();
    this.yeomanView.destroy();
  },

  serialize() {
    return {
      yeomanViewState: this.yeomanView.serialize(),
      yeomanModalViewState: this.modalYeomanView.serialize(),
    };
  },

  consumeTaskRunner: function(taskRunner) {
    this.taskRunner = taskRunner;
  },

  toggle() {
    console.log('Yeoman was toggled!');
    return (
      this.rightPanel.isVisible() ?
      this.rightPanel.hide() :
      this.rightPanel.show()
    );
  }

};
<|endoftext|>


<commit_before>'use strict';

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const api = require('./routes');

app.use(bodyParser.urlencoded({extended : false}));
app.use(bodyParser.json());

app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
    res.setHeader('Access-Control-Allow-Origin', 'http://exampleangular.s3-website.us-east-2.amazonaws.com:');
    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'Authorization, X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});

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

module.exports = app<commit_msg>Cambio<commit_after>'use strict';

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const api = require('./routes');

app.use(bodyParser.urlencoded({extended : false}));
app.use(bodyParser.json());

app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
    res.setHeader('Access-Control-Allow-Origin', 'http://exampleangular.s3-website.us-east-2.amazonaws.com');
    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'Authorization, X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});

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

module.exports = app<|endoftext|>


<commit_before>// Globals
// Grabs the id's for digits
var hour = document.getElementById('hours'),
    minutes = document.getElementById('minutes'),
    seconds = document.getElementById('seconds'),
    miliseconds = document.getElementById('miliseconds'),

// Grabs the id's for the buttons
    startButton = document.getElementById('startButton'),
    pauseButton =  document.getElementById('pauseButton'),
    stopButton = document.getElementById('stopButton'),
    resetButton = document.getElementById('resetbutton'),

    setTime,
    currentTime,
    difference,
    timer = 0;

// Gets current time and sets the interval
var start = function() {
  setTime = Date.now();
  setInterval(update, 100);
};

// Updates the current time
var update = function() {
  currentTime = Date.now();
  difference = currentTime - setTime;
  timer += difference;

  updateScreen();
  setTime = currentTime;
};

// Converts the current time to miliseconds
var updateScreen = function() {
  miliseconds.innerText = timer/1000;
};

startButton.addEventListener('click', start);
<commit_msg>pause button now works<commit_after>// Globals
// Grabs the id's for digits
var hour = document.getElementById('hours'),
    minutes = document.getElementById('minutes'),
    seconds = document.getElementById('seconds'),
    miliseconds = document.getElementById('miliseconds'),

// Grabs the id's for the buttons
    startButton = document.getElementById('startButton'),
    pauseButton =  document.getElementById('pauseButton'),
    stopButton = document.getElementById('stopButton'),
    resetButton = document.getElementById('resetbutton'),

    setTime,
    currentTime,
    difference,
    timer = 0,
    interval;

// Gets current time and sets the interval
var start = function() {
  setTime = Date.now();
  interval = setInterval(update, 100);
};

// This cancel the setInterval when called
var pause = function() {
  clearInterval(interval);
};

// Updates the current time
var update = function() {
  currentTime = Date.now();
  difference = currentTime - setTime;
  timer += difference;

  updateScreen();
  setTime = currentTime;
};

// Converts the current time to miliseconds
var updateScreen = function() {
  miliseconds.innerText = timer/1000;
};

// Fires the start() when the #startButton is clicked
startButton.addEventListener('click', start);
// Fires the pause() when the #pauseButton is clicked
pauseButton.addEventListener('click', pause);
<|endoftext|>


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

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var op = require('open');
var path = require('path');

var fileName1 = path.normalize(process.argv[2]),
    fileName2 = path.normalize(process.argv[3]),
    filePath1 = path.join(process.cwd(), fileName1),
    filePath2 = path.join(process.cwd(), fileName2);

console.log(filePath1, filePath2);

console.log(process.argv[2]);
console.log(process.cwd());

app.get('/', function(req, res){
   res.sendFile(__dirname + '/index.html');
});

//app.get('/js/bundle.js', function(req, res){
  //  res.sendFile(__dirname + '/js/bundle.js');
//});

io.on('connection', function(socket) {
  console.log('a user connected');
});

var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';

http.listen(port, ip_address, function(){
    console.log( "Listening on:");
    console.log('http://'+ ip_address  + ':' + port + '/');
    op('http://'+ ip_address  + ':' + port + '/');
});
<commit_msg>app.js now serves bundle.js to client.<commit_after>#!/usr/bin/env node

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var op = require('open');
var path = require('path');
var THREE = require('three');
//var THREE.STLLoader() = require('')

var fileName1 = path.normalize(process.argv[2]),
    fileName2 = path.normalize(process.argv[3]),
    filePath1 = path.join(process.cwd(), fileName1),
    filePath2 = path.join(process.cwd(), fileName2);

//console.log(filePath1, filePath2);

//load stl files. In future will modularize and include more formats.

//serve client files

app.get('/', function(req, res){
   res.sendFile(__dirname + '/index.html');
});

app.get('/bundle.js', function(req, res){
    res.sendFile(__dirname + '/bundle.js');
});

io.on('connection', function(socket) {
  console.log('a user connected');
});

var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';

http.listen(port, ip_address, function(){
    console.log( "Listening on:");
    console.log('http://'+ ip_address  + ':' + port + '/');
    op('http://'+ ip_address  + ':' + port + '/');
});
<|endoftext|>


<commit_before>
/*
 *  Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree.
 */

var mediaStream; // Contains video, and possibly added audio track
var audioStream; // Mic only
var recordedChunks = [];
var numrecordedChunks = 0;
var recorder;
var includeMic = false;

document.querySelector('#recDesktop').addEventListener('click', recordDesktop);
document.querySelector('#recCamera').addEventListener('click', recordCamera);
document.querySelector('#recWindow').addEventListener('click', recordWindow);
//document.querySelector('#recTab').addEventListener('click', recordTab);
document.querySelector('#Audio').addEventListener('click', audioCheck);
document.querySelector('#recStop').addEventListener('click', stopStreamsAndDownloadData);

function greyOutButtons(){
  document.querySelector('#recDesktop').disabled=true;
  document.querySelector('#recCamera').disabled=true;
  document.querySelector('#recWindow').disabled=true;
  document.querySelector('#recStop').hidden=false;
}

function enableButtons(){
  console.log('Enabling buttons')
  document.querySelector('#recDesktop').disabled=false;
  document.querySelector('#recCamera').disabled=false;
  document.querySelector('#recWindow').disabled=false;
  document.querySelector('#recStop').hidden=true;
}

function audioCheck() {

  // this won't work in extension

  // Mute video so we don't play loopback audio
  var video = document.querySelector("video");
  video.muted = true;
  // Tooggle state
  includeMic = !includeMic;
  console.log('Audio =', includeMic)

  if (includeMic){
    if (document.getElementById("Audio").checked){
        navigator.webkitGetUserMedia({
        audio:true,
        video: false
    }, gotAudio, getUserMediaError);

    }
  }

};

function recordDesktop(stream) {
  // Start Window picker with Desktop constraints
  recordedChunks = [];
  numrecordedChunks = 0;
  window.resizeTo(646, 565);
  pending_request_id = chrome.desktopCapture.chooseDesktopMedia(
      ["screen"], onAccessApproved);

};

function recordCamera(stream) {

  recordedChunks = [];
  numrecordedChunks = 0;

  navigator.webkitGetUserMedia({
      audio:false,
      video: { mandatory: { minWidth:1280,
                            minHeight:720 } }
  }, gotMediaStream, getUserMediaError);
};

function recordWindow(stream) {

  recordedChunks = [];
  numrecordedChunks = 0;
 // Start Window picker with Desktop constraints
  window.resizeTo(646, 565);
  pending_request_id = chrome.desktopCapture.chooseDesktopMedia(
      ["window"], onAccessApproved);

  // Check Audio inclusion, fire off GUM if needed

};

function recordTab(stream) {
  // Invoke Tab Capture API
};

function gotTab(stream) {

};

function createButton(id, text, onClick) {
  const button = document.createElement("input");
  button.id = id;
  button.type = "button";
  button.value = text;
  button.onclick = onClick;
  document.body.appendChild(button);
  console.log("Button " + id + " created");
}

function recorderOnDataAvailable(event) {
  if (event)
    console.assert(event.data.length > 0, 'Recorded data size should be > 0',event.data.length);
  console.assert(recorder.state == "recording", "State should be 'recording'");

  // Use |byteLength| instead of |length| for event.data;
  recordedChunks.push(event.data);
  numrecordedChunks += event.data.byteLength;
}

function saveByteArray(data, name) {
  var blob = new Blob(data, {type: "video/webm"});
  var url = URL.createObjectURL(blob);
  var a = document.createElement("a");
  document.body.appendChild(a);
  a.style = "display: none";
  a.href = url;
  a.download = name;
  a.click();
  URL.revokeObjectURL(url);
}

function stopStreamsAndPlaybackData() {
  //document.getElementById("btn").disabled = true;
  //document.getElementById("btn2").disabled = true;
  console.log('Stopping record and starting playback');
  recorder.stop();
  localStream.getVideoTracks()[0].stop();

  // sourceBuffer.appendBuffer(recordedChunks);
  // Or...
  var superBuffer = new Blob(recordedChunks);
  document.getElementById("video").src = window.URL.createObjectURL(superBuffer);
}

function stopStreamsAndDownloadData() {
  //document.getElementById("btn").disabled = true;
  //document.getElementById("btn2").disabled = true;
  console.log('Stopping record and starting download');
  enableButtons();
  recorder.stop();
  localStream.getVideoTracks()[0].stop();

  saveByteArray(recordedChunks, 'test.webm')();

}

function recorderOnStop() {
  console.log('recorderOnStop fired');
}

function gotMediaStream(stream) {

  console.log("Received local stream");
  var video = document.querySelector("video");
  video.src = URL.createObjectURL(stream);
  localStream = stream;
  stream.onended = function() { console.log("Ended"); };

  startTime = window.performance.now();
  var videoTracks = localStream.getVideoTracks();
  //var audioTracks = localStream.getAudioTracks();

  console.log('Checking audio')

  if(includeMic){
    console.log('Adding audio track')
    var audioTracks = audioStream.getAudioTracks();
    localStream.addTrack(audioTracks[0]);
  }
  else{
    console.log('Not adding audio track')
  }
  if (videoTracks.length > 0) {

  }

  try {
    console.log("Trying");
    recorder = new MediaRecorder(stream, "video/vp8");
  } catch (e) {
    console.assert(false, 'Exception while creating MediaRecorder: ' + e);
    return;
  }
  console.assert(recorder.state == "inactive");
  recorder.ondataavailable = recorderOnDataAvailable;
  recorder.onstop = recorderOnStop;
  recorder.start();
  console.log("Recorder is started");
  console.assert(recorder.state == "recording");
  greyOutButtons();
  //
};

function gotAudio(stream) {
  console.log("Received audio stream");
  audioStream = stream;
  stream.onended = function() { console.log("Audio Ended"); };

};

function getUserMediaError() {
  console.log("getUserMedia() failed");
};

function onAccessApproved(id) {
  window.resizeTo(500, 320);
  if (!id) {
    console.log("Access rejected.");
    return;
  }
  console.log('Window ID: ', id);

  navigator.webkitGetUserMedia({
      audio:false,
      video: { mandatory: { chromeMediaSource: "desktop",
                            chromeMediaSourceId: id,
                            maxWidth:window.screen.width,
                            maxHeight:window.screen.height } }
  }, gotMediaStream, getUserMediaError);

}
/*
var pending_request_id = null;
document.querySelector('#newTab').addEventListener('click', function(e) {
  chrome.tabs.create({url: chrome.extension.getURL('index.html#window')});
    window.resizeTo(500, 280);
});

document.querySelector('#start').addEventListener('click', function(e) {
  navigator.webkitGetUserMedia({
      audio:true,
      video: false
  }, gotAudio, getUserMediaError);

  window.resizeTo(800, 900);
  pending_request_id = chrome.desktopCapture.chooseDesktopMedia(
      ["screen", "window"], onAccessApproved);
  // "screen", "window"
  //  chrome.tabCapture.capture({
  //    audio:false,
  //    video: true
  //}, gotStream);
});

document.querySelector('#cancel').addEventListener('click', function(e) {
  if (pending_request_id != null) {
    chrome.desktopCapture.cancelChooseDesktopMedia(pending_request_id);
  }
});

*/

<commit_msg>Removing MIME parameter<commit_after>
/*
 *  Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree.
 */

var mediaStream; // Contains video, and possibly added audio track
var audioStream; // Mic only
var recordedChunks = [];
var numrecordedChunks = 0;
var recorder;
var includeMic = false;

document.querySelector('#recDesktop').addEventListener('click', recordDesktop);
document.querySelector('#recCamera').addEventListener('click', recordCamera);
document.querySelector('#recWindow').addEventListener('click', recordWindow);
//document.querySelector('#recTab').addEventListener('click', recordTab);
document.querySelector('#Audio').addEventListener('click', audioCheck);
document.querySelector('#recStop').addEventListener('click', stopStreamsAndDownloadData);

function greyOutButtons(){
  document.querySelector('#recDesktop').disabled=true;
  document.querySelector('#recCamera').disabled=true;
  document.querySelector('#recWindow').disabled=true;
  document.querySelector('#recStop').hidden=false;
}

function enableButtons(){
  console.log('Enabling buttons')
  document.querySelector('#recDesktop').disabled=false;
  document.querySelector('#recCamera').disabled=false;
  document.querySelector('#recWindow').disabled=false;
  document.querySelector('#recStop').hidden=true;
}

function audioCheck() {

  // this won't work in extension

  // Mute video so we don't play loopback audio
  var video = document.querySelector("video");
  video.muted = true;
  // Tooggle state
  includeMic = !includeMic;
  console.log('Audio =', includeMic)

  if (includeMic){
    if (document.getElementById("Audio").checked){
        navigator.webkitGetUserMedia({
        audio:true,
        video: false
    }, gotAudio, getUserMediaError);

    }
  }

};

function recordDesktop(stream) {
  // Start Window picker with Desktop constraints
  recordedChunks = [];
  numrecordedChunks = 0;
  window.resizeTo(646, 565);
  pending_request_id = chrome.desktopCapture.chooseDesktopMedia(
      ["screen"], onAccessApproved);

};

function recordCamera(stream) {

  recordedChunks = [];
  numrecordedChunks = 0;

  navigator.webkitGetUserMedia({
      audio:false,
      video: { mandatory: { minWidth:1280,
                            minHeight:720 } }
  }, gotMediaStream, getUserMediaError);
};

function recordWindow(stream) {

  recordedChunks = [];
  numrecordedChunks = 0;
 // Start Window picker with Desktop constraints
  window.resizeTo(646, 565);
  pending_request_id = chrome.desktopCapture.chooseDesktopMedia(
      ["window"], onAccessApproved);

  // Check Audio inclusion, fire off GUM if needed

};

function recordTab(stream) {
  // Invoke Tab Capture API
};

function gotTab(stream) {

};

function createButton(id, text, onClick) {
  const button = document.createElement("input");
  button.id = id;
  button.type = "button";
  button.value = text;
  button.onclick = onClick;
  document.body.appendChild(button);
  console.log("Button " + id + " created");
}

function recorderOnDataAvailable(event) {
  if (event)
    console.assert(event.data.length > 0, 'Recorded data size should be > 0',event.data.length);
  console.assert(recorder.state == "recording", "State should be 'recording'");

  // Use |byteLength| instead of |length| for event.data;
  recordedChunks.push(event.data);
  numrecordedChunks += event.data.byteLength;
}

function saveByteArray(data, name) {
  var blob = new Blob(data, {type: "video/webm"});
  var url = URL.createObjectURL(blob);
  var a = document.createElement("a");
  document.body.appendChild(a);
  a.style = "display: none";
  a.href = url;
  a.download = name;
  a.click();
  URL.revokeObjectURL(url);
}

function stopStreamsAndPlaybackData() {
  //document.getElementById("btn").disabled = true;
  //document.getElementById("btn2").disabled = true;
  console.log('Stopping record and starting playback');
  recorder.stop();
  localStream.getVideoTracks()[0].stop();

  // sourceBuffer.appendBuffer(recordedChunks);
  // Or...
  var superBuffer = new Blob(recordedChunks);
  document.getElementById("video").src = window.URL.createObjectURL(superBuffer);
}

function stopStreamsAndDownloadData() {
  //document.getElementById("btn").disabled = true;
  //document.getElementById("btn2").disabled = true;
  console.log('Stopping record and starting download');
  enableButtons();
  recorder.stop();
  localStream.getVideoTracks()[0].stop();

  saveByteArray(recordedChunks, 'test.webm')();

}

function recorderOnStop() {
  console.log('recorderOnStop fired');
}

function gotMediaStream(stream) {

  console.log("Received local stream");
  var video = document.querySelector("video");
  video.src = URL.createObjectURL(stream);
  localStream = stream;
  stream.onended = function() { console.log("Ended"); };

  startTime = window.performance.now();
  var videoTracks = localStream.getVideoTracks();
  //var audioTracks = localStream.getAudioTracks();

  console.log('Checking audio')

  if(includeMic){
    console.log('Adding audio track')
    var audioTracks = audioStream.getAudioTracks();
    localStream.addTrack(audioTracks[0]);
  }
  else{
    console.log('Not adding audio track')
  }
  if (videoTracks.length > 0) {

  }

  try {
    console.log("Trying");
    recorder = new MediaRecorder(stream);
  } catch (e) {
    console.assert(false, 'Exception while creating MediaRecorder: ' + e);
    return;
  }
  console.assert(recorder.state == "inactive");
  recorder.ondataavailable = recorderOnDataAvailable;
  recorder.onstop = recorderOnStop;
  recorder.start();
  console.log("Recorder is started");
  console.assert(recorder.state == "recording");
  greyOutButtons();
  //
};

function gotAudio(stream) {
  console.log("Received audio stream");
  audioStream = stream;
  stream.onended = function() { console.log("Audio Ended"); };

};

function getUserMediaError() {
  console.log("getUserMedia() failed");
};

function onAccessApproved(id) {
  window.resizeTo(500, 320);
  if (!id) {
    console.log("Access rejected.");
    return;
  }
  console.log('Window ID: ', id);

  navigator.webkitGetUserMedia({
      audio:false,
      video: { mandatory: { chromeMediaSource: "desktop",
                            chromeMediaSourceId: id,
                            maxWidth:window.screen.width,
                            maxHeight:window.screen.height } }
  }, gotMediaStream, getUserMediaError);

}
/*
var pending_request_id = null;
document.querySelector('#newTab').addEventListener('click', function(e) {
  chrome.tabs.create({url: chrome.extension.getURL('index.html#window')});
    window.resizeTo(500, 280);
});

document.querySelector('#start').addEventListener('click', function(e) {
  navigator.webkitGetUserMedia({
      audio:true,
      video: false
  }, gotAudio, getUserMediaError);

  window.resizeTo(800, 900);
  pending_request_id = chrome.desktopCapture.chooseDesktopMedia(
      ["screen", "window"], onAccessApproved);
  // "screen", "window"
  //  chrome.tabCapture.capture({
  //    audio:false,
  //    video: true
  //}, gotStream);
});

document.querySelector('#cancel').addEventListener('click', function(e) {
  if (pending_request_id != null) {
    chrome.desktopCapture.cancelChooseDesktopMedia(pending_request_id);
  }
});

*/

<|endoftext|>


<commit_before>process.env.NODE_ENV = 'development';
//================引入主模块=================
var koa = require('koa');
//引入日志模块
var logger = require('koa-logger');
//引入路由模块
//引入静态文件处理
var serve = require('koa-static');
//引入模板引擎
var jade = require('koa-jade');
//引入body parse
var bodyParser = require('koa-body-parser');
//引入session
var session = require('koa-session');
//引入querystring Parse
var queryString = require('qs');

var app = koa();

//===============引入自定义模块===============
//引入路由管理
var router = require('./router/route');

//================引入配置文件================
var config = require('./config/serverConfig');

//include config
//generate application
app.use(logger());
//parse static file
app.use(serve(__dirname + '/public'));
app.use(router.routes());
//parse Url query string
// app.use(function*(next){
  // this.qs = queryString.parse(this.querystring);
  // yield next;
// });
//parse request
// app.use(bodyParser());
//set session secret
// app.keys = config.secret;
//use session
// app.use(session(app));

//引入路由规则

app.listen(config.port || 3000);

//开发环境
var webpackServer = require('./config/webpackServer');
if(process.argv[2] == 'dev'){
  webpackServer(app);
};
<commit_msg>修改默认环境<commit_after>process.env.NODE_ENV = 'development';
//================引入主模块=================
var koa = require('koa');
//引入日志模块
var logger = require('koa-logger');
//引入路由模块
//引入静态文件处理
var serve = require('koa-static');
//引入模板引擎
var jade = require('koa-jade');
//引入body parse
var bodyParser = require('koa-body-parser');
//引入session
var session = require('koa-session');
//引入querystring Parse
var queryString = require('qs');

var app = koa();

//===============引入自定义模块===============
//引入路由管理
var router = require('./router/route');

//================引入配置文件================
var config = require('./config/serverConfig');

//include config
//generate application
app.use(logger());
//parse static file
app.use(serve(__dirname + '/public'));
app.use(router.routes());
//parse Url query string
// app.use(function*(next){
  // this.qs = queryString.parse(this.querystring);
  // yield next;
// });
//parse request
// app.use(bodyParser());
//set session secret
// app.keys = config.secret;
//use session
// app.use(session(app));

//引入路由规则

app.listen(config.port || 3000);

//开发环境
var webpackServer = require('./config/webpackServer');
if(process.env.NODE_ENV == 'development'){
  webpackServer(app);
};
<|endoftext|>