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

'use strict'

// return value
let toJSON = {}

// Deps and imports
const Fs = require('fs')
const Path = require('path')

// global counters
let DIRS = 0
let FILES = 0

// Generic helpers
const log = x => (console.log(x), x)
const nlog = (...x) => (x.forEach(log), x[0])
const rlog = err => log(err.message)
const genericCallback = (err, res) => log(err ? err.message : res)

// file helpers
const getRelPath = path => path.replace(toTest, '')

// Constants
const testPath = process.argv[2] || '.'
const toTest = `${Path.resolve(testPath)}${Path.sep}`
const STANDALONE = !module.parent // Falsy if imported
const EXT = '.svg'
const OUT = `${toTest}${Path.sep}${EXT.substring(1)}.json`

// Object helper
const assocPath = (target, path, file) => {
  FILES ++
  let objPath = Path.dirname(getRelPath(path)).split(Path.sep)
  let ref = target
  objPath.forEach(key => {
    if (!ref[key]) {
      DIRS ++
      ref[key] = {}
    }
    ref = ref[key]
  })
  ref[Path.basename(file, EXT)] = Fs.readFileSync(path, 'UTF-8')
}

nlog(
  `Running in ${Path.resolve('.')}`,
  `Mapping ${Path.resolve(testPath)} for ${EXT} files`
)

// const doDir = dirPath => {
//   Fs.readdir(dirPath,
//     (err, res) => {
//       if (err) {
//         log(err);
//         return err
//       } else if (res.length) {
//         res.forEach(fileName => checkFile(Path.resolve(Path.join(dirPath, fileName))));
//       }
//     })
// }

const doDir = dirPath => {
  const res = Fs.readdirSync(dirPath)
  if (res.length) {
    res.forEach(fileName => checkFile(Path.resolve(Path.join(dirPath, fileName))))
  }
}

const onMatch = filePath => {
  assocPath(toJSON, filePath, Path.basename(filePath))
}

const checkFile = filePath => {
  const res = Fs.statSync(filePath)
  if (res.isFile() && Path.extname(filePath) === EXT) {
    onMatch(filePath)
  } else if (res.isDirectory()) {
    doDir(filePath)
  }
}
//
// const checkFile = filePath => {
//   Fs.stat(filePath,
//     (err, res) => {
//       if (err){
//         log(err.message)
//         return err
//       } else if (res.isFile() && Path.extname(filePath) === EXT) {
//         onMatch(filePath)
//       } else if (res.isDirectory()) {
//         doDir(filePath)
//       }
//     })
// }

const main = () => {
  doDir(toTest)
  // setTimeout(() => {
    log(`Found ${FILES} ${EXT} files in ${DIRS} directories`)
    log(`Writing output to ${OUT}`)
    Fs.writeFileSync(OUT, JSON.stringify(toJSON))
  // }
  // ,200)
}

main()

exports = main
<commit_msg>Path error corrected<commit_after>#!/usr/local/bin/node

'use strict'

// return value
let toJSON = {}

// Deps and imports
const Fs = require('fs')
const Path = require('path')

// global counters
let DIRS = 0
let FILES = 0

// Generic helpers
const log = x => (console.log(x), x)
const nlog = (...x) => (x.forEach(log), x[0])
const rlog = err => log(err.message)
const genericCallback = (err, res) => log(err ? err.message : res)

// file helpers
const getRelPath = path => path.replace(toTest, '')

// Constants
const testPath = process.argv[2] || '.'
const toTest = `${Path.resolve(testPath)}${Path.sep}`
const STANDALONE = !module.parent // Falsy if imported
const EXT = '.svg'
const OUT = `${toTest}${EXT.substring(1)}.json`

// Object helper
const assocPath = (target, path, file) => {
  FILES ++
  let objPath = Path.dirname(getRelPath(path)).split(Path.sep)
  let ref = target
  objPath.forEach(key => {
    if (!ref[key]) {
      DIRS ++
      ref[key] = {}
    }
    ref = ref[key]
  })
  ref[Path.basename(file, EXT)] = Fs.readFileSync(path, 'UTF-8')
}

nlog(
  `Running in ${Path.resolve('.')}`,
  `Mapping ${Path.resolve(testPath)} for ${EXT} files`
)

// const doDir = dirPath => {
//   Fs.readdir(dirPath,
//     (err, res) => {
//       if (err) {
//         log(err);
//         return err
//       } else if (res.length) {
//         res.forEach(fileName => checkFile(Path.resolve(Path.join(dirPath, fileName))));
//       }
//     })
// }

const doDir = dirPath => {
  const res = Fs.readdirSync(dirPath)
  if (res.length) {
    res.forEach(fileName => checkFile(Path.resolve(Path.join(dirPath, fileName))))
  }
}

const onMatch = filePath => {
  assocPath(toJSON, filePath, Path.basename(filePath))
}

const checkFile = filePath => {
  const res = Fs.statSync(filePath)
  if (res.isFile() && Path.extname(filePath) === EXT) {
    onMatch(filePath)
  } else if (res.isDirectory()) {
    doDir(filePath)
  }
}
//
// const checkFile = filePath => {
//   Fs.stat(filePath,
//     (err, res) => {
//       if (err){
//         log(err.message)
//         return err
//       } else if (res.isFile() && Path.extname(filePath) === EXT) {
//         onMatch(filePath)
//       } else if (res.isDirectory()) {
//         doDir(filePath)
//       }
//     })
// }

const main = () => {
  doDir(toTest)
  // setTimeout(() => {
    log(`Found ${FILES} ${EXT} files in ${DIRS} directories`)
    log(`Writing output to ${OUT}`)
    Fs.writeFileSync(OUT, JSON.stringify(toJSON))
  // }
  // ,200)
}

main()

exports = main
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict'

// Always colors for better debug
process.argv.push('--color=always')

// External dependencies
const { join, resolve } = require('path')
const __rootdirname = __dirname
const requireDir = require('require-dir')
const colors = require('chalk')
const shell = require('shelljs')
const extend = require('util')._extend
const asciify = require('asciify')
const http = require('http')
const url = require('url')
const fs = require('fs')
const net = require('net')
const yargs = require('yargs')
const glob = require('glob')
const querystring = require('querystring')
const HockeyApp = require('hockeyapp-api-wrapper')
const yaml = require('js-yaml')
const cucumberHtmlReporter = require('cucumber-html-reporter')
const gherkinLint = { run: function () { require('gherkin-lint') } }

// Show CLI info
if (yargs.argv._.length) {
  const packageJson = require(join(__dirname, '/package.json'))
  console.log(colors.blue(`[Patata]`), colors.yellow(`Version ${packageJson.version}. More info: ${packageJson.homepage}`))
}

// Switch CWD if specified from options
const cwd = resolve(yargs.argv.cwd || process.cwd())
process.chdir(cwd)

// External dependencies to pass to the commands
let dep = { yargs, join, resolve, console, colors, shell, process, __rootdirname, extend, url, asciify, http, net, fs, glob, querystring, HockeyApp, yaml, cucumberHtmlReporter, gherkinLint }

// Internal dependencies
const inDepFns = requireDir(join(__rootdirname, 'lib', 'modules'), { camelcase: true })
Object.keys(inDepFns).forEach(name => { dep[name] = inDepFns[name](dep) })

// Load commands from folder and pass dependencies
const commandsFn = requireDir(join(__rootdirname, 'lib', 'commands'))
const commands = Object.keys(commandsFn).map((i) => commandsFn[i](dep))

// Change width of terminal messages
let terminalWidth = require('yargs').terminalWidth()
terminalWidth = terminalWidth > 100 ? 100 : terminalWidth

// Init CLI commands and options
commands.forEach(cmd => yargs.command(cmd.command, cmd.desc, cmd.builder, cmd.handler))
yargs
  .wrap(terminalWidth)
  .options({ cwd: { desc: 'Change the current working directory', type: 'string' } })
  .options({ verbose: { desc: 'Show all debug messages', type: 'boolean' } })
  .demand(1)
  .version()
  .alias('version', 'v')
  .help()
  .alias('help', 'h')
  .argv
<commit_msg>Try catch all errors on commands.<commit_after>#!/usr/bin/env node
'use strict'

// Always colors for better debug
process.argv.push('--color=always')

// External dependencies
const { join, resolve } = require('path')
const __rootdirname = __dirname
const requireDir = require('require-dir')
const colors = require('chalk')
const shell = require('shelljs')
const extend = require('util')._extend
const asciify = require('asciify')
const http = require('http')
const url = require('url')
const fs = require('fs')
const net = require('net')
const yargs = require('yargs')
const glob = require('glob')
const querystring = require('querystring')
const HockeyApp = require('hockeyapp-api-wrapper')
const yaml = require('js-yaml')
const cucumberHtmlReporter = require('cucumber-html-reporter')
const gherkinLint = { run: function () { require('gherkin-lint') } }

// Show CLI info
if (yargs.argv._.length) {
  const packageJson = require(join(__dirname, '/package.json'))
  console.log(colors.blue(`[Patata]`), colors.yellow(`Version ${packageJson.version}. More info: ${packageJson.homepage}`))
}

// Switch CWD if specified from options
const cwd = resolve(yargs.argv.cwd || process.cwd())
process.chdir(cwd)

// External dependencies to pass to the commands
let dep = { yargs, join, resolve, console, colors, shell, process, __rootdirname, extend, url, asciify, http, net, fs, glob, querystring, HockeyApp, yaml, cucumberHtmlReporter, gherkinLint }

// Internal dependencies
const inDepFns = requireDir(join(__rootdirname, 'lib', 'modules'), { camelcase: true })
Object.keys(inDepFns).forEach(name => { dep[name] = inDepFns[name](dep) })

// Load commands from folder and pass dependencies
const commandsFn = requireDir(join(__rootdirname, 'lib', 'commands'))
const commands = Object.keys(commandsFn).map((i) => commandsFn[i](dep))

// Change width of terminal messages
let terminalWidth = require('yargs').terminalWidth()
terminalWidth = terminalWidth > 100 ? 100 : terminalWidth

// Init CLI commands and options
commands.forEach(cmd => yargs.command(cmd.command, cmd.desc, cmd.builder, (argv) => {
  try {
    cmd.handler(argv)
  } catch (ex) {
    dep.log.exit(ex)
  }
}))
yargs
  .wrap(terminalWidth)
  .options({ cwd: { desc: 'Change the current working directory', type: 'string' } })
  .options({ verbose: { desc: 'Show all debug messages', type: 'boolean' } })
  .demand(1)
  .version()
  .alias('version', 'v')
  .help()
  .alias('help', 'h')
  .argv
<|endoftext|>


<commit_before>var Botkit = require('botkit');
var BeepBoopBotkit = require('beepboop-botkit');
var StringArgv = require('string-argv');

var PORT = process.env.PORT
if (!PORT) {
    console.error('PORT is required');
    process.exit(1);
}

var VERIFY_TOKEN = process.env.SLACK_VERIFY_TOKEN
if (!VERIFY_TOKEN) {
  console.error('SLACK_VERIFY_TOKEN is required')
  process.exit(1)
}

var controller = Botkit.slackbot({
  // reconnect to Slack RTM when connection goes bad
  retry: Infinity,
  send_via_rtm: true,
  debug: false
});

console.log('Starting in Beep Boop multi-team mode')
var BeepBoop = BeepBoopBotkit.start(controller, { debug: true, scopes: ['channels:history'] })
var MarkovChain = require('markovchain');
var JSMegaHal = require('jsmegahal');

var COMMAND_MAPPINGS = {
    "/incaseofjoshrant": handle_incaseofjoshrant,
    "/markov": handle_markov,
    "/megahal": handle_megahal,
    "/echo": handle_echo
};

controller.setupWebserver(PORT, function(err, webserver) {
    if (err) {
        console.error(err)
        process.exit(1)
    }
    // Setup our slash command webhook endpoints
    controller.createWebhookEndpoints(webserver)
});

controller.on('slash_command', function(bot, message) {
    if (message.token !== VERIFY_TOKEN) {
        return bot.res.send(401, 'Unauthorized');
    }
    if (!COMMAND_MAPPINGS[message.command]) {
        bot.replyAcknowledge();
        return;
    }

    var params = StringArgv(message.text);

    COMMAND_MAPPINGS[message.command](bot, message, params);
});

// receive an interactive message, and reply with a message that will replace the original
controller.on('interactive_message_callback', function(bot, message) {
    if (message.token !== VERIFY_TOKEN) {
        return bot.res.send(401, 'Unauthorized');
    }

    return bot.res.send(200, ''); //do nothing
});

// ============ various slash command handlers =============

function handle_incaseofjoshrant(bot, message, params) {
    bot.replyPublicDelayed(message, {
        "response_type": "in_channel",
        "attachments": [{
            "title": '@' + message.user_name + ' activated emergency alert procedure',
            "image_url": "http://i.imgur.com/wtYhyuN.png"
        }]
    }, function() {
        return bot.res.send(200, '');
    });
}

function handle_markov(bot, message, params) {
    //Hack in and get our access token
    var workerKey = Object.keys(BeepBoop.workers)[0];
    var token = BeepBoop.workers[workerKey].resource.SlackAccessToken;

    var count = 500;
    if (params && params.length > 0) {
        count = Number(params[0]);
    }

    //Get our message history
    bot.api.channels.history({
        channel: message.channel_id,
        token: token,
        count: count
    }, function(err, data) {

        var m = new MarkovChain('');
        for (var i = 0; i < data.messages.length; i++) {
            if (data.messages[i].user) {
                m.parse(data.messages[i].text);
            }
        }

        var title = "@" + message.user_name + " requested a markov chain based on the last " + count + " messages";

        var text = m.process();
        bot.replyPublicDelayed(message, {
            "response_type": "in_channel",
            "attachments": [{
                 "title": title,
                "text": text
            }]
        }, function() {
            return bot.res.send(200, '');
        });
    });
}

function handle_megahal(bot, message, params) {
    //Hack in and get our access token
    var workerKey = Object.keys(BeepBoop.workers)[0];
    var token = BeepBoop.workers[workerKey].resource.SlackAccessToken;

    var count = 500;
    var order = 4;
    var question = undefined;
    if (params && params.length > 0) {
        question = params.join(' ');
    }

    //Get our message history
    bot.api.channels.history({
        channel: message.channel_id,
        token: token,
        count: count
    }, function(err, data) {

        var m = new JSMegaHal(order);
        var currentUser = null;
        var currentMessage = null;
        for (var i = 0; i < data.messages.length; i++) {
            var msg = data.messages[i];

            if (!msg.user) {
                continue;
            }

            if (msg.user !== currentUser) {
                if (currentMessage) {
                    m.add(currentMessage);
                }
                currentUser = msg.user;
                currentMessage = msg.text;
            } else {
                //Same user with multiple messages should be combined
                currentMessage += '. ' + msg.text;
            }
        }

        m.add(currentMessage);

        var title = null;
        if (question) {
            title = "@" + message.user_name + " requested a megahal response to: '" + question + "'";
        } else {
            title = "@" + message.user_name + " requested a random megahal response";
        }

        var text = m.getReply(question);
        bot.replyPublicDelayed(message, {
            "response_type": "in_channel",
            "attachments": [{
                 "title": title,
                "text": text
            }]
        }, function() {
            return bot.res.send(200, '');
        });
    });
}

function handle_echo(bot, message, params) {
    var text = 'Whatever...'
    if (params) {
        var obj = null;
        switch (params[0]) {
            case "beepboop":
                obj = BeepBoop;
                break;
            case "beepboopbotkit":
                obj = BeepBoopBotkit;
                break;
            case "controller":
                obj = controller;
                break;
            case "message":
                obj = message;
                break;
            default:
                obj = bot;
                break;
        }
        for (var i = 1; i < params.length; i++) {
            obj = obj[params[i]];
            if (obj === null || obj === undefined) {
                text = "Couldnt find " + params[i] + " in " + obj;
                break;
            }
        }

        if (obj == null || obj == undefined) {
            text = 'null/undefined';
        } else if (obj instanceof String) {
            text = obj + ':(String)';
        } else if (obj instanceof Number) {
            text = obj + ':(Number)';
        } else if (obj instanceof Object) {
            text = obj + ':(Object) has keys ' + Object.keys(obj);
        } else {
            text = obj + ':(' + typeof obj + ') has keys ' + Object.keys(obj);
        }
    }
    bot.replyPublicDelayed(message, {
        "response_type": "in_channel",
        "attachments": [{
            "title": '/echo ' + params.join(' '),
            "text": text
        }]
    }, function() {
        return bot.res.send(200, '');
    });
}

<commit_msg>disorder<commit_after>var Botkit = require('botkit');
var BeepBoopBotkit = require('beepboop-botkit');
var StringArgv = require('string-argv');

var PORT = process.env.PORT
if (!PORT) {
    console.error('PORT is required');
    process.exit(1);
}

var VERIFY_TOKEN = process.env.SLACK_VERIFY_TOKEN
if (!VERIFY_TOKEN) {
  console.error('SLACK_VERIFY_TOKEN is required')
  process.exit(1)
}

var controller = Botkit.slackbot({
  // reconnect to Slack RTM when connection goes bad
  retry: Infinity,
  send_via_rtm: true,
  debug: false
});

console.log('Starting in Beep Boop multi-team mode')
var BeepBoop = BeepBoopBotkit.start(controller, { debug: true, scopes: ['channels:history'] })
var MarkovChain = require('markovchain');
var JSMegaHal = require('jsmegahal');

var COMMAND_MAPPINGS = {
    "/incaseofjoshrant": handle_incaseofjoshrant,
    "/markov": handle_markov,
    "/megahal": handle_megahal,
    "/echo": handle_echo
};

controller.setupWebserver(PORT, function(err, webserver) {
    if (err) {
        console.error(err)
        process.exit(1)
    }
    // Setup our slash command webhook endpoints
    controller.createWebhookEndpoints(webserver)
});

controller.on('slash_command', function(bot, message) {
    if (message.token !== VERIFY_TOKEN) {
        return bot.res.send(401, 'Unauthorized');
    }
    if (!COMMAND_MAPPINGS[message.command]) {
        bot.replyAcknowledge();
        return;
    }

    var params = StringArgv(message.text);

    COMMAND_MAPPINGS[message.command](bot, message, params);
});

// receive an interactive message, and reply with a message that will replace the original
controller.on('interactive_message_callback', function(bot, message) {
    if (message.token !== VERIFY_TOKEN) {
        return bot.res.send(401, 'Unauthorized');
    }

    return bot.res.send(200, ''); //do nothing
});

// ============ various slash command handlers =============

function handle_incaseofjoshrant(bot, message, params) {
    bot.replyPublicDelayed(message, {
        "response_type": "in_channel",
        "attachments": [{
            "title": '@' + message.user_name + ' activated emergency alert procedure',
            "image_url": "http://i.imgur.com/wtYhyuN.png"
        }]
    }, function() {
        return bot.res.send(200, '');
    });
}

function handle_markov(bot, message, params) {
    //Hack in and get our access token
    var workerKey = Object.keys(BeepBoop.workers)[0];
    var token = BeepBoop.workers[workerKey].resource.SlackAccessToken;

    var count = 500;
    if (params && params.length > 0) {
        count = Number(params[0]);
    }

    //Get our message history
    bot.api.channels.history({
        channel: message.channel_id,
        token: token,
        count: count
    }, function(err, data) {

        var m = new MarkovChain('');
        for (var i = 0; i < data.messages.length; i++) {
            if (data.messages[i].user) {
                m.parse(data.messages[i].text);
            }
        }

        var title = "@" + message.user_name + " requested a markov chain based on the last " + count + " messages";

        var text = m.process();
        bot.replyPublicDelayed(message, {
            "response_type": "in_channel",
            "attachments": [{
                 "title": title,
                "text": text
            }]
        }, function() {
            return bot.res.send(200, '');
        });
    });
}

function handle_megahal(bot, message, params) {
    //Hack in and get our access token
    var workerKey = Object.keys(BeepBoop.workers)[0];
    var token = BeepBoop.workers[workerKey].resource.SlackAccessToken;

    var count = 500;
    var order = 3;
    var question = undefined;
    if (params && params.length > 0) {
        question = params.join(' ');
    }

    //Get our message history
    bot.api.channels.history({
        channel: message.channel_id,
        token: token,
        count: count
    }, function(err, data) {

        var m = new JSMegaHal(order);
        var currentUser = null;
        var currentMessage = null;
        for (var i = 0; i < data.messages.length; i++) {
            var msg = data.messages[i];

            if (!msg.user) {
                continue;
            }

            if (msg.user !== currentUser) {
                if (currentMessage) {
                    m.add(currentMessage);
                }
                currentUser = msg.user;
                currentMessage = msg.text;
            } else {
                //Same user with multiple messages should be combined
                currentMessage += '. ' + msg.text;
            }
        }

        m.add(currentMessage);

        var title = null;
        if (question) {
            title = "@" + message.user_name + " requested a megahal response to: '" + question + "'";
        } else {
            title = "@" + message.user_name + " requested a random megahal response";
        }

        var text = m.getReply(question);
        bot.replyPublicDelayed(message, {
            "response_type": "in_channel",
            "attachments": [{
                 "title": title,
                "text": text
            }]
        }, function() {
            return bot.res.send(200, '');
        });
    });
}

function handle_echo(bot, message, params) {
    var text = 'Whatever...'
    if (params) {
        var obj = null;
        switch (params[0]) {
            case "beepboop":
                obj = BeepBoop;
                break;
            case "beepboopbotkit":
                obj = BeepBoopBotkit;
                break;
            case "controller":
                obj = controller;
                break;
            case "message":
                obj = message;
                break;
            default:
                obj = bot;
                break;
        }
        for (var i = 1; i < params.length; i++) {
            obj = obj[params[i]];
            if (obj === null || obj === undefined) {
                text = "Couldnt find " + params[i] + " in " + obj;
                break;
            }
        }

        if (obj == null || obj == undefined) {
            text = 'null/undefined';
        } else if (obj instanceof String) {
            text = obj + ':(String)';
        } else if (obj instanceof Number) {
            text = obj + ':(Number)';
        } else if (obj instanceof Object) {
            text = obj + ':(Object) has keys ' + Object.keys(obj);
        } else {
            text = obj + ':(' + typeof obj + ') has keys ' + Object.keys(obj);
        }
    }
    bot.replyPublicDelayed(message, {
        "response_type": "in_channel",
        "attachments": [{
            "title": '/echo ' + params.join(' '),
            "text": text
        }]
    }, function() {
        return bot.res.send(200, '');
    });
}

<|endoftext|>


<commit_before>var exec = require('child_process').exec,
    spawn = require('child_process').spawn,
    chalk = require('chalk'),
    path = require('path'),
    EventEmitter = require('events').EventEmitter,
    Immutable = require('immutable'),
    util = require('util'),
    ATTRIBUTES = [
        'username',
        'host',
        'sshKey'
    ],
    DEBUG = true;

function debug() {
    if (DEBUG) {
        console.log.apply(console, [chalk.underline.green('DEBUG:') + ' '].concat(Array.prototype.slice.call(arguments)));
    }
};

/*
 * @constructor
 */
function RemoteExec() {
    this.queue = [];
    // Context of task execution. Immutable
    this.ctx = Immutable.Map({});
};

util.inherits(RemoteExec, EventEmitter);

// define setter
RemoteExec.prototype.set = function(k, v) {
    this.ctx = this.ctx.set(k, v);
};

RemoteExec.prototype.exec = function(cmd, callback) {
    this.queue.push(new Task({
        cmd: cmd,
        ctx: this.ctx,
        callback: callback
    }));
    this.start();
};

RemoteExec.prototype.start = function() {
    if (!this.isRunning) {
        this.emit('start');
        debug('start');
        this.isRunning = true;
        this.callNext();
    }
};

RemoteExec.prototype.stop = function() {
    debug('stop');
    this.isRunning = false;
    this.emit('finish');
};

RemoteExec.prototype.callNext = function() {
    var _this = this;

    setTimeout(function() {
        var task = _this.queue.shift();
        if (!task) {
            return _this.stop();
        }
        task.run(function(err) {
            if (err) {
                throw err;
            }
            _this.callNext();
        });
    }, 5);
};

function Task(options) {
    this.type = options.type;
    this.cmd = options.cmd;
    this.ctx = options.ctx
}

Task.prototype.run = function(done) {
    var cmd = 'ssh',
        userAndHost, key;
    if (this.ctx.get('username')) {
        userAndHost = this.ctx.get('username') + '@' + this.ctx.get('host');
    } else {
        userAndHost = this.ctx.get('host');
    }

    args = [
        userAndHost,
        '-o',
        'UserKnownHostsFile=/dev/null',
        '-o',
        'StrictHostKeyChecking=no',
        '-q',
    ];

    if (key = this.ctx.get('sshKey')) {
        args.push('-i');
        args.push(key);
    }

    args.push(this.cmd);
    console.log(cmd, args);
    console.log(chalk.underline.cyan('executing:'), this.cmd);
    var child = spawn(cmd, args);
    child.stdout.pipe(process.stdout);
    child.stderr.pipe(process.stderr);
    child.on('close', function(code) {
        done();
    });
};

module.exports = RemoteExec;
<commit_msg>check if attribute is valid<commit_after>var exec = require('child_process').exec,
    spawn = require('child_process').spawn,
    chalk = require('chalk'),
    path = require('path'),
    EventEmitter = require('events').EventEmitter,
    Immutable = require('immutable'),
    util = require('util'),
    ATTRIBUTES = [
        'username',
        'host',
        'sshKey'
    ],
    ATTRIBUTES_HASH = {},
    DEBUG = true;

ATTRIBUTES.forEach(function(attr) {
    ATTRIBUTES_HASH[attr] = true;
});

function debug() {
    if (DEBUG) {
        console.log.apply(console, [chalk.underline.green('DEBUG:') + ' '].concat(Array.prototype.slice.call(arguments)));
    }
};

/*
 * @constructor
 */
function RemoteExec() {
    this.queue = [];
    // Context of task execution. Immutable
    this.ctx = Immutable.Map({});
};

util.inherits(RemoteExec, EventEmitter);

// define setter
RemoteExec.prototype.set = function(k, v) {
    if (!ATTRIBUTES_HASH[k]) {
        throw new Error('unknown attribute: ' + k);
    }
    this.ctx = this.ctx.set(k, v);
};

RemoteExec.prototype.exec = function(cmd, callback) {
    this.queue.push(new Task({
        cmd: cmd,
        ctx: this.ctx,
        callback: callback
    }));
    this.start();
};

RemoteExec.prototype.start = function() {
    if (!this.isRunning) {
        this.emit('start');
        debug('start');
        this.isRunning = true;
        this.callNext();
    }
};

RemoteExec.prototype.stop = function() {
    debug('stop');
    this.isRunning = false;
    this.emit('finish');
};

RemoteExec.prototype.callNext = function() {
    var _this = this;

    setTimeout(function() {
        var task = _this.queue.shift();
        if (!task) {
            return _this.stop();
        }
        task.run(function(err) {
            if (err) {
                throw err;
            }
            _this.callNext();
        });
    }, 5);
};

function Task(options) {
    this.type = options.type;
    this.cmd = options.cmd;
    this.ctx = options.ctx
}

Task.prototype.run = function(done) {
    var cmd = 'ssh',
        userAndHost, key;
    if (this.ctx.get('username')) {
        userAndHost = this.ctx.get('username') + '@' + this.ctx.get('host');
    } else {
        userAndHost = this.ctx.get('host');
    }

    args = [
        userAndHost,
        '-o',
        'UserKnownHostsFile=/dev/null',
        '-o',
        'StrictHostKeyChecking=no',
        '-q',
    ];

    if (key = this.ctx.get('sshKey')) {
        args.push('-i');
        args.push(key);
    }

    args.push(this.cmd);
    console.log(cmd, args);
    console.log(chalk.underline.cyan('executing:'), this.cmd);
    var child = spawn(cmd, args);
    child.stdout.pipe(process.stdout);
    child.stderr.pipe(process.stderr);
    child.on('close', function(code) {
        done();
    });
};

module.exports = RemoteExec;
<|endoftext|>


<commit_before>var program = require('commander');
var toposort = require("toposort");
var fs = require("fs");

function collect(value, values) {
    return values.concat([value]);
}

program
    .usage('<source>')
    .option('-o, --output <file>', 'Set the output file [references.js]', 'references.js')
    .option('-e, --extra <file>', 'Add an extra dependency', collect, [])
    .parse(process.argv);

var source = program.args[0];
var destination = program.output;

if (!source)
    program.help();

var getPattern = function () {
    return /\/\/\/\s*<reference path="([^\"]*)" \/>/g;
};

var start = source;
var root = nicePathTo(start);
var savePath = destination;
var niceSavePath = savePath;

if (fs.existsSync(destination)) {
    console.log("Output file exists, removing it");
    fs.unlinkSync(destination);
}

console.log("Reading: " + root);
console.log("Writing: " + niceSavePath);

var start = +new Date();
var files = readDirectory(root).filter(isIncluded);
console.log("  Read " + files.length + " file(s) in " + (+new Date() - start) + 'ms');

start = +new Date();
var dependencies = files.map(getEdges);
var edges = flatten(dependencies);
console.log("  Found " + dependencies.length + " edges in " + (+new Date() - start) + 'ms');

start = +new Date();
var sorted = toposort.array(files.map(function(f) { return f.filename; }), edges).reverse();
console.log("Sorted in " + (+new Date() - start) + 'ms');

function createRelativeReference(path) {
    var relativeToRootPath = path.replace(root + "/", "");
    return '/// <reference path="~/' + relativeToRootPath + '" />';
}

function createAssemblyReference(path) {
    var relativeToRootPath = path.replace(root + "/", "");
    var assemblyName = relativeToRootPath.replace(/\//g, '.');
    return '/// <reference name="' + assemblyName + '" assembly="' + 'Zap.Web.Core' + '" />';
}

var referencesJs = sorted.reduce(function (soFar, path) {
    var relativeToRootPath = path.replace(root + "/", "");
    var relativeReference = createRelativeReference(path);
    var assemblyReference = createAssemblyReference(path);

    return soFar + relativeReference + "\n" + assemblyReference + "\n" + "\n";
}, '');

referencesJs += program.extra.reduce(function(soFar, extra) {
    return soFar + '/// <reference path="' + extra + '" />' + "\n";
}, '');

//console.log(referencesJs);
fs.writeFileSync(savePath, referencesJs);

function readDirectory(path) {
    var dirContents = fs.readdirSync(path);

    var files = [];
    dirContents.forEach(function (filename) {
        var fullPath = nicePathTo(path + "/" + filename);

        if (filename == "." || filename == ".." || filename == "node_modules" || fullPath == niceSavePath)
            return;

        var stats = fs.statSync(fullPath);
        if (stats.isDirectory()) {
            files = files.concat(readDirectory(fullPath));
        } else
            files.push(toFile(fullPath));
    });

    return files;

    function toFile(f) {
        return {
            directory: path,
            filename: f
        };
    }
}

function nicePathTo(file) {
    return fs.realpathSync(file)
        .replace(/\\/g, "/");
}

function isIncluded(file) {
    return file.filename.indexOf('.js') != -1;
}

function getEdges(file) {
    var contents = fs.readFileSync(file.filename).toString();
    var matches = contents.match(getPattern());

    if (!matches)
        return [];

    var dependencies = matches.map(function (line) {
        var match = getPattern().exec(line)
        var fullPath = match[1].indexOf("~") == -1
            ? file.directory + "/" + match[1]
            : match[1].replace("~", root);

        if (!fs.existsSync(fullPath)) {
            console.warn("Warning: Dependency: " + fullPath + " does not exist!\n   (from " + file.filename + ")");
            return null;
        }

        return nicePathTo(fullPath);
    }).filter(function(f) { return f != null });

    return dependencies.map(function (d) {
        return [file.filename, d];
    })
}

function flatten(v) {
    return Array.prototype.concat.apply([], v);
}<commit_msg>Made assembly references optional and dynamic<commit_after>var program = require('commander');
var toposort = require("toposort");
var fs = require("fs");

function collect(value, values) {
    return values.concat([value]);
}

program
    .usage('<source>')
    .option('-o, --output <file>', 'Set the output file [references.js]', 'references.js')
    .option('-e, --extra <file>', 'Add an extra dependency', collect, [])
    .option('-a, --assembly <file>', 'Add an assembly reference', collect, [])
    .parse(process.argv);

var source = program.args[0];
var destination = program.output;

if (!source)
    program.help();

var getPattern = function () {
    return /\/\/\/\s*<reference path="([^\"]*)" \/>/g;
};
var start = source;
var root = nicePathTo(start);
var savePath = destination;
var niceSavePath = savePath;

if (fs.existsSync(destination)) {
    console.log("Output file exists, removing it");
    fs.unlinkSync(destination);
}

console.log("Reading: " + root);
console.log("Writing: " + niceSavePath);

var start = +new Date();
var files = readDirectory(root).filter(isIncluded);
console.log("  Read " + files.length + " file(s) in " + (+new Date() - start) + 'ms');

start = +new Date();
var dependencies = files.map(getEdges);
var edges = flatten(dependencies);
console.log("  Found " + dependencies.length + " edges in " + (+new Date() - start) + 'ms');

start = +new Date();
var sorted = toposort.array(files.map(function(f) { return f.filename; }), edges).reverse();
console.log("Sorted in " + (+new Date() - start) + 'ms');

function createRelativeReference(path) {
    var relativeToRootPath = path.replace(root + "/", "");
    return '/// <reference path="~/' + relativeToRootPath + '" />';
}

function createAssemblyReferences(path) {
    var relativeToRootPath = path.replace(root + "/", "");
    var scriptId = relativeToRootPath.replace(/\//g, '.');

    return program.assembly.map(function(assemblyName) {
        return '/// <reference name="' + scriptId + '" assembly="' + assemblyName + '" />';
    });
}

var referencesJs = sorted.reduce(function (soFar, path) {
    var relativeReference = createRelativeReference(path);
    var assemblyReference = createAssemblyReferences(path).join("\n");

    return soFar + relativeReference + "\n" + assemblyReference + "\n" + "\n";
}, '');

referencesJs += program.extra.reduce(function(soFar, extra) {
    return soFar + '/// <reference path="' + extra + '" />' + "\n";
}, '');

//console.log(referencesJs);
fs.writeFileSync(savePath, referencesJs);

function readDirectory(path) {
    var dirContents = fs.readdirSync(path);

    var files = [];
    dirContents.forEach(function (filename) {
        var fullPath = nicePathTo(path + "/" + filename);

        if (filename == "." || filename == ".." || filename == "node_modules" || fullPath == niceSavePath)
            return;

        var stats = fs.statSync(fullPath);
        if (stats.isDirectory()) {
            files = files.concat(readDirectory(fullPath));
        } else
            files.push(toFile(fullPath));
    });

    return files;

    function toFile(f) {
        return {
            directory: path,
            filename: f
        };
    }
}

function nicePathTo(file) {
    return fs.realpathSync(file)
        .replace(/\\/g, "/");
}

function isIncluded(file) {
    return file.filename.indexOf('.js') != -1;
}

function getEdges(file) {
    var contents = fs.readFileSync(file.filename).toString();
    var matches = contents.match(getPattern());

    if (!matches)
        return [];

    var dependencies = matches.map(function (line) {
        var match = getPattern().exec(line)
        var fullPath = match[1].indexOf("~") == -1
            ? file.directory + "/" + match[1]
            : match[1].replace("~", root);

        if (!fs.existsSync(fullPath)) {
            console.warn("Warning: Dependency: " + fullPath + " does not exist!\n   (from " + file.filename + ")");
            return null;
        }

        return nicePathTo(fullPath);
    }).filter(function(f) { return f != null });

    return dependencies.map(function (d) {
        return [file.filename, d];
    })
}

function flatten(v) {
    return Array.prototype.concat.apply([], v);
}<|endoftext|>


<commit_before>var $ = require('jquery');

exports.defineBasicMatcher =
    function defineBasicMatcher(passFn, messageFn) {
        return function () {
            return {
                compare: function (actual, expected) {
                    var argsArray = Array.prototype.slice.call(arguments);
                    var pass = passFn.apply(this, argsArray);
                    argsArray.push(pass);

                    return {
                        pass: pass,
                        message: messageFn && messageFn.apply(this, argsArray)
                    };
                }
            };
        };
    };

exports.expectedObjectWithNot = function expectedObjectWithNot(actual, pass, obj) {
    try {
        actual = JSON.stringify(obj || actual);
    } catch (e) {
        actual = 'actual';
    }
    return 'Expected ' + actual + (!pass ? '' : ' not' );
};

exports.angularDeps = function () {
    var self = this;

    try {
        var depNames = Array.prototype.slice.call(arguments, 0);
        depNames.push(function actualInjectedFunction() {
            var depsArray = Array.prototype.slice.call(arguments, 0);
            depsArray.forEach(function (dep, i) {
                self[depNames[i]] = dep;
            });
        });
        inject.call(this, depNames);
    } catch (e) {
        console.log(e);
    }
};

exports.lazyLoad = function (obj, name, createFn) {
    var prop;
    Object.defineProperty(obj, name, {
        get: function () {
            if (!prop) {
                prop = createFn();
            }
            return prop;
        }
    })
};

exports.findDTS = function (dts) {
    return $('[dts="' + dts + '"]');
};

exports.findDTSWithinElement = function (element, dts) {
    return element.find('[dts="' + dts + '"]');
};

exports.findDTSIn$Element = function (self, dts) {
    return findDTSWithinElement(self.$element, dts);
};
<commit_msg>don't need to catch this anymore<commit_after>var $ = require('jquery');

exports.defineBasicMatcher =
    function defineBasicMatcher(passFn, messageFn) {
        return function() {
            return {
                compare: function(actual, expected) {
                    var argsArray = Array.prototype.slice.call(arguments);
                    var pass = passFn.apply(this, argsArray);
                    argsArray.push(pass);

                    return {
                        pass: pass,
                        message: messageFn && messageFn.apply(this, argsArray)
                    };
                }
            };
        };
};

exports.expectedObjectWithNot = function expectedObjectWithNot(actual, pass, obj) {
    try {
        actual = JSON.stringify(obj || actual);
    } catch (e) {
        actual = 'actual';
    }
    return 'Expected ' + actual + (!pass ? '' : ' not');
};

exports.angularDeps = function() {
    var self = this;

    var depNames = Array.prototype.slice.call(arguments, 0);
    depNames.push(function actualInjectedFunction() {
        var depsArray = Array.prototype.slice.call(arguments, 0);
        depsArray.forEach(function(dep, i) {
            self[depNames[i]] = dep;
        });
    });
    inject.call(this, depNames);

};

exports.lazyLoad = function(obj, name, createFn) {
    var prop;
    Object.defineProperty(obj, name, {
        get: function() {
            if (!prop) {
                prop = createFn();
            }
            return prop;
        }
    })
};

exports.findDTS = function(dts) {
    return $('[dts="' + dts + '"]');
};

exports.findDTSWithinElement = function(element, dts) {
    return element.find('[dts="' + dts + '"]');
};

exports.findDTSIn$Element = function(self, dts) {
    return findDTSWithinElement(self.$element, dts);
};<|endoftext|>


<commit_before>"use strict";
const path = require('path');
const nodemailer = require("nodemailer");
const EmailTemplate = require('email-templates').EmailTemplate;

let SimpleParseSmtpAdapter = (adapterOptions) => {
    if (!adapterOptions || !adapterOptions.user || !adapterOptions.password || !adapterOptions.host || !adapterOptions.fromAddress ) {
        throw 'SimpleParseSMTPAdapter requires user, password, host, and fromAddress';
    }

    /**
     * Creates trasporter for send emails
     */
    let transporter = nodemailer.createTransport({
        host: adapterOptions.host,
        port: adapterOptions.port,
        secure: adapterOptions.isSSL,
        name: adapterOptions.name || '127.0.0.1',
        auth: {
            user: adapterOptions.user,
            pass: adapterOptions.password
        },
        tls: {
            rejectUnauthorized: adapterOptions.isTlsRejectUnauthorized || true
        }
    });

    /**
     * When emailField is defined in adapterOptines return that field
     * if not return the field email and if is undefined returns username
     *
     * @param Parse Object user
     * @return String email
     */
    let getUserEmail = (user) => {
        let email = user.get('email') || user.get('username');

        if (adapterOptions.emailField) {
            email = user.get(adapterOptions.emailField);
        }

        return email;
    };

    /**
     * Return an email template with data rendered using email-templates module
     * check module docs: https://github.com/niftylettuce/node-email-templates
     *
     * @param String template path template
     * @param Object data object with data for use in template
     */
    let renderTemplate = (template, data) => {
        let templateDir = template;
        let html = new EmailTemplate(templateDir);

        return new Promise((resolve, reject) => {
            html.render(data, (err, result) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });
    };

    /**
     * Parse use this function by default for sends emails
     * @param mail This object contain to address, subject and email text in plain text
     * @returns {Promise}
     */
    let sendMail = (mail) => {
        let mailOptions = {
            to: mail.to,
            html: mail.text,
            subject: mail.subject,
            from: adapterOptions.fromAddress
        };

        return new Promise((resolve, reject) => {
            transporter.sendMail(mailOptions, (error, info) => {
                if(error) {
                    reject(error);
                } else {
                    resolve(info);
                }
            });
        });
    };

    /**
     * When this method is available parse use for send email for reset password
     * @param data This object contain {appName}, {link} and {user} user is an object parse of User class
     * @returns {Promise}
     */
    let sendPasswordResetEmail = (data) => {
        let mail = {
            subject: 'Reset Password',
            to: getUserEmail(data.user)
        };

        if (adapterOptions.templates && adapterOptions.templates.resetPassword) {

            return renderTemplate(adapterOptions.templates.resetPassword.template, data).then((result) => {
                mail.text = result.html;
                mail.subject = adapterOptions.templates.resetPassword.subject;

                return sendMail(mail);
            }, (e) => {

                return new Promise((resolve, reject) => {
                    reject(e);
                });
            });

        } else {
            mail.text = data.link;

            return sendMail(mail);
        }
    };

    return Object.freeze({
        sendMail: sendMail,
        sendPasswordResetEmail: sendPasswordResetEmail
    });
};

module.exports = SimpleParseSmtpAdapter;<commit_msg>sendVerificationEmail<commit_after>"use strict";
const path = require('path');
const nodemailer = require("nodemailer");
const EmailTemplate = require('email-templates').EmailTemplate;

let SimpleParseSmtpAdapter = (adapterOptions) => {
    if (!adapterOptions || !adapterOptions.user || !adapterOptions.password || !adapterOptions.host || !adapterOptions.fromAddress ) {
        throw 'SimpleParseSMTPAdapter requires user, password, host, and fromAddress';
    }

    /**
     * Creates trasporter for send emails
     */
    let transporter = nodemailer.createTransport({
        host: adapterOptions.host,
        port: adapterOptions.port,
        secure: adapterOptions.isSSL,
        name: adapterOptions.name || '127.0.0.1',
        auth: {
            user: adapterOptions.user,
            pass: adapterOptions.password
        },
        tls: {
            rejectUnauthorized: adapterOptions.isTlsRejectUnauthorized || true
        }
    });

    /**
     * When emailField is defined in adapterOptines return that field
     * if not return the field email and if is undefined returns username
     *
     * @param Parse Object user
     * @return String email
     */
    let getUserEmail = (user) => {
        let email = user.get('email') || user.get('username');

        if (adapterOptions.emailField) {
            email = user.get(adapterOptions.emailField);
        }

        return email;
    };

    /**
     * Return an email template with data rendered using email-templates module
     * check module docs: https://github.com/niftylettuce/node-email-templates
     *
     * @param String template path template
     * @param Object data object with data for use in template
     */
    let renderTemplate = (template, data) => {
        let templateDir = template;
        let html = new EmailTemplate(templateDir);

        return new Promise((resolve, reject) => {
            html.render(data, (err, result) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });
    };

    /**
     * Parse use this function by default for sends emails
     * @param mail This object contain to address, subject and email text in plain text
     * @returns {Promise}
     */
    let sendMail = (mail) => {
        let mailOptions = {
            to: mail.to,
            html: mail.text,
            subject: mail.subject,
            from: adapterOptions.fromAddress
        };

        return new Promise((resolve, reject) => {
            transporter.sendMail(mailOptions, (error, info) => {
                if(error) {
                    reject(error);
                } else {
                    resolve(info);
                }
            });
        });
    };

    /**
     * When this method is available parse use for send email for reset password
     * @param data This object contain {appName}, {link} and {user} user is an object parse of User class
     * @returns {Promise}
     */
    let sendPasswordResetEmail = (data) => {
        let mail = {
            subject: 'Reset Password',
            to: getUserEmail(data.user)
        };

        if (adapterOptions.templates && adapterOptions.templates.resetPassword) {

            return renderTemplate(adapterOptions.templates.resetPassword.template, data).then((result) => {
                mail.text = result.html;
                mail.subject = adapterOptions.templates.resetPassword.subject;

                return sendMail(mail);
            }, (e) => {

                return new Promise((resolve, reject) => {
                    reject(e);
                });
            });

        } else {
            mail.text = data.link;

            return sendMail(mail);
        }
    };

    /**
     * When this method is available parse use for send email for email verification
     * @param data This object contain {appName}, {link} and {user} user is an object parse of User class
     * @returns {Promise}
     */
    let sendVerificationEmail = (data) => {
        let mail = {
            subject: 'Verify Email',
            to: getUserEmail(data.user)
        };

        if (adapterOptions.templates && adapterOptions.templates.verifyEmail) {

            return renderTemplate(adapterOptions.templates.verifyEmail.template, data).then((result) => {
                mail.text = result.html;
                mail.subject = adapterOptions.templates.verifyEmail.subject;

                return sendMail(mail);
            }, (e) => {

                return new Promise((resolve, reject) => {
                    reject(e);
                });
            });

        } else {
            mail.text = data.link;

            return sendMail(mail);
        }
    };

    return Object.freeze({
        sendMail: sendMail,
        sendPasswordResetEmail: sendPasswordResetEmail,
        sendVerificationEmail: sendVerificationEmail
    });
};

module.exports = SimpleParseSmtpAdapter;<|endoftext|>


<commit_before>
module.exports = {

	add : function(value){

	},

	fetch : function(start, end){

	}

};<commit_msg>added asset<commit_after>
module.exports = {

	add : function(asset, value){

	},

	fetch : function(asset, start, end){

	}

};<|endoftext|>


<commit_before>let smartcast = require('vizio-smart-cast');
let config = require('config');
let btoa = require('btoa');
let wakeOnLan = require('node-wol');
let eventsource = require('eventsource');
let directv = require('directv-remote');
let didyoumean = require('didyoumean');
var http
if (config.useHttps) {
  console.log('https enabled');
  http = require('https');
} else {
  http = require('http');
}

console.log('configuration:' + JSON.stringify(config));

let headers= {
  headers : {
    Authorization: 'Basic ' + btoa(config.mq.username + ':' + config.mq.token),
    'Content-Type' : 'application/json'
  }
};

let dtv = new directv.Remote(config.directv.ip);

let tv = new smartcast(config.tv.ip);
tv.pairing.useAuthToken(config.tv.token);

let channelMap = config.channels || {}

function handleMessage(message) {
  console.log('Handling message' + JSON.stringify(message));
  switch (message.message) {
    case 'powerOn':
      console.log('turning on');
      wakeOnLan.wake(config.tv.mac,
        tv.control.power.on);
        dtv.processCommand(FA82);
      break;
    case 'powerOff':
      console.log('turning off');
      tv.control.power.off();
      break;
    case 'mute':
      console.log('muteing');
      tv.control.volume.mute();
      break;
    case 'unmute':
      console.log('unmuteing');
      tv.control.volume.unmute();
      break;
    case 'pause':
      console.log('pausing');
      dtv.processKey('pause');
      tv.control.media.pause();
      break;
    case 'play':
      console.log('playing');
      dtv.processKey('play');
      tv.control.media.play();
      break;
    case "FastForward" :
      console.log('FF');
      dtv.processKey('advance');
      tv.control.media.seek.forward();
      break;
    case 'Rewind' :
      console.log('RW');
      dtv.processKey('replay');
      tv.control.media.seek.back();
      break;
    case 'Stop':
      console.log('Stop');
      dtv.processKey('Exit');
      tv.control.navigate.exit();
      break;
    case 'Next':
      console.log('Next');
      for (var i = 0; i < 6; i++) {
        //6 seems to be the right number for commercials
        setTimeout(() => {dtv.processKey('advance');}, i * 750);
      }
      break;
    case 'AdjustVolume':
      console.log('adjusting volume');
      const value = message.parameters.value;
      if (value > 0) {
        tv.control.volume.up();
      } else {
        tv.control.volume.down();
      }
      break;
    case 'SelectInput':
      const input = message.parameters.input;
      tv.input.list().then(resp => {
        var inputList = [];
        resp.ITEMS.forEach(item => {
          inputList.push(item.NAME);
          inputList.push(item.VALUE.NAME);
        });
        var inputClosest = didyoumean(input, inputList);
        if (! inputClosest) {
          console.log('could not find closest: ' + input + ' from: ' + inputList);
          return;
        }
        console.log('setting input: ' + inputClosest);
        tv.input.set(inputClosest);
      });
      break;
      case 'ChangeChannel':
        const channel = JSON.parse(message.parameters.channel);
        if (channel.channelMetadata.name) {
            let channelName = channel.channelMetadata.name;
            console.log("Trying to find channel name " + channelName);
            let guess = didyoumean(channelName, Object.keys(channelMap));
            if (!!guess) {
                console.log("Switching to channel " + channelMap[guess])
                dtv.tune(channelMap[guess])
            }
        } else if (channel.channel.number) {
            console.log("Switching to channel " + channel.channel.number)
            dtv.tune(channel.channel.number)
        }
        break;

    case 'DoubleDown':
        dtv.processKey('pause');
        doubleDown()
        break;
    default:
      console.log('unimplemented message: ' + message.message);
  }

}

async function doubleDown() {
    var getTuner = async function() {
        return await processCommand('FA83').then(value => {
                    var data = (value.return || {}).data
                    return data.length > 32 ? data[32] : 0;
                })
    }
    var currentTuner = await getTuner();

    processKey('down').then(getTuner).then(newTuner => {
        if (currentTuner == newTuner) {
            processKey('down')
        }
    });
}

async function processCommand(command) {
    return new Promise((resolve, reject) => {
        dtv.processCommand(command, function(err, resp) {
            if (!!err) {
                reject(err)
            } else {
                resolve(resp)
            }
        })
    })
}

async function processKey(key) {
    return new Promise((resolve, reject) => {
        dtv.processKey(key, undefined, function(err, resp) {
            if (!!err) {
                reject(err)
            }
            resolve()
        })
    })
}

//TODO queued commands...
var address = (config.useHttps ? 'https://' : 'http://')
              + config.mq.host + ':' + config.mq.port + '/api/stream/queue/' + config.clientId;
console.log('connecting to:' + address);
function startStream() {
  var es = new eventsource(address, headers);
  es.addEventListener('message', message => {
    console.log("recieved message" + JSON.stringify(message));
    if (!!message) {
      var data = JSON.parse(message.data);
      if (!!data) {
        try {
          handleMessage(data);
        } catch (e) {
          console.error(e);
        }
      }
    }
  });

  es.onerror = function(err) {
    setTimeout(_ => {
        if (es.readyState === eventsource.CLOSED) {
            es.close();
            setTimeout(startStream, 5000);
        }
    }, 0);
  }
}
startStream();
<commit_msg>Add wait for tuner check<commit_after>let smartcast = require('vizio-smart-cast');
let config = require('config');
let btoa = require('btoa');
let wakeOnLan = require('node-wol');
let eventsource = require('eventsource');
let directv = require('directv-remote');
let didyoumean = require('didyoumean');
var http
if (config.useHttps) {
  console.log('https enabled');
  http = require('https');
} else {
  http = require('http');
}

console.log('configuration:' + JSON.stringify(config));

let headers= {
  headers : {
    Authorization: 'Basic ' + btoa(config.mq.username + ':' + config.mq.token),
    'Content-Type' : 'application/json'
  }
};

let dtv = new directv.Remote(config.directv.ip);

let tv = new smartcast(config.tv.ip);
tv.pairing.useAuthToken(config.tv.token);

let channelMap = config.channels || {}

function handleMessage(message) {
  console.log('Handling message' + JSON.stringify(message));
  switch (message.message) {
    case 'powerOn':
      console.log('turning on');
      wakeOnLan.wake(config.tv.mac,
        tv.control.power.on);
        dtv.processCommand(FA82);
      break;
    case 'powerOff':
      console.log('turning off');
      tv.control.power.off();
      break;
    case 'mute':
      console.log('muteing');
      tv.control.volume.mute();
      break;
    case 'unmute':
      console.log('unmuteing');
      tv.control.volume.unmute();
      break;
    case 'pause':
      console.log('pausing');
      dtv.processKey('pause');
      tv.control.media.pause();
      break;
    case 'play':
      console.log('playing');
      dtv.processKey('play');
      tv.control.media.play();
      break;
    case "FastForward" :
      console.log('FF');
      dtv.processKey('advance');
      tv.control.media.seek.forward();
      break;
    case 'Rewind' :
      console.log('RW');
      dtv.processKey('replay');
      tv.control.media.seek.back();
      break;
    case 'Stop':
      console.log('Stop');
      dtv.processKey('Exit');
      tv.control.navigate.exit();
      break;
    case 'Next':
      console.log('Next');
      for (var i = 0; i < 6; i++) {
        //6 seems to be the right number for commercials
        setTimeout(() => {dtv.processKey('advance');}, i * 750);
      }
      break;
    case 'AdjustVolume':
      console.log('adjusting volume');
      const value = message.parameters.value;
      if (value > 0) {
        tv.control.volume.up();
      } else {
        tv.control.volume.down();
      }
      break;
    case 'SelectInput':
      const input = message.parameters.input;
      tv.input.list().then(resp => {
        var inputList = [];
        resp.ITEMS.forEach(item => {
          inputList.push(item.NAME);
          inputList.push(item.VALUE.NAME);
        });
        var inputClosest = didyoumean(input, inputList);
        if (! inputClosest) {
          console.log('could not find closest: ' + input + ' from: ' + inputList);
          return;
        }
        console.log('setting input: ' + inputClosest);
        tv.input.set(inputClosest);
      });
      break;
      case 'ChangeChannel':
        const channel = JSON.parse(message.parameters.channel);
        if (channel.channelMetadata.name) {
            let channelName = channel.channelMetadata.name;
            console.log("Trying to find channel name " + channelName);
            let guess = didyoumean(channelName, Object.keys(channelMap));
            if (!!guess) {
                console.log("Switching to channel " + channelMap[guess])
                dtv.tune(channelMap[guess])
            }
        } else if (channel.channel.number) {
            console.log("Switching to channel " + channel.channel.number)
            dtv.tune(channel.channel.number)
        }
        break;

    case 'DoubleDown':
        dtv.processKey('pause');
        doubleDown()
        break;
    default:
      console.log('unimplemented message: ' + message.message);
  }

}

async function doubleDown() {
    var getTuner = async function() {
        return await processCommand('FA83').then(value => {
                    var data = (value.return || {}).data
                    return data.length > 32 ? data[32] : 0;
                })
    }
    var currentTuner = await getTuner();

    return processKey('down').then(_ => new Promise((resolve) => {
        setTimeout(resolve, 1000);
    })).then(getTuner).then(newTuner => {
        if (currentTuner == newTuner) {
            processKey('down')
        }
    });
}

async function processCommand(command) {
    return new Promise((resolve, reject) => {
        dtv.processCommand(command, function(err, resp) {
            if (!!err) {
                reject(err)
            } else {
                resolve(resp)
            }
        })
    })
}

async function processKey(key) {
    return new Promise((resolve, reject) => {
        dtv.processKey(key, undefined, function(err, resp) {
            if (!!err) {
                reject(err)
            }
            resolve()
        })
    })
}

//TODO queued commands...
var address = (config.useHttps ? 'https://' : 'http://')
              + config.mq.host + ':' + config.mq.port + '/api/stream/queue/' + config.clientId;
console.log('connecting to:' + address);
function startStream() {
  var es = new eventsource(address, headers);
  es.addEventListener('message', message => {
    console.log("recieved message" + JSON.stringify(message));
    if (!!message) {
      var data = JSON.parse(message.data);
      if (!!data) {
        try {
          handleMessage(data);
        } catch (e) {
          console.error(e);
        }
      }
    }
  });

  es.onerror = function(err) {
    setTimeout(_ => {
        if (es.readyState === eventsource.CLOSED) {
            es.close();
            setTimeout(startStream, 5000);
        }
    }, 0);
  }
}
startStream();
<|endoftext|>


<commit_before>var vdf = require('vdf');
var fs = require('fs');
var SteamID = require('steamid');

var protomask = 0x80000000;

var Language = require(__dirname + '/language.js');
var Protos = require(__dirname + '/protos.js');

var base_gcmessages = Protos.base_gcmessages;
var tf_gcmessages = Protos.tf_gcmessages;

module.exports = TeamFortress2;

require('util').inherits(TeamFortress2, require('events').EventEmitter);

function TeamFortress2(steam) {
	this._steam = steam;
	this.haveGCSession = false;

	var self = this;

	// "extend" the default steam.gamesPlayed function so we can catch when TF2 starts up
	var gamesPlayed = steam.gamesPlayed;
	steam.gamesPlayed = function(appids) {
		if(appids.indexOf(440) != -1 && !self.haveGCSession) {
			self._connect();
		} else if(self._helloInterval) {
			clearInterval(self._helloInterval);
			self._helloInterval = null;
		}

		gamesPlayed.call(steam, appids);
	};

	steam.on('fromGC', function(appID, type, body) {
		if(appID != 440) {
			// Not from the TF2 GC
			return;
		}

		var protobuf = !!(type & protomask);
		type &= ~protomask;

		if(self._handlers[type]) {
			self._handlers[type].call(self, body);
		} else {
			var msgName = type;
			for(var i in Language) {
				if(Language[i] == type) {
					msgName = i;
					break;
				}
			}

			self.emit('debug', "Got unhandled GC message " + msgName + (protobuf ? " (protobuf)" : ""));
		}
	});
}

TeamFortress2.prototype._connect = function() {
	var self = this;
	this._helloInterval = setInterval(function() {
		if(self.haveGCSession) {
			clearInterval(self._helloInterval);
			self._helloInterval = null;
			return;
		}

		self._send(Language.ClientHello, base_gcmessages.CMsgClientHello, {});
	}, 2000);
};

TeamFortress2.prototype._send = function(type, protobuf, body) {
	var msgName = type;
	for(var i in Language) {
		if(Language[i] == type) {
			msgName = i;
			break;
		}
	}

	this.emit('debug', "Sending GC message " + msgName);

	if(protobuf) {
		this._steam.toGC(440, type | protomask, protobuf.serialize(body));
	} else {
		this._steam.toGC(440, type, body);
	}
};

TeamFortress2.prototype.setLang = function(langFile) {
	var lang = vdf.parse(langFile);
	// The vdf parser appears to add some random characters and quotes to the root 'lang' key, so we'll just use a loop to find it
	for(var i in lang) {
		this.lang = lang[i].Tokens;
	}
};

TeamFortress2.prototype.craft = function(items, recipe) {
	var buffer = new Buffer(2 + 2 + (8 * items.length));
	buffer.writeInt16LE(recipe || -2, 0); // -2 is wildcard
	buffer.writeInt16LE(items.length, 2);
	for(var i = 0; i < items.length; i++) {
		buffer.writeUInt64LE(items[i], 4 + (i * 8));
	}

	this._send(Language.Craft, null, buffer);
};

TeamFortress2.prototype.trade = function(steamID) {
	var buffer = new Buffer(12);
	buffer.writeUInt32LE(0, 0);
	buffer.writeUInt64LE(steamID, 4);
	this._send(Language.Trading_InitiateTradeRequest, null, buffer);
};

TeamFortress2.prototype.cancelTradeRequest = function() {
	var buffer = new Buffer(0);
	this._send(Language.Trading_CancelSession, null, buffer);
};

TeamFortress2.prototype.respondToTrade = function(tradeID, accept) {
	var buffer = new Buffer(8);
	buffer.writeUInt32LE(accept ? TeamFortress2.TradeResponse.Accepted : TeamFortress2.TradeResponse.Declined, 0);
	buffer.writeUInt32LE(tradeID, 4);
	this._send(Language.Trading_InitiateTradeResponse, null, buffer);
};

TeamFortress2.prototype.setStyle = function(item, style) {
	var buffer = new Buffer(12);
	buffer.writeUInt64LE(item, 0);
	buffer.writeUInt32LE(style, 8);
	this._send(Language.SetItemStyle, null, buffer);
};

TeamFortress2.prototype.setPosition = function(item, position) {
	var buffer = new Buffer(16);
	buffer.writeUInt64LE(item, 0);
	buffer.writeUInt64LE(position, 8);
	this._send(Language.SetSingleItemPosition, null, buffer);
};

TeamFortress2.prototype.setPositions = function(items) {
	this._send(Language.SetItemPositions, base_gcmessages.CMsgSetItemPositions, {"itemPositions": items});
};

TeamFortress2.prototype.deleteItem = function(item) {
	var buffer = new Buffer(8);
	buffer.writeUInt64LE(item);
	this._send(Language.Delete, null, buffer);
};

TeamFortress2.prototype.wrapItem = function(wrapID, itemID) {
	var buffer = new Buffer(16);
	buffer.writeUInt64LE(wrapID, 0);
	buffer.writeUInt64LE(itemID, 8);
	this._send(Language.GiftWrapItem, null, buffer);
};

TeamFortress2.prototype.deliverGift = function(gift, steamID) {
	var buffer = new Buffer(16);
	buffer.writeUInt64LE(gift, 0);
	buffer.writeUInt64LE(steamID, 8);
	this._send(Language.DeliverGift, null, buffer);
};

TeamFortress2.prototype.unwrapGift = function(gift) {
	var buffer = new Buffer(8);
	buffer.writeUInt64LE(gift);
	this._send(Language.UnwrapGiftRequest, null, buffer);
};

TeamFortress2.prototype.useItem = function(item) {
	this._send(Language.UseItemRequest, base_gcmessages.CMsgUseItem, {"itemId": item});
};

TeamFortress2.prototype.sortBackpack = function(sortType) {
	this._send(Language.SortItems, base_gcmessages.CMsgSortItems, {"sortType": sortType});
};

TeamFortress2.prototype.sendProfessorSpeks = function(steamID) {
	this._send(Language.FreeTrial_ChooseMostHelpfulFriend, tf_gcmessages.CMsgTFFreeTrialChooseMostHelpfulFriend, {"accountIdFriend": new SteamID(steamID).accountid});
};

TeamFortress2.prototype.createServerIdentity = function() {
	this._send(Language.GameServer_CreateIdentity, tf_gcmessages.CMsgGC_GameServer_CreateIdentity, {"accountId": new SteamID(this._steam.steamID).accountid});
};

TeamFortress2.prototype.getRegisteredServers = function() {
	this._send(Language.GameServer_List, tf_gcmessages.CMsgGC_GameServer_List, {"accountId": new SteamID(this._steam.steamID).accountid});
};

TeamFortress2.prototype.resetServerIdentity = function(id) {
	this._send(Language.GameServer_ResetIdentity, tf_gcmessages.CMsgGC_GameServer_ResetIdentity, {"gameServerAccountId": id});
};

TeamFortress2.prototype.openCrate = function(keyID, crateID) {
	var buffer = new Buffer(16);
	buffer.writeUInt64LE(keyID, 0);
	buffer.writeUInt64LE(crateID, 8);
	this._send(Language.UnlockCrate, null, buffer);
};

TeamFortress2.prototype.requestSpyVsEngiWarStats = function() {
	this._send(Language.SpyVsEngyWar_RequestGlobalStats, tf_gcmessages.CGCMsgGC_SpyVsEngyWar_RequestGlobalStats, {});
};

TeamFortress2.prototype._handlers = {};

require('./enums.js');
require('./handlers.js');<commit_msg>Handle GC disconnects caused by Steam outages<commit_after>var vdf = require('vdf');
var fs = require('fs');
var SteamID = require('steamid');

var protomask = 0x80000000;

var Language = require(__dirname + '/language.js');
var Protos = require(__dirname + '/protos.js');

var base_gcmessages = Protos.base_gcmessages;
var tf_gcmessages = Protos.tf_gcmessages;

module.exports = TeamFortress2;

require('util').inherits(TeamFortress2, require('events').EventEmitter);

function TeamFortress2(steam) {
	this._steam = steam;
	this.haveGCSession = false;
	this._hadGCSession = false;

	var self = this;

	// "extend" the default steam.gamesPlayed function so we can catch when TF2 starts up
	var gamesPlayed = steam.gamesPlayed;
	steam.gamesPlayed = function(appids) {
		if(appids.indexOf(440) != -1) {
			if(!self.haveGCSession) {
				self._connect();
			}
		} else {
			if(self._helloInterval) {
				clearInterval(self._helloInterval);
				self._helloInterval = null;
			}

			self.haveGCSession = false;
			self._hadGCSession = false;
		}

		gamesPlayed.call(steam, appids);
	};

	steam.on('fromGC', function(appID, type, body) {
		if(appID != 440) {
			// Not from the TF2 GC
			return;
		}

		var protobuf = !!(type & protomask);
		type &= ~protomask;

		if(self._handlers[type]) {
			self._handlers[type].call(self, body);
		} else {
			var msgName = type;
			for(var i in Language) {
				if(Language[i] == type) {
					msgName = i;
					break;
				}
			}

			self.emit('debug', "Got unhandled GC message " + msgName + (protobuf ? " (protobuf)" : ""));
		}
	});

	steam.on('loggedOff', function() {
		self._hadGCSession = self.haveGCSession;
		if(self.haveGCSession) {
			self.emit('disconnectedFromGC', TeamFortress2.GCGoodbyeReason.NO_SESSION);
			self.haveGCSession = false;
		}
	});
	steam.on('error', function(e) {
		self._hadGCSession = false;
		if(self.haveGCSession) {
			self.emit('disconnectedFromGC', TeamFortress2.GCGoodbyeReason.NO_SESSION);
			self.haveGCSession = false;
		}
	});

	steam.on('loggedOn', function() {
		if(self._hadGCSession) {
			self._connect();
			self._hadGCSession = false;
		}
	});
}

TeamFortress2.prototype._connect = function() {
	var self = this;
	this._helloInterval = setInterval(function() {
		if(self.haveGCSession) {
			clearInterval(self._helloInterval);
			self._helloInterval = null;
			return;
		}

		self._send(Language.ClientHello, base_gcmessages.CMsgClientHello, {});
	}, 2000);
};

TeamFortress2.prototype._send = function(type, protobuf, body) {
	var msgName = type;
	for(var i in Language) {
		if(Language[i] == type) {
			msgName = i;
			break;
		}
	}

	this.emit('debug', "Sending GC message " + msgName);

	if(protobuf) {
		this._steam.toGC(440, type | protomask, protobuf.serialize(body));
	} else {
		this._steam.toGC(440, type, body);
	}
};

TeamFortress2.prototype.setLang = function(langFile) {
	var lang = vdf.parse(langFile);
	// The vdf parser appears to add some random characters and quotes to the root 'lang' key, so we'll just use a loop to find it
	for(var i in lang) {
		this.lang = lang[i].Tokens;
	}
};

TeamFortress2.prototype.craft = function(items, recipe) {
	var buffer = new Buffer(2 + 2 + (8 * items.length));
	buffer.writeInt16LE(recipe || -2, 0); // -2 is wildcard
	buffer.writeInt16LE(items.length, 2);
	for(var i = 0; i < items.length; i++) {
		buffer.writeUInt64LE(items[i], 4 + (i * 8));
	}

	this._send(Language.Craft, null, buffer);
};

TeamFortress2.prototype.trade = function(steamID) {
	var buffer = new Buffer(12);
	buffer.writeUInt32LE(0, 0);
	buffer.writeUInt64LE(steamID, 4);
	this._send(Language.Trading_InitiateTradeRequest, null, buffer);
};

TeamFortress2.prototype.cancelTradeRequest = function() {
	var buffer = new Buffer(0);
	this._send(Language.Trading_CancelSession, null, buffer);
};

TeamFortress2.prototype.respondToTrade = function(tradeID, accept) {
	var buffer = new Buffer(8);
	buffer.writeUInt32LE(accept ? TeamFortress2.TradeResponse.Accepted : TeamFortress2.TradeResponse.Declined, 0);
	buffer.writeUInt32LE(tradeID, 4);
	this._send(Language.Trading_InitiateTradeResponse, null, buffer);
};

TeamFortress2.prototype.setStyle = function(item, style) {
	var buffer = new Buffer(12);
	buffer.writeUInt64LE(item, 0);
	buffer.writeUInt32LE(style, 8);
	this._send(Language.SetItemStyle, null, buffer);
};

TeamFortress2.prototype.setPosition = function(item, position) {
	var buffer = new Buffer(16);
	buffer.writeUInt64LE(item, 0);
	buffer.writeUInt64LE(position, 8);
	this._send(Language.SetSingleItemPosition, null, buffer);
};

TeamFortress2.prototype.setPositions = function(items) {
	this._send(Language.SetItemPositions, base_gcmessages.CMsgSetItemPositions, {"itemPositions": items});
};

TeamFortress2.prototype.deleteItem = function(item) {
	var buffer = new Buffer(8);
	buffer.writeUInt64LE(item);
	this._send(Language.Delete, null, buffer);
};

TeamFortress2.prototype.wrapItem = function(wrapID, itemID) {
	var buffer = new Buffer(16);
	buffer.writeUInt64LE(wrapID, 0);
	buffer.writeUInt64LE(itemID, 8);
	this._send(Language.GiftWrapItem, null, buffer);
};

TeamFortress2.prototype.deliverGift = function(gift, steamID) {
	var buffer = new Buffer(16);
	buffer.writeUInt64LE(gift, 0);
	buffer.writeUInt64LE(steamID, 8);
	this._send(Language.DeliverGift, null, buffer);
};

TeamFortress2.prototype.unwrapGift = function(gift) {
	var buffer = new Buffer(8);
	buffer.writeUInt64LE(gift);
	this._send(Language.UnwrapGiftRequest, null, buffer);
};

TeamFortress2.prototype.useItem = function(item) {
	this._send(Language.UseItemRequest, base_gcmessages.CMsgUseItem, {"itemId": item});
};

TeamFortress2.prototype.sortBackpack = function(sortType) {
	this._send(Language.SortItems, base_gcmessages.CMsgSortItems, {"sortType": sortType});
};

TeamFortress2.prototype.sendProfessorSpeks = function(steamID) {
	this._send(Language.FreeTrial_ChooseMostHelpfulFriend, tf_gcmessages.CMsgTFFreeTrialChooseMostHelpfulFriend, {"accountIdFriend": new SteamID(steamID).accountid});
};

TeamFortress2.prototype.createServerIdentity = function() {
	this._send(Language.GameServer_CreateIdentity, tf_gcmessages.CMsgGC_GameServer_CreateIdentity, {"accountId": new SteamID(this._steam.steamID).accountid});
};

TeamFortress2.prototype.getRegisteredServers = function() {
	this._send(Language.GameServer_List, tf_gcmessages.CMsgGC_GameServer_List, {"accountId": new SteamID(this._steam.steamID).accountid});
};

TeamFortress2.prototype.resetServerIdentity = function(id) {
	this._send(Language.GameServer_ResetIdentity, tf_gcmessages.CMsgGC_GameServer_ResetIdentity, {"gameServerAccountId": id});
};

TeamFortress2.prototype.openCrate = function(keyID, crateID) {
	var buffer = new Buffer(16);
	buffer.writeUInt64LE(keyID, 0);
	buffer.writeUInt64LE(crateID, 8);
	this._send(Language.UnlockCrate, null, buffer);
};

TeamFortress2.prototype.requestSpyVsEngiWarStats = function() {
	this._send(Language.SpyVsEngyWar_RequestGlobalStats, tf_gcmessages.CGCMsgGC_SpyVsEngyWar_RequestGlobalStats, {});
};

TeamFortress2.prototype._handlers = {};

require('./enums.js');
require('./handlers.js');<|endoftext|>


<commit_before>/*
 * gulp-frep
 * https://github.com/jonschlinkert/gulp-frep
 * Copyright (c) 2014 Jon Schlinkert
 * Licensed under the MIT license.
 */

var Buffer = require('buffer').Buffer;
var es = require('event-stream');
var frep = require('frep');

module.exports = function (opts) {
  'use strict';

  opts = opts || {};
  opts.patterns = opts.patterns || [];

  return es.map(function (file, cb) {
    try {
      file.contents = new Buffer(frep.strWithArr(String(file.contents), opts));
    } catch (err) {
      console.warn('Error caught from js-beautify: ' + err.message + '.');
    }
    cb(null, file);
  });
};<commit_msg>Fixing error message<commit_after>/*
 * gulp-frep
 * https://github.com/jonschlinkert/gulp-frep
 * Copyright (c) 2014 Jon Schlinkert
 * Licensed under the MIT license.
 */

var Buffer = require('buffer').Buffer;
var es = require('event-stream');
var frep = require('frep');

module.exports = function (opts) {
  'use strict';

  opts = opts || {};
  opts.patterns = opts.patterns || [];

  return es.map(function (file, cb) {
    try {
      file.contents = new Buffer(frep.strWithArr(String(file.contents), opts));
    } catch (err) {
      console.warn('Error caught from frep: ' + err.message + '.');
    }
    cb(null, file);
  });
};<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var through = require('through2');
var fs = require('fs');
var path = require('path');
var cssTransform = require('./css-transform');
var CleanCSS = require('clean-css');

var defaults = {
    'autoInject': true,
    'autoInjectOptions': {
        'verbose': true
    },
    'rootDir': process.cwd(),
    'minify': false,
    'minifyOptions': {
        // Check out a list of CSS minify options at [CleanCSS](https://github.com/jakubpawlowicz/clean-css#how-to-use-clean-css-programmatically).
    }
};

var pkg = JSON.parse(fs.readFileSync(process.cwd() + '/package.json') || '{}');
var options = pkg['browserify-css'] || {};
if (typeof options === 'string') {
    var base = path.relative(__dirname, process.cwd());
    options = require(path.join(base, options)) || {};
}
options = _.defaults(options || {}, defaults);

module.exports = function(filename) {
    if ( ! /\.css$/i.test(filename)) {
        return through();
    }

    var cssBuffer = {};
    var buffer = '';
    var externalURLs = [];

    return through(
        function transform(chunk, enc, next) {
            buffer += chunk;
            next();
        },
        function flush(done) {
            var that = this;

            cssTransform({ rootDir: options['rootDir'] }, filename, function(data) {
                var moduleBody = '';
                var rootDir = path.join(process.cwd(), options.rootDir);
                var relativePath = path.relative(rootDir, path.dirname(filename));
                var href = path.join(relativePath, path.basename(filename));

                if (options['minify']) {
                    data = new CleanCSS(options['minifyOptions']).minify(data);
                }

                if ( ! options['autoInject']) {
                    moduleBody = 'module.exports = ' + JSON.stringify(data) + ';'
                } else {
                    if (options.autoInjectOptions['verbose']) {
                        moduleBody = 'var css = ' + JSON.stringify(data) + '; (require(' + JSON.stringify(__dirname) + ').createStyle(css, { "href": ' + JSON.stringify(href) + '})); module.exports = css;'
                    } else {
                        moduleBody = 'var css = ' + JSON.stringify(data) + '; (require(' + JSON.stringify(__dirname) + ').createStyle(css)); module.exports = css;'
                    }
                }

                that.push(moduleBody);
                that.push(null);
                done();
            });
        }
    );
};
<commit_msg>Fixes an issue that cannot pass custom options to the transform function from the API<commit_after>'use strict';

var _ = require('lodash');
var through = require('through2');
var fs = require('fs');
var path = require('path');
var cssTransform = require('./css-transform');
var CleanCSS = require('clean-css');

var defaults = {
    'autoInject': true,
    'autoInjectOptions': {
        'verbose': true
    },
    'rootDir': process.cwd(),
    'minify': false,
    'minifyOptions': {
        // Check out a list of CSS minify options at [CleanCSS](https://github.com/jakubpawlowicz/clean-css#how-to-use-clean-css-programmatically).
    }
};

var pkg = JSON.parse(fs.readFileSync(process.cwd() + '/package.json') || '{}');
var options = pkg['browserify-css'] || {};
if (typeof options === 'string') {
    var base = path.relative(__dirname, process.cwd());
    try {
        options = require(path.join(base, options)) || defaults;
    } catch (err) {
        options = defaults;
    }
}
options = _.defaults(options, defaults);

module.exports = function(filename, opts) {
    if ( ! /\.css$/i.test(filename)) {
        return through();
    }

    var cssBuffer = {};
    var buffer = '';
    var externalURLs = [];

    options = _.extend({}, options, opts);

    return through(
        function transform(chunk, enc, next) {
            buffer += chunk;
            next();
        },
        function flush(done) {
            var that = this;

            cssTransform({ rootDir: options['rootDir'] }, filename, function(data) {
                var moduleBody = '';
                var rootDir = path.join(process.cwd(), options.rootDir);
                var relativePath = path.relative(rootDir, path.dirname(filename));
                var href = path.join(relativePath, path.basename(filename));

                if (options['minify']) {
                    data = new CleanCSS(options['minifyOptions']).minify(data);
                }

                if ( ! options['autoInject']) {
                    moduleBody = 'module.exports = ' + JSON.stringify(data) + ';'
                } else {
                    if (options.autoInjectOptions['verbose']) {
                        moduleBody = 'var css = ' + JSON.stringify(data) + '; (require(' + JSON.stringify(__dirname) + ').createStyle(css, { "href": ' + JSON.stringify(href) + '})); module.exports = css;'
                    } else {
                        moduleBody = 'var css = ' + JSON.stringify(data) + '; (require(' + JSON.stringify(__dirname) + ').createStyle(css)); module.exports = css;'
                    }
                }

                that.push(moduleBody);
                that.push(null);
                done();
            });
        }
    );
};
<|endoftext|>


<commit_before>/*!
 * is-empty-function <https://github.com/tunnckoCore/is-empty-function>
 *
 * Copyright (c) 2015 Charlike Mike Reagent, contributors.
 * Released under the MIT license.
 */

'use strict'

'use strict'

var balanced = require('balanced-match')
var cleanupCoverageCode = require('cleanup-coverage-code')

/**
 * Check given function have empty body or not, and returns true or false.
 *
 * **Example:**
 *
 * ```js
 * var isEmptyFunction = require('is-empty-function')
 *
 * var fixture = 'function() {}'
 * isEmptyFunction(fixture)
 * //=> true
 *
 * var fixture = function named() {}
 * isEmptyFunction(fixture)
 * //=> true
 *
 * var fixture = function() { return true; }
 * isEmptyFunction(fixture)
 * //=> false
 *
 * var fixture = function named() { return true; }
 * isEmptyFunction(fixture)
 * //=> false
 * ```
 *
 * @name isEmptyFunction
 * @param  {Function|String} `[fn]` passed to [parse-function][parse-function]
 * @return {Boolean}
 * @api private
 */
module.exports = function isEmptyFunction (fn) {
  if (fn) {
    var fnString = fn.toString()
    var body = balanced('{', '}', fnString).body
    body = cleanupCoverageCode(body)
    return body.length > 0 ? false : true
  }
  return false
}
<commit_msg>cleanup<commit_after>/*!
 * is-empty-function <https://github.com/tunnckoCore/is-empty-function>
 *
 * Copyright (c) 2015 Charlike Mike Reagent, contributors.
 * Released under the MIT license.
 */

'use strict'

var balanced = require('balanced-match')
var cleanupCoverageCode = require('cleanup-coverage-code')

/**
 * Check given function have empty body or not, and returns true or false.
 *
 * **Example:**
 *
 * ```js
 * var isEmptyFunction = require('is-empty-function')
 *
 * var fixture = 'function() {}'
 * isEmptyFunction(fixture)
 * //=> true
 *
 * var fixture = function named() {}
 * isEmptyFunction(fixture)
 * //=> true
 *
 * var fixture = function() { return true }
 * isEmptyFunction(fixture)
 * //=> false
 *
 * var fixture = function named() { return true }
 * isEmptyFunction(fixture)
 * //=> false
 * ```
 *
 * @name isEmptyFunction
 * @param  {Function|String} `[fn]` passed to [parse-function][parse-function]
 * @return {Boolean}
 * @api public
 */
module.exports = function isEmptyFunction (fn) {
  if (fn) {
    var fnString = fn.toString()
    var body = balanced('{', '}', fnString).body
    body = cleanupCoverageCode(body)
    return body.length > 0 ? false : true
  }
  return false
}
<|endoftext|>


<commit_before>// contains, add, remove, toggle

module.exports = ClassList

function ClassList(elem) {
    var cl = elem.classList

    if (cl) {
        return cl
    }

    var classList = {
        add: add
        , remove: remove
        , contains: contains
        , toggle: toggle
        , toString: $toString
        , length: 0
        , item: item
    }

    return classList

    function add(token) {
        var list = getTokens()
        if (list.indexOf(token) > -1) {
            return
        }
        list.push(token)
        setTokens(list)
    }

    function remove(token) {
        var list = getTokens()
            , index = list.indexOf(token)

        if (index === -1) {
            return
        }

        list.splice(index, 1)
        setTokens(list)
    }

    function contains(token) {
        return getTokens().indexOf(token) > -1
    }

    function toggle(token) {
        if (contains(token)) {
            remove(token)
            return false
        } else {
            add(token)
            return true
        }
    }

    function $toString() {
        return elem.className
    }

    function item(index) {
        var tokens = getTokens()
        return tokens[index] || null
    }

    function getTokens() {
        var className = elem.className

        return className.split(" ").filter(Boolean)
    }

    function setTokens(list) {
        var length = list.length

        elem.className = list.join(" ")
        classList.length = length

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

        delete list[length]
    }
}
<commit_msg>filter library<commit_after>// contains, add, remove, toggle

module.exports = ClassList

function ClassList(elem) {
    var cl = elem.classList

    if (cl) {
        return cl
    }

    var classList = {
        add: add
        , remove: remove
        , contains: contains
        , toggle: toggle
        , toString: $toString
        , length: 0
        , item: item
    }

    return classList

    function add(token) {
        var list = getTokens()
        if (list.indexOf(token) > -1) {
            return
        }
        list.push(token)
        setTokens(list)
    }

    function remove(token) {
        var list = getTokens()
            , index = list.indexOf(token)

        if (index === -1) {
            return
        }

        list.splice(index, 1)
        setTokens(list)
    }

    function contains(token) {
        return getTokens().indexOf(token) > -1
    }

    function toggle(token) {
        if (contains(token)) {
            remove(token)
            return false
        } else {
            add(token)
            return true
        }
    }

    function $toString() {
        return elem.className
    }

    function item(index) {
        var tokens = getTokens()
        return tokens[index] || null
    }

    function getTokens() {
        var className = elem.className

        return filter(className.split(" "), isTruthy)
    }

    function setTokens(list) {
        var length = list.length

        elem.className = list.join(" ")
        classList.length = length

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

        delete list[length]
    }
}

function filter (arr, fn) {
    var ret = []
    for (var i = 0; i < arr.length; i++) {
        if (fn(arr[i])) ret.push(arr[i])
    }
    return ret
}

function isTruthy(value) {
    return !!value
}
<|endoftext|>


<commit_before>'use strict';

// Modules
var path = require('path');
var fs = require('fs');
var _ = require('lodash');

// "Constants"
var PLUGIN_NAME = 'kalabox-plugin-drush';

module.exports = function(argv, app, events, engine, tasks) {

  // Helpers
  /**
   * Gets plugin conf from the appconfig or from CLI arg
   **/
  var getOpts = function() {
    // Grab our options from config
    var opts = app.config.pluginConf[PLUGIN_NAME];

    // Override any config coming in on the CLI
    for (var key in opts) {
      if (argv[key]) {
        opts[key] = argv[key];
      }
    }
    return opts;
  };

  /**
   * Returns an arrayed set of drush-ready commands
   **/
  var getCmd = function() {
    // @todo: not sure if the command structure is different on D7 vs D6
    // Grab our options from config so we can filter these out
    var cmd = argv._;
    delete argv._;
    var strip = app.config.pluginConf[PLUGIN_NAME];

    // Remove
    for (var key in strip) {
      delete argv[key];
    }

    for (var opt in argv) {
      cmd.push('--' + opt + '=' + argv[opt]);
    }

    return cmd;
  };

  /*
   * Some drupal sites dont use settings.php and drush will fail without this
   * @todo : there should be a way for the pressflow plugin to handle this?
   */
  var getPressflowSettings = function() {
    var pressflowSettings = {
      databases: {
        default: {
          default: {
            driver: 'mysql',
            prefix: '',
            database: 'kalabox',
            username: 'kalabox',
            password: '',
            host: app.domain,
            port: 3306,
          }
        }
      },
      conf: {
        'pressflow_smart_start': 1
      }
    };
    return JSON.stringify(pressflowSettings);
  };

  /**
   * Runs a git command on the app data container
   **/
  var runDrushCMD = function(cmd, opts, done) {
    engine.run(
      'kalabox/drush:stable',
      cmd,
      {
        Env: [
          'DRUSH_VERSION=' + opts['drush-version'],
          'APPNAME=' +  app.name,
          'APPDOMAIN=' +  app.domain,
          'PRESSFLOW_SETTINGS=' + getPressflowSettings()
        ],
        HostConfig: {
          VolumesFrom: [app.dataContainerName]
        }
      },
      {
        Binds: [
          app.config.homeBind + ':/ssh:rw',
          app.rootBind + ':/src:rw'
        ]
      },
      done
    );
  };

  /**
   * Create a symlink from the local.aliases.drushrc.php file to ~/.drush/kalabox/<appname>.aliases.drushrc.php
   **/
  var copyLocalAlias = function() {
    var home =
      process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME'];
    var drushPath = path.resolve(home, '.drush');
    // Create ~/.drush dir if it doesn't exist.
    if (!fs.existsSync(drushPath)) {
      fs.mkdirSync(drushPath);
    }

    // Define the paths
    var src = path.resolve(
      app.root, 'config', 'drush', 'local.aliases.drushrc.php'
    );
    var dst = path.resolve(drushPath, app.domain + '.aliases.drushrc.php');

    // Create the symlink
    if (process.platform !== 'win32') {
      if (!fs.existsSync(dst) && fs.existsSync(src)) {
        fs.symlinkSync(src, dst);
      }
    }
  };

  // Events
  // Install the util container for our things
  events.on('post-install', function(app, done) {
    engine.build({name: 'kalabox/drush:stable'}, done);
  });

  // Updates kalabox aliases when app is started.
  // This allows for both kbox drush to be used
  // and local drush to be used via: drush @<appname> status
  events.on('post-start-component', function(component, done) {
    // Only run on the db container
    if (component.name !== 'db') {
      done();
    }
    else {
      engine.inspect(component.containerId, function(err, data) {
        var key = '3306/tcp';
        if (data && data.NetworkSettings.Ports[key]) {
          var port = data.NetworkSettings.Ports[key][0].HostPort;
          var commands = [
            [
              'sed',
              '-i',
              's/\'host\'.*/\'host\' => \'' + app.domain + '\',/g',
              '/src/config/drush/aliases.drushrc.php'
            ],
            [
              'sed',
              '-i',
              's/\'uri\'.*/\'uri\' => \'' + app.domain + '\',/g',
              '/src/config/drush/local.aliases.drushrc.php'
            ],
            [
              'sed',
              '-i',
              's/aliases\\[\'.*/aliases[\'' + app.name + '\'] = array(/g',
              '/src/config/drush/local.aliases.drushrc.php'
            ],
            [
              'sed',
              '-i',
              's@\'root\'.*@\'root\' => \'' +
              path.join(app.config.codeRoot, app.name) + '\',@g',
              '/src/config/drush/local.aliases.drushrc.php'
            ],
            [
              'sed',
              '-i',
              's%\'db-url.*%\'db-url\' => \'mysql://kalabox@' + app.domain +
              ':' + port + '/kalabox\',%g',
              '/src/config/drush/local.aliases.drushrc.php'
            ]
          ];

          _.map(commands, function(cmd) {
            engine.queryString(
              'kalabox/debian:stable',
              cmd,
              {
                'Env': ['APPDOMAIN=' + app.domain]
              },
              {
                Binds: [app.rootBind + ':/src:rw']
              },
              function(err) {
                if (err) {
                  console.log(err);
                }
              }
            );
          });
          copyLocalAlias();
        }
        done();
      });
    }
  });

  // Tasks
  // drush wrapper: kbox drush COMMAND
  tasks.registerTask([app.name, 'drush'], function(done) {
    var opts = getOpts();
    var cmd = getCmd();
    cmd.unshift('@dev');
    runDrushCMD(cmd, opts, done);
  });

};
<commit_msg>#319: Code root is now explictly defined<commit_after>'use strict';

// Modules
var path = require('path');
var fs = require('fs');
var _ = require('lodash');

// "Constants"
var PLUGIN_NAME = 'kalabox-plugin-drush';

module.exports = function(argv, app, events, engine, tasks) {

  // Helpers
  /**
   * Gets plugin conf from the appconfig or from CLI arg
   **/
  var getOpts = function() {
    // Grab our options from config
    var opts = app.config.pluginConf[PLUGIN_NAME];

    // Override any config coming in on the CLI
    for (var key in opts) {
      if (argv[key]) {
        opts[key] = argv[key];
      }
    }
    return opts;
  };

  /**
   * Returns an arrayed set of drush-ready commands
   **/
  var getCmd = function() {
    // @todo: not sure if the command structure is different on D7 vs D6
    // Grab our options from config so we can filter these out
    var cmd = argv._;
    delete argv._;
    var strip = app.config.pluginConf[PLUGIN_NAME];

    // Remove
    for (var key in strip) {
      delete argv[key];
    }

    for (var opt in argv) {
      cmd.push('--' + opt + '=' + argv[opt]);
    }

    return cmd;
  };

  /*
   * Some drupal sites dont use settings.php and drush will fail without this
   * @todo : there should be a way for the pressflow plugin to handle this?
   */
  var getPressflowSettings = function() {
    var pressflowSettings = {
      databases: {
        default: {
          default: {
            driver: 'mysql',
            prefix: '',
            database: 'kalabox',
            username: 'kalabox',
            password: '',
            host: app.domain,
            port: 3306,
          }
        }
      },
      conf: {
        'pressflow_smart_start': 1
      }
    };
    return JSON.stringify(pressflowSettings);
  };

  /**
   * Runs a git command on the app data container
   **/
  var runDrushCMD = function(cmd, opts, done) {
    engine.run(
      'kalabox/drush:stable',
      cmd,
      {
        Env: [
          'DRUSH_VERSION=' + opts['drush-version'],
          'APPNAME=' +  app.name,
          'APPDOMAIN=' +  app.domain,
          'PRESSFLOW_SETTINGS=' + getPressflowSettings()
        ],
        HostConfig: {
          VolumesFrom: [app.dataContainerName]
        }
      },
      {
        Binds: [
          app.config.homeBind + ':/ssh:rw',
          app.rootBind + ':/src:rw'
        ]
      },
      done
    );
  };

  /**
   * Create a symlink from the local.aliases.drushrc.php file to ~/.drush/kalabox/<appname>.aliases.drushrc.php
   **/
  var copyLocalAlias = function() {
    var home =
      process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME'];
    var drushPath = path.resolve(home, '.drush');
    // Create ~/.drush dir if it doesn't exist.
    if (!fs.existsSync(drushPath)) {
      fs.mkdirSync(drushPath);
    }

    // Define the paths
    var src = path.resolve(
      app.root, 'config', 'drush', 'local.aliases.drushrc.php'
    );
    var dst = path.resolve(drushPath, app.domain + '.aliases.drushrc.php');

    // Create the symlink
    if (process.platform !== 'win32') {
      if (!fs.existsSync(dst) && fs.existsSync(src)) {
        fs.symlinkSync(src, dst);
      }
    }
  };

  // Events
  // Install the util container for our things
  events.on('post-install', function(app, done) {
    engine.build({name: 'kalabox/drush:stable'}, done);
  });

  // Updates kalabox aliases when app is started.
  // This allows for both kbox drush to be used
  // and local drush to be used via: drush @<appname> status
  events.on('post-start-component', function(component, done) {
    // Only run on the db container
    if (component.name !== 'db') {
      done();
    }
    else {
      engine.inspect(component.containerId, function(err, data) {
        var key = '3306/tcp';
        if (data && data.NetworkSettings.Ports[key]) {
          var port = data.NetworkSettings.Ports[key][0].HostPort;
          var commands = [
            [
              'sed',
              '-i',
              's/\'host\'.*/\'host\' => \'' + app.domain + '\',/g',
              '/src/config/drush/aliases.drushrc.php'
            ],
            [
              'sed',
              '-i',
              's/\'uri\'.*/\'uri\' => \'' + app.domain + '\',/g',
              '/src/config/drush/local.aliases.drushrc.php'
            ],
            [
              'sed',
              '-i',
              's/aliases\\[\'.*/aliases[\'' + app.name + '\'] = array(/g',
              '/src/config/drush/local.aliases.drushrc.php'
            ],
            [
              'sed',
              '-i',
              's@\'root\'.*@\'root\' => \'' +
              app.config.codeRoot, app.name + '\',@g',
              '/src/config/drush/local.aliases.drushrc.php'
            ],
            [
              'sed',
              '-i',
              's%\'db-url.*%\'db-url\' => \'mysql://kalabox@' + app.domain +
              ':' + port + '/kalabox\',%g',
              '/src/config/drush/local.aliases.drushrc.php'
            ]
          ];

          _.map(commands, function(cmd) {
            engine.queryString(
              'kalabox/debian:stable',
              cmd,
              {
                'Env': ['APPDOMAIN=' + app.domain]
              },
              {
                Binds: [app.rootBind + ':/src:rw']
              },
              function(err) {
                if (err) {
                  console.log(err);
                }
              }
            );
          });
          copyLocalAlias();
        }
        done();
      });
    }
  });

  // Tasks
  // drush wrapper: kbox drush COMMAND
  tasks.registerTask([app.name, 'drush'], function(done) {
    var opts = getOpts();
    var cmd = getCmd();
    cmd.unshift('@dev');
    runDrushCMD(cmd, opts, done);
  });

};
<|endoftext|>