<commit_before>const watchifyRequest = require('watchify-request')
const lrScript = require('inject-lr-script-stream')
const htmlIndex = require('simple-html-index')
const stream = require('readable-stream')
const watchify = require('watchify')
const assert = require('assert')
const xtend = require('xtend')
const path = require('path')
const bl = require('bl')

const env = process.env.NODE_ENV

// create html stream
// obj? -> (req, res) -> rstream
exports.html = function html (opts) {
  opts = opts || {}
  const defaultOpts = { entry: '/bundle.js', css: '/bundle.css' }
  const htmlOpts = xtend(defaultOpts, opts)
  const html = htmlIndex(htmlOpts)
  const htmlBuf = (env === 'development')
    ? html.pipe(lrScript()).pipe(bl())
    : html.pipe(bl())

  return function (req, res) {
    res.setHeader('Content-Type', 'text/html')
    return htmlBuf.duplicate()
  }
}

// create css stream
// (fn, str, obj?) -> (req, res) -> rstream
exports.css = function css (sheetify, src, opts) {
  assert.equal(typeof sheetify, 'function', 'sheetify should be a fn')
  assert.equal(typeof src, 'string', 'src should be a location')

  opts = opts || {}
  src = path.resolve(src)
  const defaultOpts = { basedir: path.dirname(src) }
  opts = xtend(defaultOpts, opts)

  return function (req, res) {
    res.setHeader('Content-Type', 'text/css')
    return sheetify(src, opts)
  }
}

// create js stream
// (fn, str, obj?) -> (req, res) -> rstream
exports.js = function js (browserify, src, opts) {
  assert.equal(typeof browserify, 'function', 'browserify should be a fn')
  assert.equal(typeof src, 'string', 'src should be a location')

  opts = opts || {}
  const defaultOpts = {
    cache: {},
    packageCache: {},
    entries: [ require.resolve(src) ],
    fullPaths: true
  }
  var b = browserify(xtend(defaultOpts, opts))

  if (process.env.NODE_ENV === 'development') b = watchify(b)
  const handler = watchifyRequest(b)

  return function (req, res) {
    const ts = new stream.PassThrough()
    handler(req, res, function (err, js) {
      if (err) return ts.emit('error', err)
      res.setHeader('Content-Type', 'application/javascript')
      ts.end(js)
    })
    return ts
  }
}
<commit_msg>css: use sheetify v4<commit_after>const watchifyRequest = require('watchify-request')
const lrScript = require('inject-lr-script-stream')
const htmlIndex = require('simple-html-index')
const stream = require('readable-stream')
const watchify = require('watchify')
const assert = require('assert')
const xtend = require('xtend')
const path = require('path')
const bl = require('bl')

const env = process.env.NODE_ENV

var jsStarted = false
var cssBuf = null
var cssOpts = null

// create html stream
// obj? -> (req, res) -> rstream
exports.html = function html (opts) {
  opts = opts || {}
  const defaultOpts = { entry: '/bundle.js', css: '/bundle.css' }
  const htmlOpts = xtend(defaultOpts, opts)
  const html = htmlIndex(htmlOpts)
  const htmlBuf = (env === 'development')
    ? html.pipe(lrScript()).pipe(bl())
    : html.pipe(bl())

  return function (req, res) {
    res.setHeader('Content-Type', 'text/html')
    return htmlBuf.duplicate()
  }
}

// create css stream
// obj? -> (req, res) -> rstream
exports.css = function css (opts) {
  opts = opts || {}
  cssOpts = opts

  if (jsStarted) throw new Error('css must be registered before js to work')

  return function (req, res) {
    res.setHeader('Content-Type', 'text/css')
    return cssBuf.duplicate()
  }
}

// create js stream
// (fn, str, obj?) -> (req, res) -> rstream
exports.js = function js (browserify, src, opts) {
  assert.equal(typeof browserify, 'function', 'browserify should be a fn')
  assert.equal(typeof src, 'string', 'src should be a location')

  opts = opts || {}
  const defaultOpts = {
    cache: {},
    packageCache: {},
    entries: [ require.resolve(src) ],
    fullPaths: true
  }
  var b = browserify(xtend(defaultOpts, opts))

  // enable css if registered
  if (cssOpts) {
    cssBuf = bl()
    const styleOpts = xtend(cssOpts, {
      out: cssBuf,
      basedir: path.dirname(module.parent)
    })
    b.transform('sheetify/transform', styleOpts)
  }

  if (process.env.NODE_ENV === 'development') b = watchify(b)
  const handler = watchifyRequest(b)
  jsStarted = true

  return function (req, res) {
    const ts = new stream.PassThrough()
    handler(req, res, function (err, js) {
      if (err) return ts.emit('error', err)
      res.setHeader('Content-Type', 'application/javascript')
      ts.end(js)
    })
    return ts
  }
}
<|endoftext|>


<commit_before>'use strict';
var childProcess = require('child_process'),
  path = require('path');

function createDeployer(projectRoot, foundries, environments, environmentName,
                        timestamp) {
  timestamp = timestamp || Math.ceil(new Date().valueOf() / 1000);

  function getEnvironment() {
    return environments[environmentName];
  }

  function newFoundry(location) {
    var foundry = foundries[location],
      environment = getEnvironment(),
      newAppName = environment.newAppName,
      oldAppName,
      cfCmd = process.env.CF_CMD || path.resolve(__dirname, 'bin/cf');

    function cf() {
      var args = Array.prototype.slice.call(arguments, 0),
        displayOutput = true;

      if (args[0] === '--no-output') {
        displayOutput = false;
        args.shift();
      }
      return new Promise(function (resolve, reject) {
        /*jslint nomen: true */
        var results = '',
          stdio = [process.stdin, 'pipe', process.stderr],
          p;
        p = childProcess.spawn(cfCmd, args, {
          cwd: projectRoot,
          env: {
            CF_HOME: foundry.home,
            CF_COLOR: 'false'
          },
          stdio: stdio
        });
        p.stdout.on('data', function (data) {
          var str = data.toString();
          results += str;
          if (displayOutput) {
            process.stdout.write(data);
          }
        });
        p.on('close', function (code) {
          if (code === 0) {
            resolve(results);
          } else {
            reject({
              message: 'error "cf ' + args.join(' ') + '" ' +
                'failed with exit code ' + code
            });
          }
        });
      });
    }
    function setApi() {
      return cf('api', foundry.api);
    }
    function logout() {
      return cf('logout');
    }
    function login() {
      var space = foundry.spaces[environment.appEnv.NODE_ENV];
      return cf('login', '--u', foundry.username, '--p', foundry.password,
                '--o', foundry.org, '--s', space);
    }
    function logApp() {
      return cf('logs', newAppName, '--recent')
        .catch(function (error) {
          // Do not reject so that a failed app log doesn't cause
          // the rest of the script to fail.
          console.error('logApp', newAppName, 'failed', error);
        });
    }
    function pushApp() {
      return cf('push', newAppName,
                '-c', environment.startCommand,
                '-i', environment.instances,
                '-m', environment.memory,
                '-k', environment.disk,
                '-b', environment.buildPack,
                '--no-start');
    }
    function startApp() {
      return cf('start', newAppName);
    }
    function deleteApp(appName) {
      return cf('delete', '-f', '-r', appName)
        .catch(function (error) {
          // Do not reject so that a failed app deletion doesn't cause
          // the rest of the script to fail.
          console.error('deleteApp', appName, 'failed', error);
        });
    }
    function setAppEnvironment() {
      var settings = Object.keys(environment.appEnv).map(function (variable) {
        return function () {
          if (variable.match(/PASSWORD|KEY/)) {
            return cf('--no-output', 'set-env', newAppName, variable,
                      environment.appEnv[variable]);
          }
          return cf('set-env', newAppName, variable,
                    environment.appEnv[variable]);
        };
      });
      settings.push(function () {
        return cf('set-env', newAppName, "FOUNDRY_LOCATION", location);
      });
      return settings.reduce(function (cur, next) {
        return cur.then(next);
      }, Promise.resolve());
    }
    function bindServiceToApp(serviceName) {
      return cf('bind-service', newAppName, serviceName);
    }
    function checkAppState() {
      return cf('app', newAppName)
        .then(function (results) {
          var isRunning;
          isRunning = results
            .split('\n')
            .filter(function (line) {
              return line.substr(0, 1) === '#';
            })
            .map(function (line) {
              var fields = line.split(/ +/),
                state;
              if (fields[0].substr(0, 1) === '#') {
                state = fields[1];
              }
              return state;
            })
            .some(function (state) {
              return state === 'running';
            });
          if (!isRunning) {
            return Promise.reject({
              message: 'app ' + newAppName + ' is not running'
            });
          }
          return true;
        });
    }

    function getAppName(domain, endpoint) {
      return cf('apps')
        .then(function (results) {
          var appPattern = new RegExp(endpoint + '.' + domain);
          return results
            .split('\n')
            .filter(function (line) {
              return line.match(appPattern);
            })
            .map(function (line) {
              return line.split(' ')[0];
            })[0];
        });
    }
    function setOldAppName() {
      return Promise.all([
        getAppName(foundry.domain, environment.endpoint),
        getAppName(environment.baseDomain, environment.baseName)
      ])
        .then(function (appNames) {
          oldAppName = appNames.filter(function (appName) {
            return appName;
          })[0];
        });
    }
    function mapNewAppAndUnmapOldApp(domain, endpoint) {
      var mapArgs = ['map-route', newAppName, domain],
        unmapArgs = ['unmap-route', oldAppName, domain];
      if (endpoint) {
        mapArgs.push('-n', endpoint);
        unmapArgs.push('-n', endpoint);
      }
      return cf.apply(foundry, mapArgs)
        .then(function () {
          if (!oldAppName) {
            return true;
          }
          return cf.apply(foundry, unmapArgs);
        });
    }
    function pushNewApp() {
      return logout()
        .then(setApi)
        .then(login)
        .then(pushApp)
        .then(setAppEnvironment)
        .then(startApp)
        .then(checkAppState)
        .catch(function (error) {
          console.error('error pushing app', location, error);
          return logApp().then(function () {
            return Promise.reject(error);
          });
        });
    }
    function deleteNewApp() {
      return deleteApp(newAppName);
    }
    function deleteOldApp() {
      if (!oldAppName) {
        return true;
      }
      return deleteApp(oldAppName);
    }
    function mapNewAppsAndUnmapOldApps() {
      var mappings = [
        mapNewAppAndUnmapOldApp(foundry.domain, environment.endpoint),
      ];
      if (environment.baseDomain === 'ctl.io') {
        // the ctl.io domain does not exist in AppFog
        mappings.push(
          mapNewAppAndUnmapOldApp(environment.baseName + '.' + environment.baseDomain));
      } else {
        mappings.push(mapNewAppAndUnmapOldApp(environment.baseDomain, environment.baseName));
      }
      mappings =
        mappings.concat(environment.custom_domains.map(mapNewAppAndUnmapOldApp));

      return Promise.all(mappings);
    }
    function remapNewAppAndDeleteOldApp() {
      return setOldAppName()
        .then(mapNewAppsAndUnmapOldApps)
        .then(deleteOldApp);
    }
    function bindServicesToApp() {
      return Promise.all(environment.services.map(bindServiceToApp));
    }
    foundry.pushNewApp = pushNewApp;
    foundry.deleteNewApp = deleteNewApp;
    foundry.bindServicesToApp = bindServicesToApp;
    foundry.remapNewAppAndDeleteOldApp = remapNewAppAndDeleteOldApp;
    return foundry;
  }

  function pushNewApp(location) {
    var foundry = newFoundry(location);
    return foundry.pushNewApp();
  }

  function deleteNewApp(location) {
    var foundry = newFoundry(location);
    return foundry.deleteNewApp();
  }

  function bindServicesToApp(location) {
    var foundry = newFoundry(location);
    return foundry.bindServicesToApp();
  }

  function remapNewAppAndDeleteOldApp(location) {
    var foundry = newFoundry(location);
    return foundry.remapNewAppAndDeleteOldApp();
  }

  function eachLocation(fn) {
    var environment = getEnvironment();
    return Promise.all(environment.locations.map(fn));
  }
  function pushNewApps() {
    return eachLocation(pushNewApp);
  }

  function bindServicesToApps() {
    return eachLocation(bindServicesToApp);
  }

  function remapNewAppsAndDeleteOldApps() {
    return eachLocation(remapNewAppAndDeleteOldApp);
  }

  function deleteApps() {
    return eachLocation(deleteNewApp);
  }

  function deployApps() {
    pushNewApps()
      .then(bindServicesToApps)
      .then(remapNewAppsAndDeleteOldApps)
      .catch(function () {
        deleteApps();
        console.error('deploy failed');
        process.exit(1);
      });
  }
  return {
    deployApps: deployApps
  };
}

exports.createDeployer = createDeployer;
<commit_msg>make sure deleteApps finishes before exiting<commit_after>'use strict';
var childProcess = require('child_process'),
  path = require('path');

function createDeployer(projectRoot, foundries, environments, environmentName,
                        timestamp) {
  timestamp = timestamp || Math.ceil(new Date().valueOf() / 1000);

  function getEnvironment() {
    return environments[environmentName];
  }

  function newFoundry(location) {
    var foundry = foundries[location],
      environment = getEnvironment(),
      newAppName = environment.newAppName,
      oldAppName,
      cfCmd = process.env.CF_CMD || path.resolve(__dirname, 'bin/cf');

    function cf() {
      var args = Array.prototype.slice.call(arguments, 0),
        displayOutput = true;

      if (args[0] === '--no-output') {
        displayOutput = false;
        args.shift();
      }
      return new Promise(function (resolve, reject) {
        /*jslint nomen: true */
        var results = '',
          stdio = [process.stdin, 'pipe', process.stderr],
          p;
        p = childProcess.spawn(cfCmd, args, {
          cwd: projectRoot,
          env: {
            CF_HOME: foundry.home,
            CF_COLOR: 'false'
          },
          stdio: stdio
        });
        p.stdout.on('data', function (data) {
          var str = data.toString();
          results += str;
          if (displayOutput) {
            process.stdout.write(data);
          }
        });
        p.on('close', function (code) {
          if (code === 0) {
            resolve(results);
          } else {
            reject({
              message: 'error "cf ' + args.join(' ') + '" ' +
                'failed with exit code ' + code
            });
          }
        });
      });
    }
    function setApi() {
      return cf('api', foundry.api);
    }
    function logout() {
      return cf('logout');
    }
    function login() {
      var space = foundry.spaces[environment.appEnv.NODE_ENV];
      return cf('login', '--u', foundry.username, '--p', foundry.password,
                '--o', foundry.org, '--s', space);
    }
    function logApp() {
      return cf('logs', newAppName, '--recent')
        .catch(function (error) {
          // Do not reject so that a failed app log doesn't cause
          // the rest of the script to fail.
          console.error('logApp', newAppName, 'failed', error);
        });
    }
    function pushApp() {
      return cf('push', newAppName,
                '-c', environment.startCommand,
                '-i', environment.instances,
                '-m', environment.memory,
                '-k', environment.disk,
                '-b', environment.buildPack,
                '--no-start');
    }
    function startApp() {
      return cf('start', newAppName);
    }
    function deleteApp(appName) {
      return cf('delete', '-f', '-r', appName)
        .catch(function (error) {
          // Do not reject so that a failed app deletion doesn't cause
          // the rest of the script to fail.
          console.error('deleteApp', appName, 'failed', error);
        });
    }
    function setAppEnvironment() {
      var settings = Object.keys(environment.appEnv).map(function (variable) {
        return function () {
          if (variable.match(/PASSWORD|KEY/)) {
            return cf('--no-output', 'set-env', newAppName, variable,
                      environment.appEnv[variable]);
          }
          return cf('set-env', newAppName, variable,
                    environment.appEnv[variable]);
        };
      });
      settings.push(function () {
        return cf('set-env', newAppName, "FOUNDRY_LOCATION", location);
      });
      return settings.reduce(function (cur, next) {
        return cur.then(next);
      }, Promise.resolve());
    }
    function bindServiceToApp(serviceName) {
      return cf('bind-service', newAppName, serviceName);
    }
    function checkAppState() {
      return cf('app', newAppName)
        .then(function (results) {
          var isRunning;
          isRunning = results
            .split('\n')
            .filter(function (line) {
              return line.substr(0, 1) === '#';
            })
            .map(function (line) {
              var fields = line.split(/ +/),
                state;
              if (fields[0].substr(0, 1) === '#') {
                state = fields[1];
              }
              return state;
            })
            .some(function (state) {
              return state === 'running';
            });
          if (!isRunning) {
            return Promise.reject({
              message: 'app ' + newAppName + ' is not running'
            });
          }
          return true;
        });
    }

    function getAppName(domain, endpoint) {
      return cf('apps')
        .then(function (results) {
          var appPattern = new RegExp(' ' + endpoint + '\\.' + domain);
          return results
            .split('\n')
            .filter(function (line) {
              return line.match(appPattern);
            })
            .map(function (line) {
              return line.split(' ')[0];
            })[0];
        });
    }
    function setOldAppName() {
      return Promise.all([
        getAppName(foundry.domain, environment.endpoint),
        getAppName(environment.baseDomain, environment.baseName)
      ])
        .then(function (appNames) {
          oldAppName = appNames.filter(function (appName) {
            return appName;
          })[0];
        });
    }
    function mapNewAppAndUnmapOldApp(domain, endpoint) {
      var mapArgs = ['map-route', newAppName, domain],
        unmapArgs = ['unmap-route', oldAppName, domain];
      if (endpoint) {
        mapArgs.push('-n', endpoint);
        unmapArgs.push('-n', endpoint);
      }
      return cf.apply(foundry, mapArgs)
        .then(function () {
          if (!oldAppName) {
            return true;
          }
          return cf.apply(foundry, unmapArgs);
        })
        .catch(function (error) {
          console.error('error mapping route:', error);
          return Promise.reject(error);
        });
    }
    function pushNewApp() {
      return logout()
        .then(setApi)
        .then(login)
        .then(pushApp)
        .then(setAppEnvironment)
        .then(startApp)
        .then(checkAppState)
        .catch(function (error) {
          console.error('error pushing app', location, error);
          return logApp().then(function () {
            return Promise.reject(error);
          });
        });
    }
    function deleteNewApp() {
      return deleteApp(newAppName);
    }
    function deleteOldApp() {
      if (!oldAppName) {
        return true;
      }
      return deleteApp(oldAppName);
    }
    function mapNewAppsAndUnmapOldApps() {
      var mappings = [
        mapNewAppAndUnmapOldApp(foundry.domain, environment.endpoint),
      ];
      if (environment.baseDomain === 'ctl.io') {
        // the ctl.io domain does not exist in AppFog
        mappings.push(
          mapNewAppAndUnmapOldApp(environment.baseName + '.' + environment.baseDomain));
      } else {
        mappings.push(mapNewAppAndUnmapOldApp(environment.baseDomain, environment.baseName));
      }
      mappings =
        mappings.concat(environment.custom_domains.map(mapNewAppAndUnmapOldApp));

      return Promise.all(mappings);
    }
    function remapNewAppAndDeleteOldApp() {
      return setOldAppName()
        .then(mapNewAppsAndUnmapOldApps)
        .then(deleteOldApp);
    }
    function bindServicesToApp() {
      return Promise.all(environment.services.map(bindServiceToApp));
    }
    foundry.pushNewApp = pushNewApp;
    foundry.deleteNewApp = deleteNewApp;
    foundry.bindServicesToApp = bindServicesToApp;
    foundry.remapNewAppAndDeleteOldApp = remapNewAppAndDeleteOldApp;
    return foundry;
  }

  function pushNewApp(location) {
    var foundry = newFoundry(location);
    return foundry.pushNewApp();
  }

  function deleteNewApp(location) {
    var foundry = newFoundry(location);
    return foundry.deleteNewApp();
  }

  function bindServicesToApp(location) {
    var foundry = newFoundry(location);
    return foundry.bindServicesToApp();
  }

  function remapNewAppAndDeleteOldApp(location) {
    var foundry = newFoundry(location);
    return foundry.remapNewAppAndDeleteOldApp();
  }

  function eachLocation(fn) {
    var environment = getEnvironment();
    return Promise.all(environment.locations.map(fn));
  }
  function pushNewApps() {
    return eachLocation(pushNewApp);
  }

  function bindServicesToApps() {
    return eachLocation(bindServicesToApp);
  }

  function remapNewAppsAndDeleteOldApps() {
    return eachLocation(remapNewAppAndDeleteOldApp);
  }

  function deleteApps() {
    return eachLocation(deleteNewApp);
  }

  function deployApps() {
    pushNewApps()
      .then(bindServicesToApps)
      .then(remapNewAppsAndDeleteOldApps)
      .catch(function () {
        deleteApps()
          .then(function () {
            console.error('deploy failed');
            process.exit(1);
          });
      });
  }
  return {
    deployApps: deployApps
  };
}

exports.createDeployer = createDeployer;
<|endoftext|>


<commit_before>// # pretty-select-value component

/*
   Render a select dropdown for a list of choices. Choices values can be of any
   type. Does not use native select dropdown. Choices can optionally include
   'sample' property displayed grayed out.
 */

'use strict';

var React = require('react/addons');
var _ = require('underscore');
var cx = require('classnames');

module.exports = React.createClass({

  displayName: 'SelectValue',

  mixins: [require('../../mixins/helper')],

  onChange: function (event) {
    var choiceValue = event.target.value;
    var choiceType = choiceValue.substring(0, choiceValue.indexOf(':'));
    if (choiceType === 'choice') {
      var choiceIndex = choiceValue.substring(choiceValue.indexOf(':') + 1);
      choiceIndex = parseInt(choiceIndex);
      this.props.onChange(this.props.choices[choiceIndex].value);
    }
  },

  getDefaultProps: function () {
    return {
      choices: []
    };
  },

  getInitialState: function() {
    var defaultValue = this.props.field.value !== undefined ? this.props.field.value : '';

    return {
      isChoicesOpen: this.props.isChoicesOpen,
      value: defaultValue,
      isEnteringCustomValue: false
    };
  },

  render: function () {
    return this.renderWithConfig();
  },

  renderDefault: function () {
    // var config = this.props.config;
    var choices = this.props.config.normalizePrettyChoices(this.props.choices);
    var choicesOrLoading;

    if ((choices.length > 1 && choices[0].value === '///loading///') || this.props.config.fieldIsLoading(this.props.field)) {
      choices = [{value: '///loading///'}];
    }
    var choicesElem = this.props.config.createElement('choices', {
      ref: 'choices',
      choices: choices,
      open: this.state.isChoicesOpen,
      ignoreCloseNodes: this.getCloseIgnoreNodes,
      onSelect: this.onSelectChoice,
      onClose: this.onCloseChoices,
      onChoiceAction: this.onChoiceAction,
      field: this.props.field
    });

    var inputElem = this.getInputElement();

    choicesOrLoading = (

          {inputElem}

        {choicesElem}

    );

    return choicesOrLoading;
  },

  getInputElement: function () {
    if (this.state.isEnteringCustomValue) {
      return <input ref="customInput" type="text" value={this.props.field.value}
                    onChange={this.onInputChange} onFocus={this.onFocusAction} onBlur={this.onBlur} />;
    }

    return <input type="text" value={this.getDisplayValue()} readOnly onFocus={this.onFocusAction} onBlur={this.onBlur} />;
  },

  onBlur: function () {
    if (!this.state.isChoicesOpen) {
      this.onBlurAction();
    }
  },

  getCloseIgnoreNodes: function () {
    return this.refs.toggle.getDOMNode();
  },

  onToggleChoices: function () {
    this.setChoicesOpen(!this.state.isChoicesOpen);
  },

  setChoicesOpen: function (isOpen) {
    var action = isOpen ? 'open-choices' : 'close-choices';
    this.onStartAction(action);
    this.setState({ isChoicesOpen: isOpen });
  },

  onSelectChoice: function (value) {
    this.setState({
      isChoicesOpen: false,
      value: value
    });
    this.props.onChange(value);
    this.onBlurAction();
  },

  onCloseChoices: function () {
    if (this.state.isChoicesOpen) {
      this.onBlurAction();
      this.setChoicesOpen(false);
    }
  },

  getDisplayValue: function () {
    var config = this.props.config;
    var currentValue = this.state.value;
    var currentChoice = this.props.config.fieldSelectedChoice(this.props.field);
    // Make sure selectedChoice is a match for current value.
    if (currentChoice && currentChoice.value !== currentValue) {
      currentChoice = null;
    }
    if (!currentChoice) {
      currentChoice = _.find(this.props.choices, function (choice) {
        return !choice.action && choice.value === currentValue;
      });
    }

    if (currentChoice) {
      return currentChoice.label;
    } else if (currentValue) { // custom value
      return currentValue;
    }
    return config.fieldPlaceholder(this.props.field) || '';
  },

  onChoiceAction: function (choice) {
    if (choice.action === 'enter-custom-value') {
      this.setState({
        isEnteringCustomValue: true,
        isChoicesOpen: false,
        value: choice.value
      }, function () {
        this.refs.customInput.getDOMNode().focus();
      });
    } else {
      this.setState({
        isChoicesOpen: false,
        value: choice.value
      });
    }

    this.onStartAction(choice.action, choice);
  },

  onAction: function (params) {
    if (params.action === 'enter-custom-value') {
      this.setState({isEnteringCustomValue: true}, function () {
        this.refs.customInput.getDOMNode().focus();
      });
    }
    this.onBubbleAction(params);
  },

  onInputChange: function (event) {
    this.props.onChange(event.target.value);
  }
});
<commit_msg>pretty-select do onBlur in timeout<commit_after>// # pretty-select-value component

/*
   Render a select dropdown for a list of choices. Choices values can be of any
   type. Does not use native select dropdown. Choices can optionally include
   'sample' property displayed grayed out.
 */

'use strict';

var React = require('react/addons');
var _ = require('underscore');
var cx = require('classnames');

module.exports = React.createClass({

  displayName: 'SelectValue',

  mixins: [require('../../mixins/helper')],

  onChange: function (event) {
    var choiceValue = event.target.value;
    var choiceType = choiceValue.substring(0, choiceValue.indexOf(':'));
    if (choiceType === 'choice') {
      var choiceIndex = choiceValue.substring(choiceValue.indexOf(':') + 1);
      choiceIndex = parseInt(choiceIndex);
      this.props.onChange(this.props.choices[choiceIndex].value);
    }
  },

  getDefaultProps: function () {
    return {
      choices: []
    };
  },

  getInitialState: function() {
    var defaultValue = this.props.field.value !== undefined ? this.props.field.value : '';

    return {
      isChoicesOpen: this.props.isChoicesOpen,
      value: defaultValue,
      isEnteringCustomValue: false
    };
  },

  render: function () {
    return this.renderWithConfig();
  },

  renderDefault: function () {
    // var config = this.props.config;
    var choices = this.props.config.normalizePrettyChoices(this.props.choices);
    var choicesOrLoading;

    if ((choices.length > 1 && choices[0].value === '///loading///') || this.props.config.fieldIsLoading(this.props.field)) {
      choices = [{value: '///loading///'}];
    }
    var choicesElem = this.props.config.createElement('choices', {
      ref: 'choices',
      choices: choices,
      open: this.state.isChoicesOpen,
      ignoreCloseNodes: this.getCloseIgnoreNodes,
      onSelect: this.onSelectChoice,
      onClose: this.onCloseChoices,
      onChoiceAction: this.onChoiceAction,
      field: this.props.field
    });

    var inputElem = this.getInputElement();

    choicesOrLoading = (

          {inputElem}

        {choicesElem}

    );

    return choicesOrLoading;
  },

  getInputElement: function () {
    if (this.state.isEnteringCustomValue) {
      return <input ref="customInput" type="text" value={this.props.field.value}
                    onChange={this.onInputChange} onFocus={this.onFocusAction} onBlur={this.onBlur} />;
    }

    return <input type="text" value={this.getDisplayValue()} readOnly onFocus={this.onFocusAction} onBlur={this.onBlur} />;
  },

  onBlur: function () {
    if (!this.state.isChoicesOpen) {
      setTimeout(function () {
        this.onBlurAction();
      }, 0);
    }
  },

  getCloseIgnoreNodes: function () {
    return this.refs.toggle.getDOMNode();
  },

  onToggleChoices: function () {
    this.setChoicesOpen(!this.state.isChoicesOpen);
  },

  setChoicesOpen: function (isOpen) {
    var action = isOpen ? 'open-choices' : 'close-choices';
    this.onStartAction(action);
    this.setState({ isChoicesOpen: isOpen });
  },

  onSelectChoice: function (value) {
    this.setState({
      isChoicesOpen: false,
      value: value
    });
    this.props.onChange(value);
    this.onBlurAction();
  },

  onCloseChoices: function () {
    if (this.state.isChoicesOpen) {
      this.onBlurAction();
      this.setChoicesOpen(false);
    }
  },

  getDisplayValue: function () {
    var config = this.props.config;
    var currentValue = this.state.value;
    var currentChoice = this.props.config.fieldSelectedChoice(this.props.field);
    // Make sure selectedChoice is a match for current value.
    if (currentChoice && currentChoice.value !== currentValue) {
      currentChoice = null;
    }
    if (!currentChoice) {
      currentChoice = _.find(this.props.choices, function (choice) {
        return !choice.action && choice.value === currentValue;
      });
    }

    if (currentChoice) {
      return currentChoice.label;
    } else if (currentValue) { // custom value
      return currentValue;
    }
    return config.fieldPlaceholder(this.props.field) || '';
  },

  onChoiceAction: function (choice) {
    if (choice.action === 'enter-custom-value') {
      this.setState({
        isEnteringCustomValue: true,
        isChoicesOpen: false,
        value: choice.value
      }, function () {
        this.refs.customInput.getDOMNode().focus();
      });
    } else {
      this.setState({
        isChoicesOpen: false,
        value: choice.value
      });
    }

    this.onStartAction(choice.action, choice);
  },

  onAction: function (params) {
    if (params.action === 'enter-custom-value') {
      this.setState({isEnteringCustomValue: true}, function () {
        this.refs.customInput.getDOMNode().focus();
      });
    }
    this.onBubbleAction(params);
  },

  onInputChange: function (event) {
    this.props.onChange(event.target.value);
  }
});
<|endoftext|>


<commit_before>require("./lib/chai-sorted");
<commit_msg>Fixed export issue in index.js<commit_after>module.exports = require("./lib/chai-sorted");
<|endoftext|>


<commit_before>/**
 * @typedef {String} key
 */
/**
 * @typedef {String} html
 */

/**
 * @typedef {Object} File
 * @property {String} file
 */
/**
 * @typedef {Object} URL
 * @property {String} url
 */
/**
 * @typedef {Object} HTML
 * @property {String} html
 */

/**
 * @callback renderCallback
 * @param {Error|null} err
 * @param {String} html
 */

/** @type {Nightmare} */
var Nightmare = require("nightmare");
var fs = require('fs');
var os = require('os');
var path = require("path");

/**
 * @typedef {function(html)} grabHtml
 * @lends Nightmare
 */
/**
 * @desc defines grabHtml
 */
Nightmare.action('grabHtml', function (done) {
    this.evaluate_now(function () {
        return "" + document.documentElement.innerHTML + "";
    }, done)
});

/**
 * @typedef {function(html)} inject
 * @lends Nightmare
 */
/**
 * @desc defines inject
 */
Nightmare.action('inject', function (html, done) {
    this.evaluate_now(function (html) {
        return document.documentElement.innerHTML = html;
    }, done, html)
});

var getTempFilePath = function() {
    return path.join((os.tmpdir || os.tmpDir)(), Math.random().toString().replace('.', '') + '.html');
};

/**
 * Rendered HTML
 * @param {URL|File|HTML} options
 * @param {Cache} [options.cache=null]
 * @param {Number} [options.width=1280]
 * @param {Number} [options.height=720]
 * @param {renderCallback} callback
 */
var serverRender = function serverRender (options, callback) {
    "use strict";

    if (options.cache) {
        options.cache.get(options.url || options.file || options.html, function (err, html) {
            if (err) return callback(err);

            if (!html) return coldRender();

            return callback(null, html);
        });
    } else {
        return coldRender();
    }

    function coldRender () {
        var nightmare = Nightmare({
            show: false,
            width: options.width || 1280,
            height: options.height || 720
        });

        if (options.url) {
            nightmare = nightmare.goto(options.url);
            return _doRender();
        }
        if (options.file) {
            nightmare = nightmare.goto("file://" + path.resolve(options.file));
            return _doRender();
        }

        if (options.html) {
            var tempPath = getTempFilePath();
            return fs.writeFile(tempPath, options.html, function(err) {
                if(err){
                  return callback(err);
                }

                nightmare = nightmare.goto("file://" + tempPath);
                setTimeout(function(){
                    fs.unlink(tempPath, function(){});
                }, 1000);
                return _doRender();
            });
        }

        nightmare.end();
        return callback(module.exports.Errors.noInput);

        function _doRender() {
          nightmare
            .wait("html")
            .grabHtml()
            .then(
              function(html) {
                if (options.cache) options.cache.set(options.url || options.file || options.html, html, new Function);

                return callback(null, html);
              },
              function(err) {
                if (!(err instanceof Error)) err = new Error(err);
                return callback(err);
              }
            );
          nightmare.end();
        }
    }
};

module.exports = serverRender;

module.exports.Errors = {};
module.exports.Errors.noInput = new Error("You haven't provided URL, file or HTML");<commit_msg>Update: rendering callback awaits cache set and may throw if cache errors on set<commit_after>/**
 * @typedef {String} key
 */
/**
 * @typedef {String} html
 */

/**
 * @typedef {Object} File
 * @property {String} file
 */
/**
 * @typedef {Object} URL
 * @property {String} url
 */
/**
 * @typedef {Object} HTML
 * @property {String} html
 */

/**
 * @callback renderCallback
 * @param {Error|null} err
 * @param {String} html
 */

/** @type {Nightmare} */
var Nightmare = require("nightmare");
var fs = require('fs');
var os = require('os');
var path = require("path");

/**
 * @typedef {function(html)} grabHtml
 * @lends Nightmare
 */
/**
 * @desc defines grabHtml
 */
Nightmare.action('grabHtml', function (done) {
    this.evaluate_now(function () {
        return "" + document.documentElement.innerHTML + "";
    }, done)
});

/**
 * @typedef {function(html)} inject
 * @lends Nightmare
 */
/**
 * @desc defines inject
 */
Nightmare.action('inject', function (html, done) {
    this.evaluate_now(function (html) {
        return document.documentElement.innerHTML = html;
    }, done, html)
});

var getTempFilePath = function() {
    return path.join((os.tmpdir || os.tmpDir)(), Math.random().toString().replace('.', '') + '.html');
};

/**
 * Rendered HTML
 * @param {URL|File|HTML} options
 * @param {Cache} [options.cache=null]
 * @param {Number} [options.width=1280]
 * @param {Number} [options.height=720]
 * @param {renderCallback} callback
 */
var serverRender = function serverRender (options, callback) {
    "use strict";

    if (options.cache) {
        options.cache.get(options.url || options.file || options.html, function (err, html) {
            if (err) return callback(err);

            if (!html) return coldRender();

            return callback(null, html);
        });
    } else {
        return coldRender();
    }

    function coldRender () {
        var nightmare = Nightmare({
            show: false,
            width: options.width || 1280,
            height: options.height || 720
        });

        if (options.url) {
            nightmare = nightmare.goto(options.url);
            return _doRender();
        }
        if (options.file) {
            nightmare = nightmare.goto("file://" + path.resolve(options.file));
            return _doRender();
        }

        if (options.html) {
            var tempPath = getTempFilePath();
            return fs.writeFile(tempPath, options.html, function(err) {
                if(err){
                  return callback(err);
                }

                nightmare = nightmare.goto("file://" + tempPath);
                setTimeout(function(){
                    fs.unlink(tempPath, function(){});
                }, 1000);
                return _doRender();
            });
        }

        nightmare.end();
        return callback(module.exports.Errors.noInput);

        function _doRender() {
          nightmare
            .wait("html")
            .grabHtml()
            .then(
              function(html) {
                if (options.cache) {
                  return options.cache.set(options.url || options.file || options.html, html, function(err){
                    return callback(err, html);
                  });
                }

                return callback(null, html);
              },
              function(err) {
                if (!(err instanceof Error)) err = new Error(err);
                return callback(err);
              }
            );
          nightmare.end();
        }
    }
};

module.exports = serverRender;

module.exports.Errors = {};
module.exports.Errors.noInput = new Error("You haven't provided URL, file or HTML");<|endoftext|>


<commit_before>import React from 'react';
import {
    AppRegistry,
    Text,
} from 'react-native';

export default class Index extends React.Component {
    render() {
        return (
            <Text>hi world</Text>
        );
    }
}
<commit_msg>common style update<commit_after>import React from 'react';
import {
    AppRegistry,
    View,
    StyleSheet,
    Text,
} from 'react-native';

export default class Index extends React.Component {
    render() {
        return (
            <View style={styles.container}>
                <Text>hello world</Text>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        alignItems: 'center',
        flex: 1,
    },
});
<|endoftext|>


<commit_before>var express = require('express'),
	exphbs = require('express-handlebars'),
    jf = require('jsonfile'),
    moment = require('moment'),
    request = require('request'),
    MongoClient = require('mongodb').MongoClient,
    passport = require('passport'),
    GitHubStrategy = require('passport-github').Strategy,
    session = require('express-session');
var GITHUB_CLIENT_ID = "false";
var GITHUB_CLIENT_SECRET = "false";
console.log("Connecting...");
MongoClient.connect(process.env.MONGOLAB_URI, function(err, db) {
    if(err) throw err;
    channels = db.collection('channels');
    console.log("Loading channels...");
    // Passport session setup.
    //   To support persistent login sessions, Passport needs to be able to
    //   serialize users into and deserialize users out of the session.  Typically,
    //   this will be as simple as storing the user ID when serializing, and finding
    //   the user by ID when deserializing.  However, since this example does not
    //   have a database of user records, the complete GitHub profile is serialized
    //   and deserialized.
    passport.serializeUser(function(user, done) {
        done(null, user);
    });

    passport.deserializeUser(function(obj, done) {
        done(null, obj);
    });

    // Use the GitHubStrategy within Passport.
    //   Strategies in Passport require a `verify` function, which accept
    //   credentials (in this case, an accessToken, refreshToken, and GitHub
    //   profile), and invoke a callback with a user object.
    passport.use(new GitHubStrategy({
            clientID: GITHUB_CLIENT_ID,
            clientSecret: GITHUB_CLIENT_SECRET,
            callbackURL: "https://falk-push.herokuapp.com/auth/github/callback"
        },
        function(accessToken, refreshToken, profile, done) {
            // asynchronous verification, for effect...
            process.nextTick(function () {

                // To keep the example simple, the user's GitHub profile is returned to
                // represent the logged-in user.  In a typical application, you would want
                // to associate the GitHub account with a user record in your database,
                // and return that user instead.
                return done(null, profile);
            });
        }
    ));
    var app = express();
    app.use(session({
        secret: 'keyboard cat'
    }));
    app.use(passport.initialize());
    app.use(passport.session());
    app.get('/auth/github',
        passport.authenticate('github'),
        function(req, res){
            // The request will be redirected to GitHub for authentication, so this
            // function will not be called.
        });

    // GET /auth/github/callback
    //   Use passport.authenticate() as route middleware to authenticate the
    //   request.  If authentication fails, the user will be redirected back to the
    //   login page.  Otherwise, the primary route function function will be called,
    //   which, in this example, will redirect the user to the home page.
    app.get('/auth/github/callback',
        passport.authenticate('github', { failureRedirect: '/login' }),
        function(req, res) {
            res.redirect('/');
    });
    app.engine('handlebars', exphbs({defaultLayout: 'main'}));
    app.set('view engine', 'handlebars');
    app.set('port', (process.env.PORT || 5000));

    app.get('/:user/:repo', function (request, response) {

    });
    app.get('/', function(request, response){
       response.render("home", { user: req.user });
    });
    app.get('/logout', function(req, res){
        req.logout();
        res.redirect('/');
    });
    app.listen(app.get('port'), function () {
        console.log("Node app is running at localhost:" + app.get('port'))
    });
});
<commit_msg>Fixed a little bug<commit_after>var express = require('express'),
	exphbs = require('express-handlebars'),
    jf = require('jsonfile'),
    moment = require('moment'),
    request = require('request'),
    MongoClient = require('mongodb').MongoClient,
    passport = require('passport'),
    GitHubStrategy = require('passport-github').Strategy,
    session = require('express-session');
var GITHUB_CLIENT_ID = "false";
var GITHUB_CLIENT_SECRET = "false";
console.log("Connecting...");
MongoClient.connect(process.env.MONGOLAB_URI, function(err, db) {
    if(err) throw err;
    channels = db.collection('channels');
    console.log("Loading channels...");
    // Passport session setup.
    //   To support persistent login sessions, Passport needs to be able to
    //   serialize users into and deserialize users out of the session.  Typically,
    //   this will be as simple as storing the user ID when serializing, and finding
    //   the user by ID when deserializing.  However, since this example does not
    //   have a database of user records, the complete GitHub profile is serialized
    //   and deserialized.
    passport.serializeUser(function(user, done) {
        done(null, user);
    });

    passport.deserializeUser(function(obj, done) {
        done(null, obj);
    });

    // Use the GitHubStrategy within Passport.
    //   Strategies in Passport require a `verify` function, which accept
    //   credentials (in this case, an accessToken, refreshToken, and GitHub
    //   profile), and invoke a callback with a user object.
    passport.use(new GitHubStrategy({
            clientID: GITHUB_CLIENT_ID,
            clientSecret: GITHUB_CLIENT_SECRET,
            callbackURL: "https://falk-push.herokuapp.com/auth/github/callback"
        },
        function(accessToken, refreshToken, profile, done) {
            // asynchronous verification, for effect...
            process.nextTick(function () {

                // To keep the example simple, the user's GitHub profile is returned to
                // represent the logged-in user.  In a typical application, you would want
                // to associate the GitHub account with a user record in your database,
                // and return that user instead.
                return done(null, profile);
            });
        }
    ));
    var app = express();
    app.use(session({
        secret: 'keyboard cat'
    }));
    app.use(passport.initialize());
    app.use(passport.session());
    app.get('/auth/github',
        passport.authenticate('github'),
        function(req, res){
            // The request will be redirected to GitHub for authentication, so this
            // function will not be called.
        });

    // GET /auth/github/callback
    //   Use passport.authenticate() as route middleware to authenticate the
    //   request.  If authentication fails, the user will be redirected back to the
    //   login page.  Otherwise, the primary route function function will be called,
    //   which, in this example, will redirect the user to the home page.
    app.get('/auth/github/callback',
        passport.authenticate('github', { failureRedirect: '/login' }),
        function(req, res) {
            res.redirect('/');
    });
    app.engine('handlebars', exphbs({defaultLayout: 'main'}));
    app.set('view engine', 'handlebars');
    app.set('port', (process.env.PORT || 5000));

    app.get('/:user/:repo', function (request, response) {

    });
    app.get('/', function(req, res){
       res.render("home", { user: req.user });
    });
    app.get('/logout', function(req, res){
        req.logout();
        res.redirect('/');
    });
    app.listen(app.get('port'), function () {
        console.log("Node app is running at localhost:" + app.get('port'))
    });
});
<|endoftext|>


<commit_before>const EMPTY_REGEX = /(?:)/
const NO_STYLE = { open: "", close: "", strip: EMPTY_REGEX }

const isColorSupported =
  process.env.FORCE_COLOR ||
  process.platform === "win32" ||
  (process.stdout.isTTY && process.env.TERM && process.env.TERM !== "dumb")

const Style = (open, close) =>
  isColorSupported
    ? {
        open: `\x1b[${open}m`,
        close: `\x1b[${close}m`,
        strip: new RegExp(`\\x1b\\[${close}m`, "g")
      }
    : NO_STYLE

const STYLES = {
  reset: Style(0, 0),
  bold: Style(1, 22),
  dim: Style(2, 22),
  italic: Style(3, 23),
  underline: Style(4, 24),
  inverse: Style(7, 27),
  hidden: Style(8, 28),
  strikethrough: Style(9, 29),

  black: Style(30, 39), // Dark
  red: Style(91, 39),
  green: Style(92, 39),
  yellow: Style(93, 39),
  blue: Style(94, 39),
  magenta: Style(95, 39),
  cyan: Style(96, 39),
  white: Style(97, 39),
  gray: Style(90, 39),

  bgBlack: Style(40, 49), // Dark
  bgRed: Style(101, 49),
  bgGreen: Style(102, 49),
  bgYellow: Style(103, 49),
  bgBlue: Style(104, 49),
  bgMagenta: Style(105, 49),
  bgCyan: Style(106, 49),
  bgWhite: Style(107, 49)
}

const color = function(s) {
  let i, style
  const styles = this.styles
  const length = styles.length

  for (i = 0, s = s + ""; i < length; i++) {
    style = STYLES[styles[i]]
    s = `${style.open}${s.replace(style.strip, style.open)}${style.close}`
  }

  return s
}

const defineProperty = Object.defineProperty

for (const style in STYLES) {
  defineProperty(color, style, {
    get() {
      if (this.styles === undefined) {
        const o = {}
        const f = color.bind(o)

        f.__proto__ = color
        f.styles = o.styles = [style]

        return f
      }

      this.styles.push(style)
      return this
    }
  })
}

module.exports = { color, STYLES }
<commit_msg>node.js 4 support<commit_after>"use strict"

const EMPTY_REGEX = /(?:)/
const NO_STYLE = { open: "", close: "", strip: EMPTY_REGEX }

const isColorSupported =
  process.env.FORCE_COLOR ||
  process.platform === "win32" ||
  (process.stdout.isTTY && process.env.TERM && process.env.TERM !== "dumb")

const Style = (open, close) =>
  isColorSupported
    ? {
        open: `\x1b[${open}m`,
        close: `\x1b[${close}m`,
        strip: new RegExp(`\\x1b\\[${close}m`, "g")
      }
    : NO_STYLE

const STYLES = {
  reset: Style(0, 0),
  bold: Style(1, 22),
  dim: Style(2, 22),
  italic: Style(3, 23),
  underline: Style(4, 24),
  inverse: Style(7, 27),
  hidden: Style(8, 28),
  strikethrough: Style(9, 29),

  black: Style(30, 39), // Dark
  red: Style(91, 39),
  green: Style(92, 39),
  yellow: Style(93, 39),
  blue: Style(94, 39),
  magenta: Style(95, 39),
  cyan: Style(96, 39),
  white: Style(97, 39),
  gray: Style(90, 39),

  bgBlack: Style(40, 49), // Dark
  bgRed: Style(101, 49),
  bgGreen: Style(102, 49),
  bgYellow: Style(103, 49),
  bgBlue: Style(104, 49),
  bgMagenta: Style(105, 49),
  bgCyan: Style(106, 49),
  bgWhite: Style(107, 49)
}

const color = function(s) {
  let i, style
  const styles = this.styles
  const length = styles.length

  for (i = 0, s = s + ""; i < length; i++) {
    style = STYLES[styles[i]]
    s = `${style.open}${s.replace(style.strip, style.open)}${style.close}`
  }

  return s
}

const defineProperty = Object.defineProperty

for (const style in STYLES) {
  defineProperty(color, style, {
    get() {
      if (this.styles === undefined) {
        const o = {}
        const f = color.bind(o)

        f.__proto__ = color
        f.styles = o.styles = [style]

        return f
      }

      this.styles.push(style)
      return this
    }
  })
}

module.exports = { color, STYLES }
<|endoftext|>


<commit_before>'use strict';
const JSONAPISerializer = require('jsonapi-serializer').Serializer;

function jsonapify(data, model, selfUrl) {
  return new JSONAPISerializer(model.name, data, {
    topLevelLinks: {
      self: selfUrl
    },
    attributes: Object.keys(model.attributes).filter(function(attribute) {
      return !model.attributes[attribute].primaryKey;
    })
  });
}

module.exports = function (options = {}) { // eslint-disable-line no-unused-vars
  return function (hook) {
    hook.result = jsonapify(hook.result.data, hook.service.Model, hook.path);
    return Promise.resolve(hook);
  };
};
<commit_msg>added support for GET method<commit_after>'use strict';
const JSONAPISerializer = require('jsonapi-serializer').Serializer;

function jsonapify(data, model, selfUrl) {
  const idAttribute = Object.keys(model.attributes).filter(function(attribute) {
    return model.attributes[attribute].primaryKey;
  })[0];

  const attributes = Object.keys(model.attributes).filter(function(attribute) { return attribute !== idAttribute; });

  const idParameter = !Array.isArray(data) ? ('/' + data[idAttribute]) : '';

  return new JSONAPISerializer(model.name, data, {
    topLevelLinks: {
      self: '/' + selfUrl + idParameter
    },
    attributes: attributes
  });
}

module.exports = function (options = {}) { // eslint-disable-line no-unused-vars
  return function (hook) {
    if (hook.method === 'find') {
      hook.result = jsonapify(hook.result.data, hook.service.Model, hook.path);
    } else if (hook.method === 'get') {
      hook.result = jsonapify(hook.result.toJSON(), hook.service.Model, hook.path);
    }
    return Promise.resolve(hook);
  };
};
<|endoftext|>


<commit_before>/**
 * Initialization
 */

var _       = require('lodash');
var fs      = require('fs');
var bp      = require('body-parser');
var cors    = require('cors');
var express = require('express');
var app     = express();
var forge   = require('node-forge');

var player    = null;
var inventory = null;
var releasing = null;

if (!fs.existsSync(__dirname + '/data/save/')) fs.mkdirSync(__dirname + '/data/save/');

if (!fs.existsSync(__dirname + '/.htt-mitm-proxy/certs/ca.crt')) {
  var cert = forge.pki.certificateFromPem(fs.readFile('.http-mitm-proxy/certs/ca.pem'));
  fs.writeFile('.http-mitm-proxy/certs/ca.crt', forge.asn1.toDer(forge.pki.certificateToAsn1(cert)).getBytes(), {encoding: 'binary'});
}

/**
 * Mitm
 */

var PokemonGoMITM = require('pokemon-go-mitm');

var Player    = require('./lib/player');
var Inventory = require('./lib/inventory');

var server = new PokemonGoMITM({port: 8081})
  .setResponseHandler('GetPlayer', function (data) {
    if (data.success && player === null) {
      player = new Player(data.player_data.username);
      player.load(data.player_data);
      player.save();
    }
  })
  .setResponseHandler('GetInventory', function (data) {
    if (data.success && player !== null) {
      var delta = data.inventory_delta;
      var pokemon = _.reduce(delta.inventory_items, function (result, item) {
        return (item.inventory_item_data !== undefined &&
                item.inventory_item_data.pokemon_data !== undefined &&
               !item.inventory_item_data.pokemon_data.is_egg) ? _.concat(result, item.inventory_item_data.pokemon_data) : result;
      }, []);
      var candy = _.reduce(delta.inventory_items, function (result, item) {
        return (item.inventory_item_data !== undefined &&
                item.inventory_item_data.pokemon_family !== undefined) ? _.concat(result, item.inventory_item_data.pokemon_family) : result;
      }, []);
      if (inventory === null) {
        inventory = new Inventory(player.username);
        inventory.load(candy, pokemon);
        inventory.save();
      } else {
        inventory.update(candy, pokemon);
        inventory.save();
      }
    } else if (player === null) {
      console.error("WARNING: Cannot set inventory. No player logged in.");
    } else if (!data.inventory_delta) {
      console.log(data);
    }
  })
  .setRequestHandler("ReleasePokemon", function (data) {
    releasing = data.pokemon_id;
  })
  .setResponseHandler("ReleasePokemon", function(data) {
    if (data.result === 'SUCCESS' && releasing !== null) {
      inventory.release(releasing);
      inventory.save();
      releasing = null;
    }
  })
  .setRequestHandler("EvolvePokemon", function (data) {
    releasing = data.pokemon_id;
  })
  .setResponseHandler("EvolvePokemon", function(data) {
    if (data.result === 'SUCCESS' && releasing !== null) {
      inventory.release(releasing);
      inventory.save();
      releasing = null;
    }
  });

/**
 * Express
 */

app.use(bp.json());
app.use(cors());

app.use(express.static('public'));
app.use("/ca.pem", express.static('.http-mitm-proxy/certs/ca.pem'));
app.use("/ca.crt", express.static('.http-mitm-proxy/certs/ca.crt'));

app.get('/api/player', function (req, res, next) {
  if (player) return res.send(player.toJSON());
  else return res.json(null);
});

app.post('/api/player/settings', function (req, res, next) {
  if (player) {
    player.settings = req.body;
    player.save();
  }
  return res.send();
});

app.get('/api/inventory', function (req, res, next) {
  if (inventory) {
    res.send(inventory.toJSON());
    inventory.updates = false;
  }
  else return res.json(null);
});

app.post('/api/logout', function (req, res, next) {
  player    = null;
  inventory = null;
  releasing = null;
  res.send();
});

app.listen(3000, function () {
  console.log('Pokemon GO Optimizer front-end listening on port 3000');

  require('dns').lookup(require('os').hostname(), function (err, add, fam) {
    console.log('Accept the cert at ' + add + ':3000/ca.pem if you haven\'t already done so');
  });
});
<commit_msg>.pem needed to be read synchronously<commit_after>/**
 * Initialization
 */

var _       = require('lodash');
var fs      = require('fs');
var bp      = require('body-parser');
var cors    = require('cors');
var express = require('express');
var app     = express();
var forge   = require('node-forge');

var player    = null;
var inventory = null;
var releasing = null;

if (!fs.existsSync(__dirname + '/data/save/')) fs.mkdirSync(__dirname + '/data/save/');

if (!fs.existsSync(__dirname + '/.htt-mitm-proxy/certs/ca.crt')) {
  var cert = forge.pki.certificateFromPem(fs.readFileSync('.http-mitm-proxy/certs/ca.pem'));
  fs.writeFile('.http-mitm-proxy/certs/ca.crt', forge.asn1.toDer(forge.pki.certificateToAsn1(cert)).getBytes(), {encoding: 'binary'});
}

/**
 * Mitm
 */

var PokemonGoMITM = require('pokemon-go-mitm');

var Player    = require('./lib/player');
var Inventory = require('./lib/inventory');

var server = new PokemonGoMITM({port: 8081})
  .setResponseHandler('GetPlayer', function (data) {
    if (data.success && player === null) {
      player = new Player(data.player_data.username);
      player.load(data.player_data);
      player.save();
    }
  })
  .setResponseHandler('GetInventory', function (data) {
    if (data.success && player !== null) {
      var delta = data.inventory_delta;
      var pokemon = _.reduce(delta.inventory_items, function (result, item) {
        return (item.inventory_item_data !== undefined &&
                item.inventory_item_data.pokemon_data !== undefined &&
               !item.inventory_item_data.pokemon_data.is_egg) ? _.concat(result, item.inventory_item_data.pokemon_data) : result;
      }, []);
      var candy = _.reduce(delta.inventory_items, function (result, item) {
        return (item.inventory_item_data !== undefined &&
                item.inventory_item_data.pokemon_family !== undefined) ? _.concat(result, item.inventory_item_data.pokemon_family) : result;
      }, []);
      if (inventory === null) {
        inventory = new Inventory(player.username);
        inventory.load(candy, pokemon);
        inventory.save();
      } else {
        inventory.update(candy, pokemon);
        inventory.save();
      }
    } else if (player === null) {
      console.error("WARNING: Cannot set inventory. No player logged in.");
    } else if (!data.inventory_delta) {
      console.log(data);
    }
  })
  .setRequestHandler("ReleasePokemon", function (data) {
    releasing = data.pokemon_id;
  })
  .setResponseHandler("ReleasePokemon", function(data) {
    if (data.result === 'SUCCESS' && releasing !== null) {
      inventory.release(releasing);
      inventory.save();
      releasing = null;
    }
  })
  .setRequestHandler("EvolvePokemon", function (data) {
    releasing = data.pokemon_id;
  })
  .setResponseHandler("EvolvePokemon", function(data) {
    if (data.result === 'SUCCESS' && releasing !== null) {
      inventory.release(releasing);
      inventory.save();
      releasing = null;
    }
  });

/**
 * Express
 */

app.use(bp.json());
app.use(cors());

app.use(express.static('public'));
app.use("/ca.pem", express.static('.http-mitm-proxy/certs/ca.pem'));
app.use("/ca.crt", express.static('.http-mitm-proxy/certs/ca.crt'));

app.get('/api/player', function (req, res, next) {
  if (player) return res.send(player.toJSON());
  else return res.json(null);
});

app.post('/api/player/settings', function (req, res, next) {
  if (player) {
    player.settings = req.body;
    player.save();
  }
  return res.send();
});

app.get('/api/inventory', function (req, res, next) {
  if (inventory) {
    res.send(inventory.toJSON());
    inventory.updates = false;
  }
  else return res.json(null);
});

app.post('/api/logout', function (req, res, next) {
  player    = null;
  inventory = null;
  releasing = null;
  res.send();
});

app.listen(3000, function () {
  console.log('Pokemon GO Optimizer front-end listening on port 3000');

  require('dns').lookup(require('os').hostname(), function (err, add, fam) {
    console.log('Accept the cert at ' + add + ':3000/ca.pem if you haven\'t already done so');
  });
});
<|endoftext|>


<commit_before>var arDrone = require('ar-drone')
var fs = require('fs')
var net = require('net')
var optimist = require('optimist')
var PaVEParser = require('./node_modules/ar-drone/lib/video/PaVEParser')
var split = require('split')
var through = require('through')

// Don't crash node on exceptions
process.on('uncaughtException', function (err) {
  console.error(err.stack)
  try {
    land()
  } catch (e) {}
  setTimeout(function () {
    process.exit(0)
  }, 200)
})

var argv = optimist
  .usage('Usage: $0 [--oculus]')
  .alias('oculus', 'o')
  .argv

var drone = arDrone.createClient()
var state = { x: 0, y: 0, z: 0, rot: 0 }
var inAir = false
var gestureEnabled = true

drone.disableEmergency()
drone.stop() // Stop command drone was executing before batt died

drone.on('batteryChange', function (num) {
  console.log('battery: ' + num)
})

setInterval(function () {
  console.log(state)
}, 1000)

function set (params) {
  for (var param in params) {
    var val = params[param]

    // Update parameter
    if (val > 1) {
      state[param] = 1
    } else if (val < -1) {
      state[param] = -1
    } else {
      state[param] = val
    }

    // Send movement command to drone
    if (param === 'x') {
      drone.front(val)
    } else if (param === 'y') {
      drone.right(val)
    } else if (param === 'z') {
      drone.up(val)
    } else if (param === 'rot') {
      drone.clockwise(val)
    } else {
      console.error('Invalid param to `set`')
    }
  }
}

function reset () {
  set({x: 0, y: 0, z: 0, rot: 0})
  drone.stop()
}

function takeoff () {
  drone.disableEmergency()
  drone.stop()
  drone.takeoff()
  inAir = true
}

function land () {
  inAir = false
  drone.land()
}

function flipAhead () {
  drone.animate('flipAhead', 500)
}
function flipBehind () {
  drone.animate('flipBehind', 500)
}
function flipLeft () {
  drone.animate('flipLeft', 500)
}
function flipRight () {
  drone.animate('flipRight', 500)
}

function disableGestureTimeout () {
  gestureEnabled = false
  setTimeout(function () {
    gestureEnabled = true
  }, 2000)
}

// Keyboard control
process.stdin.setRawMode(true)
process.stdin.on('data', function(chunk) {
  var key = chunk.toString()
  var keyBuf = chunk.toJSON()
  var speed = 0.2

  console.log(key)
  console.log(keyBuf)

  if (Array.isArray(keyBuf)) {
    var UP = (keyBuf[0] === 27 && keyBuf[1] === 91 && keyBuf[2] === 65)
    var DOWN = (keyBuf[0] === 27 && keyBuf[1] === 91 && keyBuf[2] === 66)
    var RIGHT = (keyBuf[0] === 27 && keyBuf[1] === 91 && keyBuf[2] === 67)
    var LEFT = (keyBuf[0] === 27 && keyBuf[1] === 91 && keyBuf[2] === 68)
  }

  if (key === 'k') {
    land()
    setTimeout(function () {
      process.exit(0)
    }, 200)

  if (key === 'w') {
    set({ x: speed })
  } else if (key === 's') {
    set({ x: -speed })
  } else if (key === 'd') {
    set({ y: speed })
  } else if (key === 'a') {
    set({ y: -speed })
  } else if (UP) {
    set({ z: speed })
  } else if (DOWN) {
    set({ z: -speed })
  } else if (LEFT) {
    set({ rot: -speed }) // COUNTERCLOCKWISE
  } else if (RIGHT) {
    set({ rot: speed }) // CLOCKWISE
  } else if (key === 'e') {
    drone.stop()
  } else if (key === 't') {
    takeoff()
  } else if (key === 'l') {
    land()

  } else if (keyBuf[0] === 32) {
    flipAhead()
  }
})

if (argv.oculus) {
  // Connect to oculus server
  var oculusClient = net.connect({ port: 12345 })
  oculusClient.on('error', function (err) {
    console.error('Error connecting to oculus server.')
  })

  oculusClient
    .pipe(split())
    .pipe(through(function (line) {
      var arr = line.split(',')
      var x = Number(-arr[0]), rot = Number(-arr[1]), y = Number(-arr[2])
      set({ x: x, y: y, rot: rot })

      // Gestures:
      //   DOWN to takeoff/land
      //   UP to flip
      if (gestureEnabled) {
        if (x < -1) {
          flipBehind()
          disableGestureTimeout()
        } else if (x > 1) {
          if (inAir) {
            land()
          } else {
            takeoff()
          }
          disableGestureTimeout()
        }
      }
    }))
}

// Video server
net.createServer(function (c) {
  console.log('server connected')

  c.on('end', function() {
    console.log('server disconnected')
  })

  drone.getVideoStream()
    .pipe(new PaVEParser())
    .pipe(through(function (data) {
      this.queue(data.payload)
      console.log('video bits sent')
    }))
    .pipe(c)

}).listen(6969)

// drone.on('navdata', function (data) {
//   console.log(data)
// })

<commit_msg>consistent naming: x,y,z,e<commit_after>var arDrone = require('ar-drone')
var fs = require('fs')
var net = require('net')
var optimist = require('optimist')
var PaVEParser = require('./node_modules/ar-drone/lib/video/PaVEParser')
var split = require('split')
var through = require('through')

// Don't crash node on exceptions
process.on('uncaughtException', function (err) {
  console.error(err.stack)
  try {
    land()
  } catch (e) {}
  setTimeout(function () {
    process.exit(0)
  }, 200)
})

var argv = optimist
  .usage('Usage: $0 [--oculus]')
  .alias('oculus', 'o')
  .argv

var drone = arDrone.createClient()
var speed = {
  x: 0, // forward/back
  y: 0, // left/right
  z: 0, // rotateLeft/rotateRight
  e: 0  // up/down
}
var inAir = false
var gestureEnabled = true

drone.disableEmergency()
drone.stop() // Stop command drone was executing before batt died

drone.on('batteryChange', function (num) {
  console.log('battery: ' + num)
})

setInterval(function () {
  console.log(speed)
}, 1000)

function set (params) {
  for (var param in params) {
    var val = params[param]

    // Update parameter
    if (val > 1) {
      speed[param] = 1
    } else if (val < -1) {
      speed[param] = -1
    } else {
      speed[param] = val
    }

    // Send movement command to drone
    if (param === 'x') {
      drone.front(val)
    } else if (param === 'y') {
      drone.right(val)
    } else if (param === 'e') {
      drone.up(val)
    } else if (param === 'z') {
      drone.clockwise(val)
    } else {
      console.error('Invalid param to `set`')
    }
  }
}

function reset () {
  set({x: 0, y: 0, z: 0, e: 0})
  drone.stop()
}

function takeoff () {
  drone.disableEmergency()
  drone.stop()
  drone.takeoff()
  inAir = true
}

function land () {
  inAir = false
  drone.land()
}

function flipAhead () {
  drone.animate('flipAhead', 500)
}
function flipBehind () {
  drone.animate('flipBehind', 500)
}
function flipLeft () {
  drone.animate('flipLeft', 500)
}
function flipRight () {
  drone.animate('flipRight', 500)
}

function disableGestureTimeout () {
  gestureEnabled = false
  setTimeout(function () {
    gestureEnabled = true
  }, 2000)
}

// Keyboard control
process.stdin.setRawMode(true)
process.stdin.on('data', function(chunk) {
  var key = chunk.toString()
  var keyBuf = chunk.toJSON()
  var speed = 0.2

  console.log(key)
  console.log(keyBuf)

  if (Array.isArray(keyBuf)) {
    var UP = (keyBuf[0] === 27 && keyBuf[1] === 91 && keyBuf[2] === 65)
    var DOWN = (keyBuf[0] === 27 && keyBuf[1] === 91 && keyBuf[2] === 66)
    var RIGHT = (keyBuf[0] === 27 && keyBuf[1] === 91 && keyBuf[2] === 67)
    var LEFT = (keyBuf[0] === 27 && keyBuf[1] === 91 && keyBuf[2] === 68)
  }

  if (key === 'w') {
    set({ x: speed })
  } else if (key === 's') {
    set({ x: -speed })
  } else if (key === 'd') {
    set({ y: speed })
  } else if (key === 'a') {
    set({ y: -speed })
  } else if (UP) {
    set({ e: speed })
  } else if (DOWN) {
    set({ e: -speed })
  } else if (LEFT) {
    set({ z: -speed }) // COUNTERCLOCKWISE
  } else if (RIGHT) {
    set({ z: speed }) // CLOCKWISE
  } else if (key === 'e') {
    drone.stop()
  } else if (key === 'k') {
    land()
    setTimeout(function () {
      process.exit(0)
    }, 200)
  } else if (key === 't') {
    takeoff()
  } else if (key === 'l') {
    land()

  } else if (keyBuf[0] === 32) {
    flipAhead()
  }
})

if (argv.oculus) {
  // Connect to oculus server
  var oculusClient = net.connect({ port: 12345 })
  oculusClient.on('error', function (err) {
    console.error('Error connecting to oculus server.')
  })

  oculusClient
    .pipe(split())
    .pipe(through(function (line) {
      var arr = line.split(',')
      var x = Number(-arr[0]), z = Number(-arr[1]), y = Number(-arr[2])
      set({ x: x, y: y, z: z })

      // Gestures:
      //   DOWN to takeoff/land
      //   UP to flip
      if (gestureEnabled) {
        if (x < -1) {
          flipBehind()
          disableGestureTimeout()
        } else if (x > 1) {
          if (inAir) {
            land()
          } else {
            takeoff()
          }
          disableGestureTimeout()
        }
      }
    }))
}

// Video server
net.createServer(function (c) {
  console.log('server connected')

  c.on('end', function() {
    console.log('server disconnected')
  })

  drone.getVideoStream()
    .pipe(new PaVEParser())
    .pipe(through(function (data) {
      this.queue(data.payload)
      console.log('video bits sent')
    }))
    .pipe(c)

}).listen(6969)

drone.on('navdata', function (data) {
  console.log(data)
})<|endoftext|>


<commit_before>var one = 'ccab cdae\'f';
var two = 'fabecadcc';

var isAnagram = function(first, second) {
  // remove all non alphanumeric characters
  // like spaces and aphostrophes
  first = first.replace(/[^azA-Z0-9]/gi, "");
  second = second.replace(/[^azA-Z0-9]/gi, "");

  var firstMap = {};
  var secondMap = {};

  var createMap = function(char) {
      if (!this[char]) {
          this[char] = 0;
      }
      this[char]++;
  }

  first.split('').forEach(createMap.bind(firstMap));
  second.split('').forEach(createMap.bind(secondMap));
  return Object.equals(firstMap, secondMap);
}
<commit_msg>[ANAGRAMS] - :finnadie: second level indentation change<commit_after>var one = 'ccab cdae\'f';
var two = 'fabecadcc';

var isAnagram = function(first, second) {
  // remove all non alphanumeric characters
  // like spaces and aphostrophes
  first = first.replace(/[^azA-Z0-9]/gi, "");
  second = second.replace(/[^azA-Z0-9]/gi, "");

  var firstMap = {};
  var secondMap = {};

  var createMap = function(char) {
    if (!this[char]) {
        this[char] = 0;
    }
    this[char]++;
  }

  first.split('').forEach(createMap.bind(firstMap));
  second.split('').forEach(createMap.bind(secondMap));
  return Object.equals(firstMap, secondMap);
}
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var uid2 = require('uid2');
var redis = require('redis').createClient;
var msgpack = require('msgpack-js');
var Adapter = require('socket.io-adapter');
var Emitter = require('events').EventEmitter;
var debug = require('debug')('socket.io-redis');
var async = require('async');

/**
 * Module exports.
 */

module.exports = adapter;

/**
 * Returns a redis Adapter class.
 *
 * @param {String} optional, redis uri
 * @return {RedisAdapter} adapter
 * @api public
 */

function adapter(uri, opts){
  opts = opts || {};

  // handle options only
  if ('object' == typeof uri) {
    opts = uri;
    uri = null;
  }

  // opts
  var pub = opts.pubClient;
  var sub = opts.subClient;
  var prefix = opts.key || 'socket.io';

  // init clients if needed
  function createClient(redis_opts) {
    if (uri) {
      // handle uri string
      return redis(uri, redis_opts);
    } else {
      var port = Number(opts.port || 6379);
      var host = opts.host || '127.0.0.1';
      return redis(port, host, redis_opts);
    }
  }

  if (!pub) pub = createClient();
  if (!sub) sub = createClient({ return_buffers: true });

  // this server's key
  var uid = uid2(6);

  /**
   * Adapter constructor.
   *
   * @param {String} namespace name
   * @api public
   */

  function Redis(nsp){
    Adapter.call(this, nsp);

    this.uid = uid;
    this.prefix = prefix;
    this.pubClient = pub;
    this.subClient = sub;

    var self = this;
    sub.subscribe(prefix + '#' + nsp.name + '#', function(err){
      if (err) self.emit('error', err);
    });
    sub.on('message', this.onmessage.bind(this));
  }

  /**
   * Inherits from `Adapter`.
   */

  Redis.prototype.__proto__ = Adapter.prototype;

  /**
   * Called with a subscription message
   *
   * @api private
   */

  Redis.prototype.onmessage = function(channel, msg){
    var args = msgpack.decode(msg);
    var packet;

    if (uid == args.shift()) return debug('ignore same uid');

    packet = args[0];

    if (packet && packet.nsp === undefined) {
      packet.nsp = '/';
    }

    if (!packet || packet.nsp != this.nsp.name) {
      return debug('ignore different namespace');
    }

    args.push(true);

    this.broadcast.apply(this, args);
  };

  /**
   * Broadcasts a packet.
   *
   * @param {Object} packet to emit
   * @param {Object} options
   * @param {Boolean} whether the packet came from another node
   * @api public
   */

  Redis.prototype.broadcast = function(packet, opts, remote){
    Adapter.prototype.broadcast.call(this, packet, opts);
    if (!remote) {
      var chn = prefix + '#' + packet.nsp + '#';
      var msg = msgpack.encode([uid, packet, opts]);
      if (opts.rooms) {
        opts.rooms.forEach(function(room) {
          var chnRoom = chn + room + '#';
          pub.publish(chnRoom, msg);
        });
      } else {
        pub.publish(chn, msg);
      }
    }
  };

  /**
   * Subscribe client to room messages.
   *
   * @param {String} client id
   * @param {String} room
   * @param {Function} callback (optional)
   * @api public
   */

  Redis.prototype.add = function(id, room, fn){
    debug('adding %s to %s ', id, room);
    var self = this;
    Adapter.prototype.add.call(this, id, room);
    var channel = prefix + '#' + this.nsp.name + '#' + room + '#';
    sub.subscribe(channel, function(err){
      if (err) {
        self.emit('error', err);
        if (fn) fn(err);
        return;
      }
      if (fn) fn(null);
    });
  };

  /**
   * Unsubscribe client from room messages.
   *
   * @param {String} session id
   * @param {String} room id
   * @param {Function} callback (optional)
   * @api public
   */

  Redis.prototype.del = function(id, room, fn){
    debug('removing %s from %s', id, room);

    var self = this;
    var hasRoom = this.rooms.hasOwnProperty(room);
    Adapter.prototype.del.call(this, id, room);

    if (hasRoom && !this.rooms[room]) {
      var channel = prefix + '#' + this.nsp.name + '#' + room + '#';
      sub.unsubscribe(channel, function(err){
        if (err) {
          self.emit('error', err);
          if (fn) fn(err);
          return;
        }
        if (fn) fn(null);
      });
    } else {
      if (fn) process.nextTick(fn.bind(null, null));
    }
  };

  /**
   * Unsubscribe client completely.
   *
   * @param {String} client id
   * @param {Function} callback (optional)
   * @api public
   */

  Redis.prototype.delAll = function(id, fn){
    debug('removing %s from all rooms', id);

    var self = this;
    var rooms = this.sids[id];

    if (!rooms) {
      if (fn) process.nextTick(fn.bind(null, null));
      return;
    }

    async.forEach(Object.keys(rooms), function(room, next){
      self.del(id, room, next);
    }, function(err){
      if (err) {
        self.emit('error', err);
        if (fn) fn(err);
        return;
      }
      delete self.sids[id];
      if (fn) fn(null);
    });
  };

  Redis.uid = uid;
  Redis.pubClient = pub;
  Redis.subClient = sub;
  Redis.prefix = prefix;

  return Redis;

}
<commit_msg>Delegate to node_redis to choose default host/port.<commit_after>
/**
 * Module dependencies.
 */

var uid2 = require('uid2');
var redis = require('redis').createClient;
var msgpack = require('msgpack-js');
var Adapter = require('socket.io-adapter');
var Emitter = require('events').EventEmitter;
var debug = require('debug')('socket.io-redis');
var async = require('async');

/**
 * Module exports.
 */

module.exports = adapter;

/**
 * Returns a redis Adapter class.
 *
 * @param {String} optional, redis uri
 * @return {RedisAdapter} adapter
 * @api public
 */

function adapter(uri, opts){
  opts = opts || {};

  // handle options only
  if ('object' == typeof uri) {
    opts = uri;
    uri = null;
  }

  // opts
  var pub = opts.pubClient;
  var sub = opts.subClient;
  var prefix = opts.key || 'socket.io';

  // init clients if needed
  function createClient(redis_opts) {
    if (uri) {
      // handle uri string
      return redis(uri, redis_opts);
    } else {
      return redis(opts.port, opts.host, redis_opts);
    }
  }

  if (!pub) pub = createClient();
  if (!sub) sub = createClient({ return_buffers: true });

  // this server's key
  var uid = uid2(6);

  /**
   * Adapter constructor.
   *
   * @param {String} namespace name
   * @api public
   */

  function Redis(nsp){
    Adapter.call(this, nsp);

    this.uid = uid;
    this.prefix = prefix;
    this.pubClient = pub;
    this.subClient = sub;

    var self = this;
    sub.subscribe(prefix + '#' + nsp.name + '#', function(err){
      if (err) self.emit('error', err);
    });
    sub.on('message', this.onmessage.bind(this));
  }

  /**
   * Inherits from `Adapter`.
   */

  Redis.prototype.__proto__ = Adapter.prototype;

  /**
   * Called with a subscription message
   *
   * @api private
   */

  Redis.prototype.onmessage = function(channel, msg){
    var args = msgpack.decode(msg);
    var packet;

    if (uid == args.shift()) return debug('ignore same uid');

    packet = args[0];

    if (packet && packet.nsp === undefined) {
      packet.nsp = '/';
    }

    if (!packet || packet.nsp != this.nsp.name) {
      return debug('ignore different namespace');
    }

    args.push(true);

    this.broadcast.apply(this, args);
  };

  /**
   * Broadcasts a packet.
   *
   * @param {Object} packet to emit
   * @param {Object} options
   * @param {Boolean} whether the packet came from another node
   * @api public
   */

  Redis.prototype.broadcast = function(packet, opts, remote){
    Adapter.prototype.broadcast.call(this, packet, opts);
    if (!remote) {
      var chn = prefix + '#' + packet.nsp + '#';
      var msg = msgpack.encode([uid, packet, opts]);
      if (opts.rooms) {
        opts.rooms.forEach(function(room) {
          var chnRoom = chn + room + '#';
          pub.publish(chnRoom, msg);
        });
      } else {
        pub.publish(chn, msg);
      }
    }
  };

  /**
   * Subscribe client to room messages.
   *
   * @param {String} client id
   * @param {String} room
   * @param {Function} callback (optional)
   * @api public
   */

  Redis.prototype.add = function(id, room, fn){
    debug('adding %s to %s ', id, room);
    var self = this;
    Adapter.prototype.add.call(this, id, room);
    var channel = prefix + '#' + this.nsp.name + '#' + room + '#';
    sub.subscribe(channel, function(err){
      if (err) {
        self.emit('error', err);
        if (fn) fn(err);
        return;
      }
      if (fn) fn(null);
    });
  };

  /**
   * Unsubscribe client from room messages.
   *
   * @param {String} session id
   * @param {String} room id
   * @param {Function} callback (optional)
   * @api public
   */

  Redis.prototype.del = function(id, room, fn){
    debug('removing %s from %s', id, room);

    var self = this;
    var hasRoom = this.rooms.hasOwnProperty(room);
    Adapter.prototype.del.call(this, id, room);

    if (hasRoom && !this.rooms[room]) {
      var channel = prefix + '#' + this.nsp.name + '#' + room + '#';
      sub.unsubscribe(channel, function(err){
        if (err) {
          self.emit('error', err);
          if (fn) fn(err);
          return;
        }
        if (fn) fn(null);
      });
    } else {
      if (fn) process.nextTick(fn.bind(null, null));
    }
  };

  /**
   * Unsubscribe client completely.
   *
   * @param {String} client id
   * @param {Function} callback (optional)
   * @api public
   */

  Redis.prototype.delAll = function(id, fn){
    debug('removing %s from all rooms', id);

    var self = this;
    var rooms = this.sids[id];

    if (!rooms) {
      if (fn) process.nextTick(fn.bind(null, null));
      return;
    }

    async.forEach(Object.keys(rooms), function(room, next){
      self.del(id, room, next);
    }, function(err){
      if (err) {
        self.emit('error', err);
        if (fn) fn(err);
        return;
      }
      delete self.sids[id];
      if (fn) fn(null);
    });
  };

  Redis.uid = uid;
  Redis.pubClient = pub;
  Redis.subClient = sub;
  Redis.prefix = prefix;

  return Redis;

}
<|endoftext|>


<commit_before>'use strict';

var runner = require('./runner');
var PGA = require('./leagues/pga');
var NHL = require('./leagues/nhl');
var MLB = require('./leagues/mlb');

module.exports = {
  pga: function(event, context) {
    var league = runner(PGA);
    league.web(context.done);
  },
  nhl: function(event, context) {
    var league = runner(NHL);
    league.web(context.done);
  }
};
<commit_msg>add MLB as handler<commit_after>'use strict';

var runner = require('./runner');
var PGA = require('./leagues/pga');
var NHL = require('./leagues/nhl');
var MLB = require('./leagues/mlb');

module.exports = {
  pga: function(event, context) {
    var league = runner(PGA);
    league.web(context.done);
  },
  nhl: function(event, context) {
    var league = runner(NHL);
    league.web(context.done);
  },
  mlb: function(event, context) {
    var league = runner(MLB);
    league.web(context.done);
  }
};
<|endoftext|>