<commit_before>/**
 * Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"). You
 * may not use this file except in compliance with the License. A copy of
 * the License is located at
 *
 *     http://aws.amazon.com/apache2.0/
 *
 * or in the "license" file accompanying this file. This file is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 * ANY KIND, either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 */

var AWS = require('./core');
var inherit = AWS.util.inherit;

/**
 * @api private
 */
AWS.ResourceWaiter = inherit({
  /**
   * Waits for a given state on a service object
   * @param service [Service] the service object to wait on
   * @param state [String] the state (defined in waiter configuration) to wait
   *   for.
   * @example Create a waiter for running EC2 instances
   *   var ec2 = new AWS.EC2;
   *   var waiter = new AWS.ResourceWaiter(ec2, 'instanceRunning');
   */
  constructor: function constructor(service, state) {
    this.service = service;
    this.state = state;
    this.config = {};

    if (typeof this.state === 'object') {
      AWS.util.each.call(this, this.state, function (key, value) {
        this.state = key;
        this.expectedValue = value;
      });
    }

    this.loadWaiterConfig(this.state);
    if (!this.expectedValue) {
      this.expectedValue = this.config.successValue;
    }
  },

  service: null,

  state: null,

  expectedValue: null,

  config: null,

  /**
   * @return [AWS.Request]
   */
  wait: function wait(params, callback) {
    if (typeof params === 'function') {
      callback = params; params = undefined;
    }

    var request = this.service.makeRequest(this.config.operation, params);
    this.setupRequest(request);

    if (callback) request.send(callback);
    return request;
  },

  setupRequest: function setupRequest(request) {
    var waiter = this;

    var retryDelay = request.retryDelay;
    request.retryDelay = function(resp) {
      if (resp.error.code === 'ResourceNotReady') {
        return waiter.config.interval * 1000;
      } else {
        return retryDelay.call(request, resp);
      }
    };

    request.removeListener('extractError', AWS.EventListeners.Core.SETUP_ERROR);
    if (waiter.config.successType === 'error') {
      request.on('extractError', function (resp) {
        var success = waiter.checkError(waiter, resp);
        if (!success) {
          resp.data = null;
          resp.error = AWS.util.error(new Error(), {
            code: 'ResourceNotReady',
            message: 'Resource is not in the state ' + waiter.state,
            originalError: resp.error,
            retryable: success === null ? false : true
          });
        } else {
          resp.error = null;
        }
      });
    } else {
      request.removeAllListeners('extractError');
      request.on('extractData', function (resp) {
        var success = waiter.checkSuccess(waiter, resp);
        if (!success) {
          resp.data = null;
          resp.error = AWS.util.error(new Error(), {
            code: 'ResourceNotReady',
            message: 'Resource is not in the state ' + waiter.state,
            originalError: resp.error,
            retryable: success === null ? false : true
          });
        }
      });
    }

    var retryCheck = AWS.EventListeners.Core.RETRY_CHECK;
    var index = request._events['retry'].indexOf(retryCheck);
    request._events['retry'][index] = function newRetryCheck(resp) {
      var e = resp.error;
      resp.waiterRetryCount = resp.waiterRetryCount || 0;
      if (e && e.retryable && e.code === 'ResourceNotReady') {
        if (resp.waiterRetryCount < waiter.config.maxAttempts) {
          resp.waiterRetryCount++;
        } else {
          throw e;
        }
      } else {
        retryCheck.call(resp.request, resp);
      }
    };
  },

  /**
   * Checks if the terminal expected success state has been met
   * @return [Boolean]
   */
  checkSuccess: function checkSuccess(waiter, resp) {
    if (!waiter.config.successPath) {
      return resp.httpResponse.statusCode < 300;
    }

    var r = AWS.util.jamespath.find(waiter.config.successPath, resp.data);

    if (waiter.config.failureValue &&
        waiter.config.failureValue.indexOf(r) >= 0) {
      return null; // fast fail
    }

    if (waiter.expectedValue) {
      return r === waiter.expectedValue;
    } else {
      return r ? true : false;
    }
  },

  /**
   * Checks if the terminal expected error state has been met
   * @return [Boolean]
   */
  checkError: function checkError(waiter, resp) {
    return resp.httpResponse.statusCode === waiter.config.successValue;
  },

  /**
   * Loads waiter configuration from API configuration and deals with inherited
   * properties.
   *
   * @api private
   */
  loadWaiterConfig: function loadWaiterConfig(state, noException) {
    if (!this.service.api.waiters[state]) {
      if (noException) return;
      throw new AWS.util.error(new Error(), {
        code: 'StateNotFoundError',
        message: 'State ' + state + ' not found.'
      });
    }

    if (state !== '__default__') {
      var superState = this.service.api.waiters[state]['extends'];
      superState = superState || '__default__';
      this.loadWaiterConfig(superState, true);
    }

    var config = this.config;
    AWS.util.update(config, this.service.api.waiters[state]);

    // inherit acceptor data
    (function () { // anonymous function to avoid max complexity count
      config.successType = config.successType || config.acceptorType;
      config.successPath = config.successPath || config.acceptorPath;
      config.successValue = config.successValue || config.acceptorValue;
      config.failureType = config.failureType || config.acceptorType;
      config.failurePath = config.failurePath || config.acceptorPath;
      config.failureValue = config.failureValue || config.acceptorValue;
    })();
  }
});
<commit_msg>Now that checkSuccess/Error are in waiter object, remove extra waiter object reference (use this)<commit_after>/**
 * Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"). You
 * may not use this file except in compliance with the License. A copy of
 * the License is located at
 *
 *     http://aws.amazon.com/apache2.0/
 *
 * or in the "license" file accompanying this file. This file is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 * ANY KIND, either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 */

var AWS = require('./core');
var inherit = AWS.util.inherit;

/**
 * @api private
 */
AWS.ResourceWaiter = inherit({
  /**
   * Waits for a given state on a service object
   * @param service [Service] the service object to wait on
   * @param state [String] the state (defined in waiter configuration) to wait
   *   for.
   * @example Create a waiter for running EC2 instances
   *   var ec2 = new AWS.EC2;
   *   var waiter = new AWS.ResourceWaiter(ec2, 'instanceRunning');
   */
  constructor: function constructor(service, state) {
    this.service = service;
    this.state = state;
    this.config = {};

    if (typeof this.state === 'object') {
      AWS.util.each.call(this, this.state, function (key, value) {
        this.state = key;
        this.expectedValue = value;
      });
    }

    this.loadWaiterConfig(this.state);
    if (!this.expectedValue) {
      this.expectedValue = this.config.successValue;
    }
  },

  service: null,

  state: null,

  expectedValue: null,

  config: null,

  /**
   * @return [AWS.Request]
   */
  wait: function wait(params, callback) {
    if (typeof params === 'function') {
      callback = params; params = undefined;
    }

    var request = this.service.makeRequest(this.config.operation, params);
    this.setupRequest(request);

    if (callback) request.send(callback);
    return request;
  },

  setupRequest: function setupRequest(request) {
    var waiter = this;

    var retryDelay = request.retryDelay;
    request.retryDelay = function(resp) {
      if (resp.error.code === 'ResourceNotReady') {
        return waiter.config.interval * 1000;
      } else {
        return retryDelay.call(request, resp);
      }
    };

    request.removeListener('extractError', AWS.EventListeners.Core.SETUP_ERROR);
    if (waiter.config.successType === 'error') {
      request.on('extractError', function (resp) {
        var success = waiter.checkError(resp);
        if (!success) {
          resp.data = null;
          resp.error = AWS.util.error(new Error(), {
            code: 'ResourceNotReady',
            message: 'Resource is not in the state ' + waiter.state,
            originalError: resp.error,
            retryable: success === null ? false : true
          });
        } else {
          resp.error = null;
        }
      });
    } else {
      request.removeAllListeners('extractError');
      request.on('extractData', function (resp) {
        var success = waiter.checkSuccess(resp);
        if (!success) {
          resp.data = null;
          resp.error = AWS.util.error(new Error(), {
            code: 'ResourceNotReady',
            message: 'Resource is not in the state ' + waiter.state,
            originalError: resp.error,
            retryable: success === null ? false : true
          });
        }
      });
    }

    var retryCheck = AWS.EventListeners.Core.RETRY_CHECK;
    var index = request._events['retry'].indexOf(retryCheck);
    request._events['retry'][index] = function newRetryCheck(resp) {
      var e = resp.error;
      resp.waiterRetryCount = resp.waiterRetryCount || 0;
      if (e && e.retryable && e.code === 'ResourceNotReady') {
        if (resp.waiterRetryCount < waiter.config.maxAttempts) {
          resp.waiterRetryCount++;
        } else {
          throw e;
        }
      } else {
        retryCheck.call(resp.request, resp);
      }
    };
  },

  /**
   * Checks if the terminal expected success state has been met
   * @return [Boolean]
   */
  checkSuccess: function checkSuccess(resp) {
    if (!this.config.successPath) {
      return resp.httpResponse.statusCode < 300;
    }

    var r = AWS.util.jamespath.find(this.config.successPath, resp.data);

    if (this.config.failureValue &&
        this.config.failureValue.indexOf(r) >= 0) {
      return null; // fast fail
    }

    if (this.expectedValue) {
      return r === this.expectedValue;
    } else {
      return r ? true : false;
    }
  },

  /**
   * Checks if the terminal expected error state has been met
   * @return [Boolean]
   */
  checkError: function checkError(resp) {
    return resp.httpResponse.statusCode === this.config.successValue;
  },

  /**
   * Loads waiter configuration from API configuration and deals with inherited
   * properties.
   *
   * @api private
   */
  loadWaiterConfig: function loadWaiterConfig(state, noException) {
    if (!this.service.api.waiters[state]) {
      if (noException) return;
      throw new AWS.util.error(new Error(), {
        code: 'StateNotFoundError',
        message: 'State ' + state + ' not found.'
      });
    }

    if (state !== '__default__') {
      var superState = this.service.api.waiters[state]['extends'];
      superState = superState || '__default__';
      this.loadWaiterConfig(superState, true);
    }

    var config = this.config;
    AWS.util.update(config, this.service.api.waiters[state]);

    // inherit acceptor data
    (function () { // anonymous function to avoid max complexity count
      config.successType = config.successType || config.acceptorType;
      config.successPath = config.successPath || config.acceptorPath;
      config.successValue = config.successValue || config.acceptorValue;
      config.failureType = config.failureType || config.acceptorType;
      config.failurePath = config.failurePath || config.acceptorPath;
      config.failureValue = config.failureValue || config.acceptorValue;
    })();
  }
});
<|endoftext|>


<commit_before>// Load modules

var NodeUtil = require('util');
var Stream = require('stream');
var Zlib = require('zlib');
var Generic = require('./generic');
var Utils = require('../utils');

// Declare internals

var internals = {};

// Stream response (Base -> Generic -> Stream)

exports = module.exports = internals.Stream = function (stream) {

    Generic.call(this);
    this._tag = 'stream';
    delete this._payload;

    this.stream = stream;

    return this;
};

NodeUtil.inherits(internals.Stream, Generic);

internals.Stream.prototype._transmit = function (request, callback) {

    var self = this;

    // Check if stream is a node HTTP response (stream.*) or a (mikeal's) Request object (stream.response.*)

    if (!request._route ||
        !request._route.config.proxy ||
        request._route.config.proxy.passThrough) {     // Pass headers only if not proxy or proxy with pass-through set

        var responseHeaders = this.stream.response ? this.stream.response.headers : this.stream.headers;
        if (responseHeaders) {
            Utils.merge(this.headers, responseHeaders);
        }
    }

    this._code = this.stream.statusCode || ((this.stream.response && this.stream.response.code) ? this.stream.response.code : this._code);

    var rawReq = (request && request.raw && request.raw.req) ? request.raw.req : null;
    var acceptEncoding = rawReq && rawReq.headers ? rawReq.headers['accept-encoding'] : null;
    var isGzip = acceptEncoding && acceptEncoding.indexOf('gzip') !== -1;
    var gzip = null;

    if (isGzip) {
        delete this.headers['Content-Length'];
        this.headers['Content-Encoding'] = 'gzip';
        this.headers.Vary = 'Accept-Encoding';
        gzip = Zlib.createGzip();
    }

    request.raw.res.writeHead(this._code, this.headers);

    var isEnded = false;
    var end = function () {

        if (isEnded) {
            return;
        }

        isEnded = true;
        request.raw.res.end();
        callback();
    };

    request.raw.req.on('close', function () {

        self.stream.destroy.bind(self.stream);
        gzip.destroy.bind(gzip);
        end();
    });

    this.stream.on('error', function () {

        request.raw.req.destroy();
        end();
    });

    if (isGzip) {
        gzip.on('end', function () {
            end();
        });
    }
    else {
        this.stream.on('end', function () {
            end();
        });
    }

    this.stream.resume();

    if (isGzip) {
        this.stream.pipe(gzip).pipe(request.raw.res);
    }
    else {
        this.stream.pipe(request.raw.res);
    }
};<commit_msg>Refactoring gzip for stream<commit_after>// Load modules

var NodeUtil = require('util');
var Stream = require('stream');
var Zlib = require('zlib');
var Generic = require('./generic');
var Utils = require('../utils');

// Declare internals

var internals = {};

// Stream response (Base -> Generic -> Stream)

exports = module.exports = internals.Stream = function (stream) {

    Generic.call(this);
    this._tag = 'stream';
    delete this._payload;

    this.stream = stream;

    return this;
};

NodeUtil.inherits(internals.Stream, Generic);

internals.Stream.prototype._transmit = function (request, callback) {

    var self = this;

    // Check if stream is a node HTTP response (stream.*) or a (mikeal's) Request object (stream.response.*)

    if (!request._route ||
        !request._route.config.proxy ||
        request._route.config.proxy.passThrough) {     // Pass headers only if not proxy or proxy with pass-through set

        var responseHeaders = this.stream.response ? this.stream.response.headers : this.stream.headers;
        if (responseHeaders) {
            Utils.merge(this.headers, responseHeaders);
        }
    }

    this._code = this.stream.statusCode || ((this.stream.response && this.stream.response.code) ? this.stream.response.code : this._code);

    var rawReq = (request && request.raw && request.raw.req) ? request.raw.req : null;
    var acceptEncoding = rawReq && rawReq.headers ? rawReq.headers['accept-encoding'] : null;
    var isGzip = acceptEncoding && acceptEncoding.indexOf('gzip') !== -1;
    var gzip = null;

    if (isGzip) {
        delete this.headers['Content-Length'];
        this.headers['Content-Encoding'] = 'gzip';
        this.headers.Vary = 'Accept-Encoding';
        gzip = Zlib.createGzip();
    }

    request.raw.res.writeHead(this._code, this.headers);

    var isEnded = false;
    var end = function () {

        if (isEnded) {
            return;
        }

        isEnded = true;
        request.raw.res.end();
        callback();
    };

    request.raw.req.on('close', function () {

        self.stream.destroy.bind(self.stream);

        if (gzip) {
            gzip.destroy.bind(gzip);
        }

        end();
    });

    this.stream.on('error', function () {

        request.raw.req.destroy();
        end();
    });

    if (isGzip) {
        gzip.on('end', function () {

            end();
        });

        this.stream.resume();
        this.stream.pipe(gzip).pipe(request.raw.res);
    }
    else {
        this.stream.on('end', function () {

            end();
        });

        this.stream.resume();
        this.stream.pipe(request.raw.res);
    }
};<|endoftext|>


<commit_before>// Dependencies
var path = require('path'),
  imagePath = '/tmp/';

module.exports = {
  // Send POST response
  postRes: function(req, res, key) {
    res.set('Content-Type', 'image/jpeg');
    res.status(201);
    res.json({id:key});
  },

  // Send error response
  errRes: function(req, res, statusCode, body) {
    statusCode = statusCode || 404;
    body = body || 'image not found';
    res.status(statusCode);
    res.send(body);
  },

  // Send GET response
  getRes: function(req, res, key) {
    res.set({'Content-Type': 'image/jpeg'});
    res.status(200);
    res.sendfile(imagePath + key + '.jpg');
  },

  // Send DELETE response
  delRes: function(req, res, key) {
    res.status(204);
    res.json({id:key});
  },

  // Send JSON with metadata for requested image
  metaData: function(req, res, key, w, h, statusCode) {
    var response = {};

    response.id = key;
    response.bucket = process.env.AWS_BUCKET;
    response.url = '/' + key;
    response.createdAt = new Date();
    response.width = w;
    response.height = h;

    res.status(statusCode);
    res.json(response);
  }
};<commit_msg>add filesize and image formate to json response<commit_after>// Dependencies
var path = require('path'),
  imagePath = '/tmp/';

module.exports = {
  // Send POST response
  postRes: function(req, res, key) {
    res.set('Content-Type', 'image/jpeg');
    res.status(201);
    res.json({id:key});
  },

  // Send error response
  errRes: function(req, res, statusCode, body) {
    statusCode = statusCode || 404;
    body = body || 'image not found';
    res.status(statusCode);
    res.send(body);
  },

  // Send GET response
  getRes: function(req, res, key) {
    res.set({'Content-Type': 'image/jpeg'});
    res.status(200);
    res.sendfile(imagePath + key + '.jpg');
  },

  // Send DELETE response
  delRes: function(req, res, key) {
    res.status(204);
    res.json({id:key});
  },

  // Send JSON with metadata for requested image
  metaData: function(req, res, key, features, statusCode) {
    var response = {};

    response.id = key;
    response.bucket = process.env.AWS_BUCKET;
    response.url = '/babyanimals' + key;
    response.createdAt = new Date();
    response.width = features.width;
    response.height = features.height;
    response.filesize = features.filesize;
    response.format = features.format;

    res.status(statusCode);
    res.json(response);
  }
};<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var es = require('event-stream');
var path = require('path');
var gutil = require('gulp-util');
var transform = require('../transform');
var tags = require('../tags');
var PluginError = gutil.PluginError;
var File = gutil.File;
var magenta = gutil.colors.magenta;
var cyan = gutil.colors.cyan;
var red = gutil.colors.red;

/**
 * Constants
 */
var PLUGIN_NAME = 'gulp-inject';

module.exports = exports = function(sources, opt){
  if (!sources) {
    throw error('Missing sources stream!');
  }
  if (!opt) {
    opt = {};
  }

  if (opt.sort) {
    throw error('sort option is deprecated! Use `sort-stream` module instead!');
  }
  if (opt.templateString) {
    throw error('`templateString` option is deprecated! Create a virtual `vinyl` file instead!');
  }
  if (opt.transform && typeof opt.transform !== 'function') {
    throw error('transform option must be a function');
  }

  // Notify people of common mistakes...
  if (opt.read) {
    warn('There is no ' + magenta('`read`') + ' option. Did you mean to provide it for ' + magenta('`gulp.src`') + ' perhaps?');
  }

  // Defaults:
  opt.ignorePath = toArray(opt.ignorePath).map(unixify);
  opt.relative = bool(opt, 'relative', false);
  opt.addRootSlash = bool(opt, 'addRootSlash', !opt.relative);
  opt.transform = defaults(opt, 'transform', transform);
  transform.selfClosingTag = bool(opt, 'selfClosingTag', false);
  tags.name = defaults(opt, 'name', 'inject');

  // Is the first parameter a Vinyl File Stream:
  if (typeof sources.on === 'function' && typeof sources.pipe === 'function') {
    return handleVinylStream(sources, opt);
  }

  throw error('passing target file as a string is deprecated! Pass a vinyl file stream (i.e. use `gulp.src`)!');
};

function defaults (options, prop, defaultValue) {
  return options[prop] || defaultValue;
}

function bool (options, prop, defaultVal) {
  return typeof options[prop] !== 'undefined' ? !!options[prop] : defaultVal;
}

/**
 * Handle injection when files to
 * inject comes from a Vinyl File Stream
 *
 * @param {Stream} sources
 * @param {Object} opt
 * @returns {Stream}
 */
function handleVinylStream (sources, opt) {
  var collected = collectFilesToInject(sources, opt);

  return es.map(function (target, cb) {
    if (target.isStream()) {
      return cb(error('Streams not supported for target templates!'));
    }
    collected(function (collection) {
      target.contents = getNewContent(target, collection, opt);
      cb(null, target);
    });
  });
}

/**
 * Collecting files to inject from Vinyl File Stream
 *
 * Returns an almost promise like function which can be
 * called multiple times with a callback, that will be
 * resolved with the result of the file collection.
 *
 * @param {Stream} sources
 * @param {Object} opt
 * @returns {Function}
 */
function collectFilesToInject (sources, opt) {
  var collection = [], done = false, queue = [];

  sources.pipe(es.through(collector(collection, opt), function () {
    done = true;
    while (queue.length) {
      resolve(queue.shift());
    }
  }));

  function resolve (cb) {
    process.nextTick(function () {
      cb(collection);
    });
  }

  return function (cb) {
    if (done) {
      resolve(cb);
    } else {
      queue.push(cb);
    }
  };
}

/**
 * Create a file collecting function
 * to be used in es.through
 *
 * @param {Array} collection  Collection to fill with files
 * @param {Object} opt
 * @returns {Function}
 */
function collector (collection, opt) {
  return function (file) {
    if (!file.path) {
      return;
    }

    collection.push(file);
  };
}

/**
 * Get new content for template
 * with all injections made
 *
 * @param {Object} target
 * @param {Array} collection
 * @param {Object} opt
 * @returns {Buffer}
 */
function getNewContent (target, collection, opt) {
  var oldContent = target.contents;
  if (!collection.length) {
    return oldContent;
  }

  var filesPerExtension = groupBy(collection, function (file) {
    return extname(file.path);
  });

  var targetExt = extname(target.path);
  var extensions = Object.keys(filesPerExtension);

  log(cyan(collection.length) + ' files into ' + magenta(target.relative) + '.');

  return new Buffer(extensions.reduce(function eachInCollection (contents, ext) {
    var startTag = tags.start(targetExt, ext, opt.starttag);
    var endTag = tags.end(targetExt, ext, opt.endtag);
    var files = filesPerExtension[ext];

    return contents.replace(
      getInjectorTagsRegExp(startTag, endTag),
      function injector (match, starttag, indent, content, endtag) {
        return [starttag]
          .concat(files.map(function transformFile (file, i) {
            var filepath = getFilepath(file, target, opt);
            return opt.transform(filepath, file, i, files.length, target);
          }))
          .concat([endtag])
          .join(indent);
      }
    );
  }, String(oldContent)));
}

function getFilepath (sourceFile, targetFile, opt) {
  var base = opt.relative ? path.dirname(targetFile.path) : sourceFile.cwd;

  var filepath = unixify(path.relative(base, sourceFile.path));

  if (opt.ignorePath.length) {
    filepath = removeBasePath(opt.ignorePath, filepath);
  }

  if (opt.addPrefix) {
    filepath = addPrefix(filepath, opt.addPrefix);
  }

  if (opt.addRootSlash) {
    filepath = addRootSlash(filepath);
  } else {
    filepath = removeRootSlash(filepath);
  }

  return filepath;
}

function getTag (tag, ext) {
  return tag.replace('{{ext}}', ext);
}

function extname (file) {
  return path.extname(file).slice(1);
}

function getInjectorTagsRegExp (starttag, endtag) {
  return new RegExp('(' + escapeForRegExp(starttag) + ')(\\s*)(\\n|\\r|.)*?(' + escapeForRegExp(endtag) + ')', 'gi');
}

function escapeForRegExp (str) {
  return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}

function unixify (filepath) {
  return filepath.replace(/\\/g, '/');
}
function addRootSlash (filepath) {
  return filepath.replace(/^\/*([^\/])/, '/$1');
}
function removeRootSlash (filepath) {
  return filepath.replace(/^\/+/, '');
}
function addPrefix (filepath, prefix) {
  return  prefix + addRootSlash(filepath);
}

function removeBasePath (basedir, filepath) {
  return toArray(basedir).reduce(function (path, remove) {
    if (path[0] === '/' && remove[0] !== '/') {
      remove = '/' + remove;
    }
    if (path[0] !== '/' && remove[0] === '/') {
      path = '/' + path;
    }
    if (remove && path.indexOf(remove) === 0) {
      return path.slice(remove.length);
    }
    return path;
  }, filepath);
}

function toArray (arr) {
  if (!Array.isArray(arr)) {
    return arr ? [arr] : [];
  }
  return arr;
}

function groupBy (arr, cb) {
  var result = {};
  for (var i = 0; i < arr.length; i++) {
    var key = cb(arr[i]);
    if (!result[key]) {
      result[key] = [];
    }
    result[key].push(arr[i]);
  }
  return result;
}

function log (message) {
  gutil.log(magenta(PLUGIN_NAME), message);
}

function warn (message) {
  log(red('WARNING') + ' ' + message);
}

function error (message) {
  return new PluginError(PLUGIN_NAME, message);
}
<commit_msg>Logging when nothing was injected as well<commit_after>'use strict';

var fs = require('fs');
var es = require('event-stream');
var path = require('path');
var gutil = require('gulp-util');
var transform = require('../transform');
var tags = require('../tags');
var PluginError = gutil.PluginError;
var File = gutil.File;
var magenta = gutil.colors.magenta;
var cyan = gutil.colors.cyan;
var red = gutil.colors.red;

/**
 * Constants
 */
var PLUGIN_NAME = 'gulp-inject';

module.exports = exports = function(sources, opt){
  if (!sources) {
    throw error('Missing sources stream!');
  }
  if (!opt) {
    opt = {};
  }

  if (opt.sort) {
    throw error('sort option is deprecated! Use `sort-stream` module instead!');
  }
  if (opt.templateString) {
    throw error('`templateString` option is deprecated! Create a virtual `vinyl` file instead!');
  }
  if (opt.transform && typeof opt.transform !== 'function') {
    throw error('transform option must be a function');
  }

  // Notify people of common mistakes...
  if (opt.read) {
    warn('There is no ' + magenta('`read`') + ' option. Did you mean to provide it for ' + magenta('`gulp.src`') + ' perhaps?');
  }

  // Defaults:
  opt.ignorePath = toArray(opt.ignorePath).map(unixify);
  opt.relative = bool(opt, 'relative', false);
  opt.addRootSlash = bool(opt, 'addRootSlash', !opt.relative);
  opt.transform = defaults(opt, 'transform', transform);
  transform.selfClosingTag = bool(opt, 'selfClosingTag', false);
  tags.name = defaults(opt, 'name', 'inject');

  // Is the first parameter a Vinyl File Stream:
  if (typeof sources.on === 'function' && typeof sources.pipe === 'function') {
    return handleVinylStream(sources, opt);
  }

  throw error('passing target file as a string is deprecated! Pass a vinyl file stream (i.e. use `gulp.src`)!');
};

function defaults (options, prop, defaultValue) {
  return options[prop] || defaultValue;
}

function bool (options, prop, defaultVal) {
  return typeof options[prop] !== 'undefined' ? !!options[prop] : defaultVal;
}

/**
 * Handle injection when files to
 * inject comes from a Vinyl File Stream
 *
 * @param {Stream} sources
 * @param {Object} opt
 * @returns {Stream}
 */
function handleVinylStream (sources, opt) {
  var collected = collectFilesToInject(sources, opt);

  return es.map(function (target, cb) {
    if (target.isStream()) {
      return cb(error('Streams not supported for target templates!'));
    }
    collected(function (collection) {
      target.contents = getNewContent(target, collection, opt);
      cb(null, target);
    });
  });
}

/**
 * Collecting files to inject from Vinyl File Stream
 *
 * Returns an almost promise like function which can be
 * called multiple times with a callback, that will be
 * resolved with the result of the file collection.
 *
 * @param {Stream} sources
 * @param {Object} opt
 * @returns {Function}
 */
function collectFilesToInject (sources, opt) {
  var collection = [], done = false, queue = [];

  sources.pipe(es.through(collector(collection, opt), function () {
    done = true;
    while (queue.length) {
      resolve(queue.shift());
    }
  }));

  function resolve (cb) {
    process.nextTick(function () {
      cb(collection);
    });
  }

  return function (cb) {
    if (done) {
      resolve(cb);
    } else {
      queue.push(cb);
    }
  };
}

/**
 * Create a file collecting function
 * to be used in es.through
 *
 * @param {Array} collection  Collection to fill with files
 * @param {Object} opt
 * @returns {Function}
 */
function collector (collection, opt) {
  return function (file) {
    if (!file.path) {
      return;
    }

    collection.push(file);
  };
}

/**
 * Get new content for template
 * with all injections made
 *
 * @param {Object} target
 * @param {Array} collection
 * @param {Object} opt
 * @returns {Buffer}
 */
function getNewContent (target, collection, opt) {
  var oldContent = target.contents;
  if (!collection.length) {
    log('Nothing to inject into ' + magenta(target.relative) + '.');
    return oldContent;
  }

  var filesPerExtension = groupBy(collection, function (file) {
    return extname(file.path);
  });

  var targetExt = extname(target.path);
  var extensions = Object.keys(filesPerExtension);

  log(cyan(collection.length) + ' files into ' + magenta(target.relative) + '.');

  return new Buffer(extensions.reduce(function eachInCollection (contents, ext) {
    var startTag = tags.start(targetExt, ext, opt.starttag);
    var endTag = tags.end(targetExt, ext, opt.endtag);
    var files = filesPerExtension[ext];

    return contents.replace(
      getInjectorTagsRegExp(startTag, endTag),
      function injector (match, starttag, indent, content, endtag) {
        return [starttag]
          .concat(files.map(function transformFile (file, i) {
            var filepath = getFilepath(file, target, opt);
            return opt.transform(filepath, file, i, files.length, target);
          }))
          .concat([endtag])
          .join(indent);
      }
    );
  }, String(oldContent)));
}

function getFilepath (sourceFile, targetFile, opt) {
  var base = opt.relative ? path.dirname(targetFile.path) : sourceFile.cwd;

  var filepath = unixify(path.relative(base, sourceFile.path));

  if (opt.ignorePath.length) {
    filepath = removeBasePath(opt.ignorePath, filepath);
  }

  if (opt.addPrefix) {
    filepath = addPrefix(filepath, opt.addPrefix);
  }

  if (opt.addRootSlash) {
    filepath = addRootSlash(filepath);
  } else {
    filepath = removeRootSlash(filepath);
  }

  return filepath;
}

function getTag (tag, ext) {
  return tag.replace('{{ext}}', ext);
}

function extname (file) {
  return path.extname(file).slice(1);
}

function getInjectorTagsRegExp (starttag, endtag) {
  return new RegExp('(' + escapeForRegExp(starttag) + ')(\\s*)(\\n|\\r|.)*?(' + escapeForRegExp(endtag) + ')', 'gi');
}

function escapeForRegExp (str) {
  return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}

function unixify (filepath) {
  return filepath.replace(/\\/g, '/');
}
function addRootSlash (filepath) {
  return filepath.replace(/^\/*([^\/])/, '/$1');
}
function removeRootSlash (filepath) {
  return filepath.replace(/^\/+/, '');
}
function addPrefix (filepath, prefix) {
  return  prefix + addRootSlash(filepath);
}

function removeBasePath (basedir, filepath) {
  return toArray(basedir).reduce(function (path, remove) {
    if (path[0] === '/' && remove[0] !== '/') {
      remove = '/' + remove;
    }
    if (path[0] !== '/' && remove[0] === '/') {
      path = '/' + path;
    }
    if (remove && path.indexOf(remove) === 0) {
      return path.slice(remove.length);
    }
    return path;
  }, filepath);
}

function toArray (arr) {
  if (!Array.isArray(arr)) {
    return arr ? [arr] : [];
  }
  return arr;
}

function groupBy (arr, cb) {
  var result = {};
  for (var i = 0; i < arr.length; i++) {
    var key = cb(arr[i]);
    if (!result[key]) {
      result[key] = [];
    }
    result[key].push(arr[i]);
  }
  return result;
}

function log (message) {
  gutil.log(magenta(PLUGIN_NAME), message);
}

function warn (message) {
  log(red('WARNING') + ' ' + message);
}

function error (message) {
  return new PluginError(PLUGIN_NAME, message);
}
<|endoftext|>


<commit_before>'use strict';

var express = require('express');
var async = require('async');
var common = require('../common');
var models = require('../models');
var pjson = require('../../package.json');
var router = express.Router();
var Project = models.Project;
var User = models.User;
var debug = require('debug')('strider:routes');

router.route('/')
  .get(function (req, res) {
    return renderProjects(false, req, res);
  })
  .post(function (req, res) {
    var refresh = req.body.refresh !== 'false' && req.body.refresh !== '0';

    return renderProjects(refresh, req, res);
  });

module.exports = router;

function renderProjects(refresh, req, res) {
  var tasks = [];
  var repomap = {};
  var configured = {};
  var unconfigured = [];
  var providers = common.userConfigs.provider;
  var manual = {};
  var manualProjects = {};

  Object.keys(common.pluginConfigs.provider).forEach(function (key) {
    var config = common.pluginConfigs.provider[key];
    if (common.extensions.provider[key].hosted) return;
    manualProjects[key] = [];
    manual[key] = {
      provider: config,
      projects: manualProjects[key]
    };
  });

  Project.find({creator: req.user._id}).lean().exec(function (err, projects) {
    if (err) return res.send(500, 'Failed to get projects from the database');
    // tree is { providerid: { accountid: { repoid: project._id, ...}, ...}, ...}
    // to track which repos have been configured
    var tree = {};
    for (var i = 0; i < projects.length; i++) {
      var provider = projects[i].provider;
      if (!provider.account) {
        if (!manual[provider.id]) {
          manual[provider.id] = {
            provider: common.pluginConfigs.provider[provider.id],
            projects: []
          };
        }
        manual[provider.id].projects.push(projects[i]);
        continue;
      }
      deepObj(tree, provider.id, provider.account)[provider.repo_id] = {
        _id: projects[i]._id,
        name: projects[i].name
      };
    }

    req.user.accounts.forEach(function (account) {
      configured[account.provider] = true;

      // Caching
      var haveCache = Array.isArray(account.cache) && account.cache.length > 0;
      if (!refresh && haveCache) {
        groupRepos(account, repomap, tree, account.toJSON().cache);
        return;
      }

      tasks.push(function (next) {
        debug(`Now trying to list repos for the following provider for an account in the user model: ${account.provider}`);

        if (!common.extensions.provider[account.provider]) {
          next(new Error(`The plugin for ${account.provider} could not be found. Please install the plugin from Admin > Plugins`));
        } else {
          common.extensions.provider[account.provider].listRepos(account.config, function (err, repos) {
            if (err) {
              if (haveCache) {
                groupRepos(account, repomap, tree, account.toJSON().cache);
              }
              return next(err);
            }
            account.set('cache', repos);
            groupRepos(account, repomap, tree, repos);
            account.last_updated = new Date();
            next();
          });
        }
      });
    });
    for (var id in providers) {
      if (configured[id] || !providers[id].setupLink) continue;
      unconfigured.push(providers[id]);
    }
    console.log('Fetching projects...');
    async.parallel(tasks, function (err) {
      if (err) req.flash('account', `Failed to refresh repositories: ${(err.message || err)}`);
      console.log([err]);
      // cache the fetched repos
      User.update({_id: req.user._id}, {$set: {accounts: req.user.toJSON().accounts}}, function (err, num) {
        if (err) console.error('error saving repo cache');
        if (!num) console.error('Didn\'t effect any users');
        console.log('Saved repo cache');
        // user is already be available via the "currentUser" template variable

        return res.format({
          html: function () {
            res.render('projects.html', {
              unconfigured: unconfigured,
              providers: providers,
              manual: manual,
              manualProjects: manualProjects,
              repos: repomap,
              flash: req.flash(),
              project_types: availableProjectTypes(),
              version: pjson.version
            });
          },
          json: function () {
            res.send({
              unconfigured: unconfigured,
              providers: providers,
              manual: manual,
              manualProjects: manualProjects,
              repos: repomap,
              project_types: availableProjectTypes()
            });
          }
        });
      });
    });
  });
}

function availableProjectTypes() {
  var available = {};
  for (var id in common.project_types) {
    var good = true;
    var plugins = common.project_types[id].plugins;
    for (var i = 0; i < plugins.length; i++) {
      if (!common.extensions.job[plugins[i]]) {
        good = false;
        break;
      }
    }
    if (good) {
      available[id] = common.project_types[id];
    }
  }
  return available;
}

function groupRepos(account, repomap, tree, repos) {
  var groups = deepObj(repomap, account.provider, account.id);
  var projectmap = getDeep(tree, account.provider, account.id) || {};
  for (var i = 0; i < repos.length; i++) {
    if (!groups[repos[i].group]) {
      groups[repos[i].group] = {
        configured: 0,
        repos: []
      };
    }
    repos[i].project = projectmap[repos[i].id];
    groups[repos[i].group].repos.push(repos[i]);
    if (repos[i].project) {
      groups[repos[i].group].configured += 1;
    }
  }
}

function getDeep(obj) {
  return [].slice.call(arguments, 1).reduce(function (obj, name) {
    return obj && obj[name];
  }, obj);
}

function deepObj(obj) {
  var names = [].slice.call(arguments, 1);
  return names.reduce(function (obj, name) {
    return obj[name] || (obj[name] = {});
  }, obj);
}
<commit_msg>Use debug for logging<commit_after>'use strict';

var express = require('express');
var async = require('async');
var common = require('../common');
var models = require('../models');
var pjson = require('../../package.json');
var router = express.Router();
var Project = models.Project;
var User = models.User;
var debug = require('debug')('strider:routes');

router.route('/')
  .get(function (req, res) {
    return renderProjects(false, req, res);
  })
  .post(function (req, res) {
    var refresh = req.body.refresh !== 'false' && req.body.refresh !== '0';

    return renderProjects(refresh, req, res);
  });

module.exports = router;

function renderProjects(refresh, req, res) {
  var tasks = [];
  var repomap = {};
  var configured = {};
  var unconfigured = [];
  var providers = common.userConfigs.provider;
  var manual = {};
  var manualProjects = {};

  Object.keys(common.pluginConfigs.provider).forEach(function (key) {
    var config = common.pluginConfigs.provider[key];
    if (common.extensions.provider[key].hosted) return;
    manualProjects[key] = [];
    manual[key] = {
      provider: config,
      projects: manualProjects[key]
    };
  });

  Project.find({creator: req.user._id}).lean().exec(function (err, projects) {
    if (err) return res.send(500, 'Failed to get projects from the database');
    // tree is { providerid: { accountid: { repoid: project._id, ...}, ...}, ...}
    // to track which repos have been configured
    var tree = {};
    for (var i = 0; i < projects.length; i++) {
      var provider = projects[i].provider;
      if (!provider.account) {
        if (!manual[provider.id]) {
          manual[provider.id] = {
            provider: common.pluginConfigs.provider[provider.id],
            projects: []
          };
        }
        manual[provider.id].projects.push(projects[i]);
        continue;
      }
      deepObj(tree, provider.id, provider.account)[provider.repo_id] = {
        _id: projects[i]._id,
        name: projects[i].name
      };
    }

    req.user.accounts.forEach(function (account) {
      configured[account.provider] = true;

      // Caching
      var haveCache = Array.isArray(account.cache) && account.cache.length > 0;
      if (!refresh && haveCache) {
        groupRepos(account, repomap, tree, account.toJSON().cache);
        return;
      }

      tasks.push(function (next) {
        debug(`Now trying to list repos for the following provider for an account in the user model: ${account.provider}`);

        if (!common.extensions.provider[account.provider]) {
          next(new Error(`The plugin for ${account.provider} could not be found. Please install the plugin from Admin > Plugins`));
        } else {
          common.extensions.provider[account.provider].listRepos(account.config, function (err, repos) {
            if (err) {
              if (haveCache) {
                groupRepos(account, repomap, tree, account.toJSON().cache);
              }
              return next(err);
            }
            account.set('cache', repos);
            groupRepos(account, repomap, tree, repos);
            account.last_updated = new Date();
            next();
          });
        }
      });
    });
    for (var id in providers) {
      if (configured[id] || !providers[id].setupLink) continue;
      unconfigured.push(providers[id]);
    }
    debug('Fetching projects...');
    async.parallel(tasks, function (err) {
      if (err) {
        req.flash('account', `Failed to refresh repositories: ${(err.message || err)}`);
        debug(err);
      }
      // cache the fetched repos
      User.update({_id: req.user._id}, {$set: {accounts: req.user.toJSON().accounts}}, function (err, num) {
        if (err) console.error('error saving repo cache');
        if (!num) console.error('Didn\'t effect any users');
        debug('Saved repo cache');
        // user is already be available via the "currentUser" template variable

        return res.format({
          html: function () {
            res.render('projects.html', {
              unconfigured: unconfigured,
              providers: providers,
              manual: manual,
              manualProjects: manualProjects,
              repos: repomap,
              flash: req.flash(),
              project_types: availableProjectTypes(),
              version: pjson.version
            });
          },
          json: function () {
            res.send({
              unconfigured: unconfigured,
              providers: providers,
              manual: manual,
              manualProjects: manualProjects,
              repos: repomap,
              project_types: availableProjectTypes()
            });
          }
        });
      });
    });
  });
}

function availableProjectTypes() {
  var available = {};
  for (var id in common.project_types) {
    var good = true;
    var plugins = common.project_types[id].plugins;
    for (var i = 0; i < plugins.length; i++) {
      if (!common.extensions.job[plugins[i]]) {
        good = false;
        break;
      }
    }
    if (good) {
      available[id] = common.project_types[id];
    }
  }
  return available;
}

function groupRepos(account, repomap, tree, repos) {
  var groups = deepObj(repomap, account.provider, account.id);
  var projectmap = getDeep(tree, account.provider, account.id) || {};
  for (var i = 0; i < repos.length; i++) {
    if (!groups[repos[i].group]) {
      groups[repos[i].group] = {
        configured: 0,
        repos: []
      };
    }
    repos[i].project = projectmap[repos[i].id];
    groups[repos[i].group].repos.push(repos[i]);
    if (repos[i].project) {
      groups[repos[i].group].configured += 1;
    }
  }
}

function getDeep(obj) {
  return [].slice.call(arguments, 1).reduce(function (obj, name) {
    return obj && obj[name];
  }, obj);
}

function deepObj(obj) {
  var names = [].slice.call(arguments, 1);
  return names.reduce(function (obj, name) {
    return obj[name] || (obj[name] = {});
  }, obj);
}
<|endoftext|>


<commit_before>// Sanitize statuses and fields for posts
//
// - N
// - posts - array of models.forum.Post. Could be plain value
// - user_info - Object with `usergroups` array and `hb`
// - callback - `function (err, res)`
//   - res - array of sanitized items. If `posts` is not array - will be plain sanitized post
//
'use strict';

const _  = require('lodash');
const co = require('bluebird-co').co;

const fields = [
  '_id',
  'hid',
  'to',
  'to_user',
  'to_fhid',
  'to_thid',
  'to_phid',
  'tail',
  'html',
  'user',
  'legacy_nick',
  'ts',
  'st',
  'ste',
  'del_reason',
  'del_by',
  'votes',
  'votes_hb',
  'bookmarks'
];

module.exports = co.wrap(function* (N, posts, user_info) {
  let res;

  if (!Array.isArray(posts)) {
    res = [ posts ];
  } else {
    res = posts.slice();
  }

  res = res.map(item => _.pick(item, fields));

  let params = {
    user_id: user_info.user_id,
    usergroup_ids: user_info.usergroups
  };

  let can_see_hellbanned = yield N.settings.get('can_see_hellbanned', params, {});

  res = res.map(item => {
    if (item.st === N.models.forum.Post.statuses.HB && can_see_hellbanned) {
      item.st = item.ste;
      delete item.ste;
    }

    if (user_info.hb) {
      item.votes = item.votes_hb;
    }
    delete item.votes_hb;

    return item;
  });

  if (Array.isArray(posts)) return res;

  return res[0];
});

module.exports.fields = fields;
<commit_msg>Fixed post sanitizer<commit_after>// Sanitize statuses and fields for posts
//
// - N
// - posts - array of models.forum.Post. Could be plain value
// - user_info - Object with `usergroups` array and `hb`
// - callback - `function (err, res)`
//   - res - array of sanitized items. If `posts` is not array - will be plain sanitized post
//
'use strict';

const _  = require('lodash');
const co = require('bluebird-co').co;

const fields = [
  '_id',
  'hid',
  'to',
  'to_user',
  'to_fhid',
  'to_thid',
  'to_phid',
  'tail',
  'html',
  'user',
  'legacy_nick',
  'ts',
  'st',
  'ste',
  'del_reason',
  'del_by',
  'votes',
  'votes_hb',
  'bookmarks'
];

module.exports = co.wrap(function* (N, posts, user_info) {
  let res;

  if (!Array.isArray(posts)) {
    res = [ posts ];
  } else {
    res = posts.slice();
  }

  res = res.map(item => _.pick(item, fields));

  let params = {
    user_id: user_info.user_id,
    usergroup_ids: user_info.usergroups
  };

  let can_see_hellbanned = yield N.settings.get('can_see_hellbanned', params, {});

  res = res.map(item => {
    if (item.st === N.models.forum.Post.statuses.HB && !can_see_hellbanned) {
      item.st = item.ste;
      delete item.ste;
    }

    if (item.votes_hb && (user_info.hb || can_see_hellbanned)) {
      item.votes = item.votes_hb;
    }
    delete item.votes_hb;

    return item;
  });

  if (Array.isArray(posts)) return res;

  return res[0];
});

module.exports.fields = fields;
<|endoftext|>


<commit_before>var settings = require('./settings.js');
var semester = settings.SEMESTER;
var request = require('request');

/* Download schedule for current semester */
var getSchedule = function(semesters){
    console.log("Getting courses for semester: " + semester);
    /* Build course URL */
    var course_url = "http://sis.rpi.edu/reg/zs" + semester + ".htm";
    console.log("Loading course from URL: " + course_url);

    request.get({
        uri: course_url
    },function(error,response,body){
        if(error){
            return console.error("ERROR: Failed to load course: " + error);
        }
		//console.log(body);
        parseSchedule(body);
    });
}(semester);

var parseSchedule = function(schedule_doc){
	var rows = [];
	var objects =[];
	var count = 0;
	while(schedule_doc.indexOf('<TR') != -1)
	{
		start = schedule_doc.indexOf('<TR');
		end = schedule_doc.indexOf('
');
		temp = schedule_doc.substring(start,end)
		rows.push(temp);
		schedule_doc = schedule_doc.substring(end+4,schedule_doc.length);
		count++;
	}
	var lastcrn = 0;
	for(i = 0; i < rows.length; i++)
	{
		var crn;
		if(rows[i].search(/\b\d{5}[ ]\b/g) != -1){
			var newobj = [];
			crn = rows[i].match(/\b\d{5}\b/);
			newobj.push(crn[0]);
			name = rows[i].match(/\b[A-Z]{4}-[0-9]{4}-[0-9]{1,2}\b/g);
			newobj.push(name[0]);
			var timeslist = [];
			var temp = '';
			if(rows[i].match(/[MTWRF ]{1}[MTWRF ]{1}[MTWRF ]{1}[MTWRF ]{1}[MTWRF ]{1}[MTWRF ]{1}/) !== null)
			{
				newday = rows[i].match(/[MTWRF ]{1}[MTWRF ]{1}[MTWRF ]{1}[MTWRF ]{1}[MTWRF ]{1}[MTWRF ]{1}/);
				temp = newday[0].replace(/\s+/g, '');
			}
			if(rows[i].match(/[0-9]{1,2}:[0-9]{2}/g) !== null)
			{
				times = rows[i].match(/[0-9]{1,2}:[0-9]{2}/g)
				temp = temp +': '+times[0]+'-'+times[1];
			}
			timeslist.push(temp);
			newobj.push(timeslist);
			objects.push(newobj);
			lastcrn = 0;
		} else if (rows[i].indexOf("CRN") == -1 && rows[i].indexOf("Course-Sec") == -1 && rows[i].indexOf("NOTE:") == -1 && objects.length > 0){
			lastcrn++;
			var temp = '';
			if(rows[i].match(/[MTWRF ]{1}[MTWRF ]{1}[MTWRF ]{1}[MTWRF ]{1}[MTWRF ]{1}[MTWRF ]{1}/) !== null)
			{
				newday = rows[i].match(/[MTWRF ]{1}[MTWRF ]{1}[MTWRF ]{1}[MTWRF ]{1}[MTWRF ]{1}[MTWRF ]{1}/);
				temp = newday[0].replace(/\s+/g, '');
			}
			if(rows[i].match(/[0-9]{1,2}:[0-9]{2}/g) !== null)
			{
				times = rows[i].match(/[0-9]{1,2}:[0-9]{2}/g)
				temp = temp +': '+times[0]+'-'+times[1];
			}
			console.log(objects[objects.length-lastcrn]);
			obj = objects[objects.length-lastcrn];
			obj[2].push(temp);
		}

	}
	console.log(objects);
	console.log(objects.length);
}

	/*
	var index = schedule_doc.search(/\b\d{5}[ ]\b/g);
	schedule_doc = schedule_doc.substring(index,schedule_doc.length);
	var count = 0;
	while(index != -1){
		endclass = schedule_doc.indexOf("
");
		current_class = schedule_doc.substring(0,endclass);
		crn = current_class.substring(0,5);
		current_class = current_class.substring(5,current_class.length);
		endsname = current_class.indexOf("<");
		sname = current_class.substring(1,endsname);
		current_class = current_class.substring(endsname,current_class.length);
		beglname = current_class.indexOf("\">");
		current_class = current_class.substring(beglname+1,current_class.length);
		endlname = current_class.indexOf("<");
		lname = current_class.substring(1,endlname);
		current_class = current_class.substr(endlname,current_class.length);
		days = current_class.match(/[MTWRF\s]{3,6}/g);
		console.log(crn);
		console.log(sname);
		console.log(lname);
		time = current_class.match(/[0-9]{1,2}:[0-9]{2}/g);
		console.log(time);
		count++;
		schedule_doc = schedule_doc.substring(endclass,schedule_doc.length);
		console.log(days);
		if(lname == "ARCHITECTURAL DESIGN STUDIO 1")
		{
			return;
		}
		index = schedule_doc.search(/\b\d{5}[ ]\b/g);
		schedule_doc = schedule_doc.substring(index,schedule_doc.length);
	}
	console.log(count);
	//crns = schedule_doc.match(/\b\d{5}[ ]\b/g);
	//name = schedule_doc.match(/\b\w[A-Z]{3}[-][0-9]{4}\b/g);
    //days = schedule_doc.match(/\b[M|T|W|R|F| ]{4}\b/g);
	//time = schedule_doc.match();
	//console.log(crns.length);
	//console.log(name.length);
	//console.log(days.length);
};*/<commit_msg>Removed Commented Code, Fixed JSHint Stuff<commit_after>var settings = require('./settings.js');
var semester = settings.SEMESTER;
var request = require('request');

/* Download schedule for current semester */
var getSchedule = function(semesters){
    console.log("Getting courses for semester: " + semester);
    /* Build course URL */
    var course_url = "http://sis.rpi.edu/reg/zs" + semester + ".htm";
    console.log("Loading course from URL: " + course_url);

    request.get({
        uri: course_url
    },function(error,response,body){
        if(error){
            return console.error("ERROR: Failed to load course: " + error);
        }
		//console.log(body);
        classes = parseSchedule(body);
    });
}(semester);

var parseSchedule = function(schedule_doc){
	var rows = [];
	var objects =[];
	var count = 0;
	while(schedule_doc.indexOf('<TR') != -1)
	{
		start = schedule_doc.indexOf('<TR');
		end = schedule_doc.indexOf('
');
		temp = schedule_doc.substring(start,end);
		rows.push(temp);
		schedule_doc = schedule_doc.substring(end+4,schedule_doc.length);
		count++;
	}
	var lastcrn = 0;
	for(i = 0; i < rows.length; i++)
	{
		var crn;
		if(rows[i].search(/\b\d{5}[ ]\b/g) != -1){
			var newobj = [];
			crn = rows[i].match(/\b\d{5}\b/);
			newobj.push(crn[0]);
			name = rows[i].match(/\b[A-Z]{4}-[0-9]{4}-[0-9]{1,2}\b/g);
			newobj.push(name[0]);
			var timeslist = [];
			var temp = '';
			if(rows[i].match(/[MTWRF ]{1}[MTWRF ]{1}[MTWRF ]{1}[MTWRF ]{1}[MTWRF ]{1}[MTWRF ]{1}/) !== null)
			{
				newday = rows[i].match(/[MTWRF ]{1}[MTWRF ]{1}[MTWRF ]{1}[MTWRF ]{1}[MTWRF ]{1}[MTWRF ]{1}/);
				temp = newday[0].replace(/\s+/g, '');
			}
			if(rows[i].match(/[0-9]{1,2}:[0-9]{2}/g) !== null)
			{
				times = rows[i].match(/[0-9]{1,2}:[0-9]{2}/g);
				temp = temp +': '+times[0]+'-'+times[1];
			}
			timeslist.push(temp);
			newobj.push(timeslist);
			objects.push(newobj);
			lastcrn = 0;
		} else if (rows[i].indexOf("CRN") == -1 && rows[i].indexOf("Course-Sec") == -1 && rows[i].indexOf("NOTE:") == -1 && objects.length > 0){
			lastcrn++;
			var temp2 = '';
			if(rows[i].match(/[MTWRF ]{1}[MTWRF ]{1}[MTWRF ]{1}[MTWRF ]{1}[MTWRF ]{1}[MTWRF ]{1}/) !== null)
			{
				newday = rows[i].match(/[MTWRF ]{1}[MTWRF ]{1}[MTWRF ]{1}[MTWRF ]{1}[MTWRF ]{1}[MTWRF ]{1}/);
				temp2 = newday[0].replace(/\s+/g, '');
			}
			if(rows[i].match(/[0-9]{1,2}:[0-9]{2}/g) !== null)
			{
				times = rows[i].match(/[0-9]{1,2}:[0-9]{2}/g)
				temp2 = temp +': '+times[0]+'-'+times[1];
			}
			console.log(objects[objects.length-lastcrn]);
			obj = objects[objects.length-lastcrn];
			obj[2].push(temp);
		}

	}
	return objects;
};<|endoftext|>


<commit_before>"use strict";

const TsBase = require("./base");
const TsUtil = require("./util");

class TsSectionUpdater extends TsBase {
    constructor() {
        super();

        this.versions = {};
    }

    _process(tsSection, callback) {
        const tableId = tsSection.getTableId();

        if (tableId === 0x00) {
            // Program association
            const subTable = TsUtil.getNestedObject(this.versions, [tableId, tsSection.getTransportStreamId()]);

            TsUtil.updateSubTable(subTable, tsSection);

            if (!TsUtil.updateSection(subTable, tsSection)) {
                callback();
                return;
            }

            this.emit("pat", tsSection);

            this.push(tsSection);
        } else if (tableId === 0x01) {
            // Conditional access
            const subTable = TsUtil.getNestedObject(this.versions, [tableId]);

            TsUtil.updateSubTable(subTable, tsSection);

            if (!TsUtil.updateSection(subTable, tsSection)) {
                callback();
                return;
            }

            this.emit("cat", tsSection);

            this.push(tsSection);
        } else if (tableId === 0x02) {
            // Program map
            const subTable = TsUtil.getNestedObject(this.versions, [tableId, tsSection.getProgramNumber()]);

            TsUtil.updateSubTable(subTable, tsSection);

            if (!TsUtil.updateSection(subTable, tsSection)) {
                callback();
                return;
            }

            this.emit("pmt", tsSection);

            this.push(tsSection);
        } else if (tableId >= 0x3A && tableId <= 0x3F) {
            // DSM-CC
            const subTable = TsUtil.getNestedObject(this.versions, [tableId, tsSection.getTableIdExtension()]);

            TsUtil.updateSubTable(subTable, tsSection);

            if (!TsUtil.updateSection(subTable, tsSection)) {
                callback();
                return;
            }

            this.emit("dsmcc", tsSection);

            this.push(tsSection);
        } else if (tableId === 0x40 || tableId === 0x41) {
            // Network information
            const subTable = TsUtil.getNestedObject(this.versions, [tableId, tsSection.getNetworkId()]);

            TsUtil.updateSubTable(subTable, tsSection);

            if (!TsUtil.updateSection(subTable, tsSection)) {
                callback();
                return;
            }

            this.emit("nit", tsSection);

            this.push(tsSection);
        } else if (tableId === 0x42 || tableId === 0x46) {
            // Service description
            const subTable = TsUtil.getNestedObject(this.versions, [tableId, tsSection.getOriginalNetworkId(), tsSection.getTransportStreamId()]);

            TsUtil.updateSubTable(subTable, tsSection);

            if (!TsUtil.updateSection(subTable, tsSection)) {
                callback();
                return;
            }

            this.emit("sdt", tsSection);

            this.push(tsSection);
        } else if (tableId === 0x4A) {
            // Bouquet association
            const subTable = TsUtil.getNestedObject(this.versions, [tableId, tsSection.getBouquetId()]);

            TsUtil.updateSubTable(subTable, tsSection);

            if (!TsUtil.updateSection(subTable, tsSection)) {
                callback();
                return;
            }

            this.emit("bat", tsSection);

            this.push(tsSection);
        } else if (tableId >= 0x4E && tableId <= 0x6F) {
            // Event information
            const subTable = TsUtil.getNestedObject(this.versions, [tableId, tsSection.getOriginalNetworkId(), tsSection.getTransportStreamId(), tsSection.getServiceId()]);

            TsUtil.updateSubTable(subTable, tsSection);

            if (!TsUtil.updateSection(subTable, tsSection)) {
                callback();
                return;
            }

            this.emit("eit", tsSection);

            this.push(tsSection);
        } else if (tableId === 0x70) {
            // Time and date
            this.emit("tdt", tsSection);

            this.push(tsSection);
        } else if (tableId === 0x73) {
            // Time offset
            this.emit("tot", tsSection);

            this.push(tsSection);
        } else if (tableId === 0x7E) {
            // Discontinuity information
            this.emit("dit", tsSection);

            this.push(tsSection);
        } else if (tableId === 0x7F) {
            // Selection information
            const subTable = TsUtil.getNestedObject(this.versions, [tableId]);

            TsUtil.updateSubTable(subTable, tsSection);

            if (!TsUtil.updateSection(subTable, tsSection)) {
                callback();
                return;
            }

            this.emit("sit", tsSection);

            this.push(tsSection);
        } else if (tableId === 0x82) {
            // ECM
            const subTable = TsUtil.getNestedObject(this.versions, [tableId, tsSection.getTableIdExtension()]);

            TsUtil.updateSubTable(subTable, tsSection);

            if (!TsUtil.updateSection(subTable, tsSection)) {
                callback();
                return;
            }

            this.emit("ecm", tsSection);

            this.push(tsSection);
        } else if (tableId === 0x84) {
            // EMM
            this.emit("emm", tsSection);

            this.push(tsSection);
        } else if (tableId === 0x85) {
            // EMM message
            const subTable = TsUtil.getNestedObject(this.versions, [tableId, tsSection.getTableIdExtension()]);

            TsUtil.updateSubTable(subTable, tsSection);

            if (!TsUtil.updateSection(subTable, tsSection)) {
                callback();
                return;
            }

            this.emit("emmm", tsSection);

            this.push(tsSection);
        } else if (tableId === 0xC3) {
            // Software download trigger
            const subTable = TsUtil.getNestedObject(this.versions, [tableId, tsSection.getTableIdExtension()]);

            TsUtil.updateSubTable(subTable, tsSection);

            if (!TsUtil.updateSection(subTable, tsSection)) {
                callback();
                return;
            }

            this.emit("sdtt", tsSection);

            this.push(tsSection);
        } else if (tableId === 0xC8) {
            // Common data
            const subTable = TsUtil.getNestedObject(this.versions, [tableId, tsSection.getDownloadDataId()]);

            TsUtil.updateSubTable(subTable, tsSection);

            if (!TsUtil.updateSection(subTable, tsSection)) {
                callback();
                return;
            }

            this.emit("cdt", tsSection);

            this.push(tsSection);
        }

        callback();
    }

    reset() {
        this.versions = {};
    }
}

module.exports = TsSectionUpdater;
<commit_msg>Remove ecm emm update<commit_after>"use strict";

const TsBase = require("./base");
const TsUtil = require("./util");

class TsSectionUpdater extends TsBase {
    constructor() {
        super();

        this.versions = {};
    }

    _process(tsSection, callback) {
        const tableId = tsSection.getTableId();

        if (tableId === 0x00) {
            // Program association
            const subTable = TsUtil.getNestedObject(this.versions, [tableId, tsSection.getTransportStreamId()]);

            TsUtil.updateSubTable(subTable, tsSection);

            if (!TsUtil.updateSection(subTable, tsSection)) {
                callback();
                return;
            }

            this.emit("pat", tsSection);

            this.push(tsSection);
        } else if (tableId === 0x01) {
            // Conditional access
            const subTable = TsUtil.getNestedObject(this.versions, [tableId]);

            TsUtil.updateSubTable(subTable, tsSection);

            if (!TsUtil.updateSection(subTable, tsSection)) {
                callback();
                return;
            }

            this.emit("cat", tsSection);

            this.push(tsSection);
        } else if (tableId === 0x02) {
            // Program map
            const subTable = TsUtil.getNestedObject(this.versions, [tableId, tsSection.getProgramNumber()]);

            TsUtil.updateSubTable(subTable, tsSection);

            if (!TsUtil.updateSection(subTable, tsSection)) {
                callback();
                return;
            }

            this.emit("pmt", tsSection);

            this.push(tsSection);
        } else if (tableId >= 0x3A && tableId <= 0x3F) {
            // DSM-CC
            const subTable = TsUtil.getNestedObject(this.versions, [tableId, tsSection.getTableIdExtension()]);

            TsUtil.updateSubTable(subTable, tsSection);

            if (!TsUtil.updateSection(subTable, tsSection)) {
                callback();
                return;
            }

            this.emit("dsmcc", tsSection);

            this.push(tsSection);
        } else if (tableId === 0x40 || tableId === 0x41) {
            // Network information
            const subTable = TsUtil.getNestedObject(this.versions, [tableId, tsSection.getNetworkId()]);

            TsUtil.updateSubTable(subTable, tsSection);

            if (!TsUtil.updateSection(subTable, tsSection)) {
                callback();
                return;
            }

            this.emit("nit", tsSection);

            this.push(tsSection);
        } else if (tableId === 0x42 || tableId === 0x46) {
            // Service description
            const subTable = TsUtil.getNestedObject(this.versions, [tableId, tsSection.getOriginalNetworkId(), tsSection.getTransportStreamId()]);

            TsUtil.updateSubTable(subTable, tsSection);

            if (!TsUtil.updateSection(subTable, tsSection)) {
                callback();
                return;
            }

            this.emit("sdt", tsSection);

            this.push(tsSection);
        } else if (tableId === 0x4A) {
            // Bouquet association
            const subTable = TsUtil.getNestedObject(this.versions, [tableId, tsSection.getBouquetId()]);

            TsUtil.updateSubTable(subTable, tsSection);

            if (!TsUtil.updateSection(subTable, tsSection)) {
                callback();
                return;
            }

            this.emit("bat", tsSection);

            this.push(tsSection);
        } else if (tableId >= 0x4E && tableId <= 0x6F) {
            // Event information
            const subTable = TsUtil.getNestedObject(this.versions, [tableId, tsSection.getOriginalNetworkId(), tsSection.getTransportStreamId(), tsSection.getServiceId()]);

            TsUtil.updateSubTable(subTable, tsSection);

            if (!TsUtil.updateSection(subTable, tsSection)) {
                callback();
                return;
            }

            this.emit("eit", tsSection);

            this.push(tsSection);
        } else if (tableId === 0x70) {
            // Time and date
            this.emit("tdt", tsSection);

            this.push(tsSection);
        } else if (tableId === 0x73) {
            // Time offset
            this.emit("tot", tsSection);

            this.push(tsSection);
        } else if (tableId === 0x7E) {
            // Discontinuity information
            this.emit("dit", tsSection);

            this.push(tsSection);
        } else if (tableId === 0x7F) {
            // Selection information
            const subTable = TsUtil.getNestedObject(this.versions, [tableId]);

            TsUtil.updateSubTable(subTable, tsSection);

            if (!TsUtil.updateSection(subTable, tsSection)) {
                callback();
                return;
            }

            this.emit("sit", tsSection);

            this.push(tsSection);
        } else if (tableId === 0x82) {
            // ECM
            this.emit("ecm", tsSection);

            this.push(tsSection);
        } else if (tableId === 0x84) {
            // EMM
            this.emit("emm", tsSection);

            this.push(tsSection);
        } else if (tableId === 0x85) {
            // EMM message
            this.emit("emmm", tsSection);

            this.push(tsSection);
        } else if (tableId === 0xC3) {
            // Software download trigger
            const subTable = TsUtil.getNestedObject(this.versions, [tableId, tsSection.getTableIdExtension()]);

            TsUtil.updateSubTable(subTable, tsSection);

            if (!TsUtil.updateSection(subTable, tsSection)) {
                callback();
                return;
            }

            this.emit("sdtt", tsSection);

            this.push(tsSection);
        } else if (tableId === 0xC8) {
            // Common data
            const subTable = TsUtil.getNestedObject(this.versions, [tableId, tsSection.getDownloadDataId()]);

            TsUtil.updateSubTable(subTable, tsSection);

            if (!TsUtil.updateSection(subTable, tsSection)) {
                callback();
                return;
            }

            this.emit("cdt", tsSection);

            this.push(tsSection);
        }

        callback();
    }

    reset() {
        this.versions = {};
    }
}

module.exports = TsSectionUpdater;
<|endoftext|>


<commit_before>var WebSocket = require('ws');
var EventEmitter = require('events').EventEmitter;
var formatter = require('./formatter');
var Response = require('./response').Response;

var SCSocket = function (id, server, socket, authData) {
  var self = this;

  EventEmitter.call(this);

  this._localEvents = {
    'open': 1,
    'disconnect': 1,
    '_disconnect': 1,
    'message': 1,
    'error': 1,
    'raw': 1
  };

  this._autoAckEvents = {
    'ready': 1,
    'publish': 1
  };

  this.id = id;
  this.server = server;
  this.socket = socket;
  this.state = this.OPEN;

  this.request = this.socket.upgradeReq;
  this.remoteAddress = this.request.remoteAddress;

  this._cid = 1;
  this._callbackMap = {};

  this._authToken = authData.token || null;

  this.socket.on('error', function (err) {
    EventEmitter.prototype.emit.call(self, 'error', err);
  });

  this.socket.on('close', function (code, data) {
    self._onSCClose(code, data);
  });

  this._pingIntervalTicker = setInterval(this._sendPing.bind(this), this.server.pingInterval);
  this._resetPongTimeout();

  // Receive incoming raw messages
  this.socket.on('message', function (message, flags) {
    self._resetPongTimeout();

    EventEmitter.prototype.emit.call(self, 'message', message);

    // If not pong, we need to parse the message.
    // If it is pong, we don't need to do anything since it has already
    // served its purpose of resetting the pong timeout (see above).
    if (message != '2') {
      var obj = formatter.parse(message);

      if (obj == null) {
        var err = new Error('Received empty message');
        EventEmitter.prototype.emit.call(self, 'error', err);
      } else if (obj.event) {
        if (self._localEvents[obj.event] == null) {
          var response = new Response(self, obj.cid);
          self.server.verifyInboundEvent(self, obj.event, obj.data, function (err) {
            if (err) {
              response.error(err);
            } else {
              if (self._autoAckEvents[obj.event]) {
                response.end();
                EventEmitter.prototype.emit.call(self, obj.event, obj.data);
              } else {
                EventEmitter.prototype.emit.call(self, obj.event, obj.data, response.callback.bind(response));
              }
            }
          });
        }
      } else if (obj.rid != null) {
        // If incoming message is a response to a previously sent message
        var ret = self._callbackMap[obj.rid];
        if (ret) {
          clearTimeout(ret.timeout);
          delete self._callbackMap[obj.rid];
          ret.callback(obj.error, obj.data);
        }
      } else {
        if (obj.disconnect) {
          self._onSCClose(obj.code, obj.data);
        } else {
          // The last remaining case is to treat the data as raw
          EventEmitter.prototype.emit.call(self, 'raw', message);
        }
      }
    }
  });

  // Emit initial status to client
  this.emit('ready', {
    id: this.id,
    isAuthenticated: !!this._authToken,
    authError: authData.error,
    pingTimeout: this.server.pingTimeout,
    deliveryTimeout: this.server.deliveryTimeout
  });
};

SCSocket.prototype = Object.create(EventEmitter.prototype);

SCSocket.CONNECTING = SCSocket.prototype.CONNECTING = 'connecting';
SCSocket.OPEN = SCSocket.prototype.OPEN = 'open';
SCSocket.CLOSED = SCSocket.prototype.CLOSED = 'closed';

SCSocket.ignoreStatuses = {
  1000: 'Socket closed normally',
  1001: 'Socket hung up'
};

SCSocket.errorStatuses = {
  1002: 'A WebSocket protocol error was encountered',
  1003: 'Server terminated socket because it received invalid data',
  1005: 'Socket closed without status code',
  1006: 'Socket hung up',
  1007: 'Message format was incorrect',
  1008: 'Encountered a policy violation',
  1009: 'Message was too big to process',
  1010: 'Client ended the connection because the server did not comply with extension requirements',
  1011: 'Server encountered an unexpected fatal condition',
  4000: 'Server ping timed out',
  4001: 'Client pong timed out',
  4002: "Client socket initialization timed out - Client did not receive a 'ready' event"
};

SCSocket.prototype._sendPing = function () {
  if (this.state == this.OPEN) {
    this.send('1');
  }
};

SCSocket.prototype._resetPongTimeout = function () {
  var self = this;

  clearTimeout(this._pingTimeoutTicker);
  this._pingTimeoutTicker = setTimeout(function() {
    self.socket.close(4001);
    self._onSCClose(4001);
  }, this.server.pingTimeout);
};

SCSocket.prototype._nextCallId = function () {
  return this._cid++;
};

SCSocket.prototype.getState = function () {
  return this.state;
};

SCSocket.prototype.getBytesReceived = function () {
  return this.socket.bytesReceived;
};

SCSocket.prototype._onSCClose = function (code, data) {
  clearInterval(this._pingIntervalTicker);
  clearTimeout(this._pingTimeoutTicker);

  if (this.state != this.CLOSED) {
    this.state = this.CLOSED;

    // Private disconnect event for internal use only
    EventEmitter.prototype.emit.call(this, '_disconnect', code, data);
    EventEmitter.prototype.emit.call(this, 'disconnect', code, data);

    if (!SCSocket.ignoreStatuses[code]) {
      var err = new Error(SCSocket.errorStatuses[code] || 'Socket connection failed for unknown reasons');
      err.code = code;
      EventEmitter.prototype.emit.call(this, 'error', err);
    }
  }
};

SCSocket.prototype.disconnect = function (code, data) {
  code = code || 1000;

  if (this.state == this.OPEN) {
    this.sendObject({
      disconnect: 1,
      code: code,
      data: data
    });
    this.socket.close(code);
    this._onSCClose(code, data);
  }
};

SCSocket.prototype.terminate = function () {
  this.socket.terminate();
};

SCSocket.prototype.send = function (data, options) {
  var self = this;

  this.socket.send(data, options, function (err) {
    if (err) {
      self._onSCClose(1006, err.toString());
    }
  });
};

SCSocket.prototype.sendObject = function (object) {
  this.send(formatter.stringify(object));
};

SCSocket.prototype.emit = function (event, data, callback) {
  var self = this;

  if (this._localEvents[event] == null) {
    this.server.verifyOutboundEvent(this, event, data, function (err) {
      var eventObject = {
        event: event
      };
      if (data !== undefined) {
        eventObject.data = data;
      }
      eventObject.cid = self._nextCallId();

      if (err) {
        callback && callback(err, eventObject);
      } else {
        if (callback) {
          var timeout = setTimeout(function () {
            var error = new Error("Event response for '" + event + "' timed out");
            error.type = 'timeout';

            delete self._callbackMap[eventObject.cid];
            callback(error, eventObject);
          }, self.server.ackTimeout);

          self._callbackMap[eventObject.cid] = {callback: callback, timeout: timeout};
        }
        self.sendObject(eventObject);
      }
    });
  } else {
    EventEmitter.prototype.emit.call(this, event, data);
  }
};

SCSocket.prototype.setAuthToken = function (data, options, callback) {
  this._authToken = data;
  var signedToken = this.server.auth.signToken(data, options);
  this.emit('setAuthToken', signedToken, callback);
};

SCSocket.prototype.getAuthToken = function () {
  return this._authToken;
};

SCSocket.prototype.removeAuthToken = function (callback) {
  this._authToken = null;
  this.emit('removeAuthToken', null, callback);
};

module.exports = SCSocket;
<commit_msg>OCD call ordering<commit_after>var WebSocket = require('ws');
var EventEmitter = require('events').EventEmitter;
var formatter = require('./formatter');
var Response = require('./response').Response;

var SCSocket = function (id, server, socket, authData) {
  var self = this;

  EventEmitter.call(this);

  this._localEvents = {
    'open': 1,
    'disconnect': 1,
    '_disconnect': 1,
    'message': 1,
    'error': 1,
    'raw': 1
  };

  this._autoAckEvents = {
    'ready': 1,
    'publish': 1
  };

  this.id = id;
  this.server = server;
  this.socket = socket;
  this.state = this.OPEN;

  this.request = this.socket.upgradeReq;
  this.remoteAddress = this.request.remoteAddress;

  this._cid = 1;
  this._callbackMap = {};

  this._authToken = authData.token || null;

  this.socket.on('error', function (err) {
    EventEmitter.prototype.emit.call(self, 'error', err);
  });

  this.socket.on('close', function (code, data) {
    self._onSCClose(code, data);
  });

  this._pingIntervalTicker = setInterval(this._sendPing.bind(this), this.server.pingInterval);
  this._resetPongTimeout();

  // Receive incoming raw messages
  this.socket.on('message', function (message, flags) {
    self._resetPongTimeout();

    EventEmitter.prototype.emit.call(self, 'message', message);

    // If not pong, we need to parse the message.
    // If it is pong, we don't need to do anything since it has already
    // served its purpose of resetting the pong timeout (see above).
    if (message != '2') {
      var obj = formatter.parse(message);

      if (obj == null) {
        var err = new Error('Received empty message');
        EventEmitter.prototype.emit.call(self, 'error', err);
      } else if (obj.event) {
        if (self._localEvents[obj.event] == null) {
          var response = new Response(self, obj.cid);
          self.server.verifyInboundEvent(self, obj.event, obj.data, function (err) {
            if (err) {
              response.error(err);
            } else {
              if (self._autoAckEvents[obj.event]) {
                response.end();
                EventEmitter.prototype.emit.call(self, obj.event, obj.data);
              } else {
                EventEmitter.prototype.emit.call(self, obj.event, obj.data, response.callback.bind(response));
              }
            }
          });
        }
      } else if (obj.rid != null) {
        // If incoming message is a response to a previously sent message
        var ret = self._callbackMap[obj.rid];
        if (ret) {
          clearTimeout(ret.timeout);
          delete self._callbackMap[obj.rid];
          ret.callback(obj.error, obj.data);
        }
      } else {
        if (obj.disconnect) {
          self._onSCClose(obj.code, obj.data);
        } else {
          // The last remaining case is to treat the data as raw
          EventEmitter.prototype.emit.call(self, 'raw', message);
        }
      }
    }
  });

  // Emit initial status to client
  this.emit('ready', {
    id: this.id,
    isAuthenticated: !!this._authToken,
    authError: authData.error,
    pingTimeout: this.server.pingTimeout,
    deliveryTimeout: this.server.deliveryTimeout
  });
};

SCSocket.prototype = Object.create(EventEmitter.prototype);

SCSocket.CONNECTING = SCSocket.prototype.CONNECTING = 'connecting';
SCSocket.OPEN = SCSocket.prototype.OPEN = 'open';
SCSocket.CLOSED = SCSocket.prototype.CLOSED = 'closed';

SCSocket.ignoreStatuses = {
  1000: 'Socket closed normally',
  1001: 'Socket hung up'
};

SCSocket.errorStatuses = {
  1002: 'A WebSocket protocol error was encountered',
  1003: 'Server terminated socket because it received invalid data',
  1005: 'Socket closed without status code',
  1006: 'Socket hung up',
  1007: 'Message format was incorrect',
  1008: 'Encountered a policy violation',
  1009: 'Message was too big to process',
  1010: 'Client ended the connection because the server did not comply with extension requirements',
  1011: 'Server encountered an unexpected fatal condition',
  4000: 'Server ping timed out',
  4001: 'Client pong timed out',
  4002: "Client socket initialization timed out - Client did not receive a 'ready' event"
};

SCSocket.prototype._sendPing = function () {
  if (this.state == this.OPEN) {
    this.send('1');
  }
};

SCSocket.prototype._resetPongTimeout = function () {
  var self = this;

  clearTimeout(this._pingTimeoutTicker);
  this._pingTimeoutTicker = setTimeout(function() {
    self._onSCClose(4001);
    self.socket.close(4001);
  }, this.server.pingTimeout);
};

SCSocket.prototype._nextCallId = function () {
  return this._cid++;
};

SCSocket.prototype.getState = function () {
  return this.state;
};

SCSocket.prototype.getBytesReceived = function () {
  return this.socket.bytesReceived;
};

SCSocket.prototype._onSCClose = function (code, data) {
  clearInterval(this._pingIntervalTicker);
  clearTimeout(this._pingTimeoutTicker);

  if (this.state != this.CLOSED) {
    this.state = this.CLOSED;

    // Private disconnect event for internal use only
    EventEmitter.prototype.emit.call(this, '_disconnect', code, data);
    EventEmitter.prototype.emit.call(this, 'disconnect', code, data);

    if (!SCSocket.ignoreStatuses[code]) {
      var err = new Error(SCSocket.errorStatuses[code] || 'Socket connection failed for unknown reasons');
      err.code = code;
      EventEmitter.prototype.emit.call(this, 'error', err);
    }
  }
};

SCSocket.prototype.disconnect = function (code, data) {
  code = code || 1000;

  if (this.state == this.OPEN) {
    this.sendObject({
      disconnect: 1,
      code: code,
      data: data
    });
    this._onSCClose(code, data);
    this.socket.close(code);
  }
};

SCSocket.prototype.terminate = function () {
  this.socket.terminate();
};

SCSocket.prototype.send = function (data, options) {
  var self = this;

  this.socket.send(data, options, function (err) {
    if (err) {
      self._onSCClose(1006, err.toString());
    }
  });
};

SCSocket.prototype.sendObject = function (object) {
  this.send(formatter.stringify(object));
};

SCSocket.prototype.emit = function (event, data, callback) {
  var self = this;

  if (this._localEvents[event] == null) {
    this.server.verifyOutboundEvent(this, event, data, function (err) {
      var eventObject = {
        event: event
      };
      if (data !== undefined) {
        eventObject.data = data;
      }
      eventObject.cid = self._nextCallId();

      if (err) {
        callback && callback(err, eventObject);
      } else {
        if (callback) {
          var timeout = setTimeout(function () {
            var error = new Error("Event response for '" + event + "' timed out");
            error.type = 'timeout';

            delete self._callbackMap[eventObject.cid];
            callback(error, eventObject);
          }, self.server.ackTimeout);

          self._callbackMap[eventObject.cid] = {callback: callback, timeout: timeout};
        }
        self.sendObject(eventObject);
      }
    });
  } else {
    EventEmitter.prototype.emit.call(this, event, data);
  }
};

SCSocket.prototype.setAuthToken = function (data, options, callback) {
  this._authToken = data;
  var signedToken = this.server.auth.signToken(data, options);
  this.emit('setAuthToken', signedToken, callback);
};

SCSocket.prototype.getAuthToken = function () {
  return this._authToken;
};

SCSocket.prototype.removeAuthToken = function (callback) {
  this._authToken = null;
  this.emit('removeAuthToken', null, callback);
};

module.exports = SCSocket;
<|endoftext|>


<commit_before>// serverAndClient.js
// globals for client and server

if (Meteor.isClient) {
    ctx = null; // The global client state
    layers = {}; // contains almost all information about attributes
    googlemap = null; // our main googlemap instance
    colormaps = {};
}

if (Meteor.isServer) {
    var process = Npm.require('process');
    Meteor.startup(function () {
        process.env.MAIL_URL = 'smtp://hexmap%40ucsc.edu:Juno6666@smtp.gmail.com:587';
    });
}

// Some global settings available to server and client.
DEV = Meteor.settings.public.DEV;  // true if you want development functionality, false if not
URL_BASE = Meteor.settings.public.URL_BASE;
VIEW_DIR = Meteor.settings.public.VIEW_DIR;
LAYOUT_INPUT_DIR = Meteor.settings.public.LAYOUT_INPUT_DIR;
FEATURE_SPACE_DIR = Meteor.settings.public.FEATURE_SPACE_DIR;

// TODO test logic should not be in production code
TEST_DATA_DIR = '/Users/swat/dev/hexagram/tests/pyUnittest/testData/';
TEMP_DIR = '/tmp/';

// accessing remote collections
//var mongo_url = 'mongodb://127.0.0.1:27017/dev'
//var database = new MongoInternals.RemoteCollectionDriver(mongo_url);
//Bookmarks = new Mongo.Collection('bookmarks', { _driver: database });

Bookmarks = new Mongo.Collection('bookmarks');

/*
// Deny all client-side updates to user documents
Meteor.users.deny({
  update() { return true; }
});
*/
<commit_msg>added ADMIN_EMAIL<commit_after>// serverAndClient.js
// globals for client and server

if (Meteor.isClient) {
    ctx = null; // The global client state
    layers = {}; // contains almost all information about attributes
    googlemap = null; // our main googlemap instance
    colormaps = {};
}

if (Meteor.isServer) {
    var process = Npm.require('process');
    Meteor.startup(function () {
        process.env.MAIL_URL = 'smtp://hexmap%40ucsc.edu:Juno6666@smtp.gmail.com:587';
    });
}

// Some global settings available to server and client.
DEV = Meteor.settings.public.DEV;  // true if you want development functionality, false if not
URL_BASE = Meteor.settings.public.URL_BASE;
VIEW_DIR = Meteor.settings.public.VIEW_DIR;
LAYOUT_INPUT_DIR = Meteor.settings.public.LAYOUT_INPUT_DIR;
FEATURE_SPACE_DIR = Meteor.settings.public.FEATURE_SPACE_DIR;
ADMIN_EMAIL = Meteor.settings.public.ADMIN_EMAIL;

// TODO test logic should not be in production code
TEST_DATA_DIR = '/Users/swat/dev/hexagram/tests/pyUnittest/testData/';
TEMP_DIR = '/tmp/';

// accessing remote collections
//var mongo_url = 'mongodb://127.0.0.1:27017/dev'
//var database = new MongoInternals.RemoteCollectionDriver(mongo_url);
//Bookmarks = new Mongo.Collection('bookmarks', { _driver: database });

Bookmarks = new Mongo.Collection('bookmarks');

/*
// Deny all client-side updates to user documents
Meteor.users.deny({
  update() { return true; }
});
*/
<|endoftext|>