<commit_before>var bigAssApi = require("BigAssFansAPI");
bigAssApi.logging = false;

var Service, Characteristic;

module.exports = function(homebridge) {
  // Platform Accessory must be created from PlatformAccessory Constructor
  PlatformAccessory = homebridge.platformAccessory;
  Service = homebridge.hap.Service;
  Characteristic = homebridge.hap.Characteristic;
  UUIDGen = homebridge.hap.uuid;

  homebridge.registerPlatform("homebridge-bigAssFans", "BigAssFans", BigAssFansPlatform, true);
  homebridge.registerAccessory("homebridge-bigAssFan", "BigAssFan", BigAssFanAccessory);
}

function BigAssFansPlatform(log, config, api) {
  // If config is not specified do not attempt to load platform
  // or else it will eat the port.
  if (!config) {
    return;
  }
  log("Big Ass Fans Platform Init");
  var platform = this;
  this.log = log;
  this.config = config;
  this.accessories = [];
  this.accessoriesHashed = {};
  this.numberOfFans = config ? (config.fan_count || 1) : 1;
  this.fanMaster = new bigAssApi.FanMaster(this.numberOfFans);

  this.fanMaster.onFanFullyUpdated = function(myBigAss){
    platform.addAccessory(myBigAss);
  }

  if (api) {
      // Save the API object as plugin needs to register new accessory via this object.
      this.api = api;

      // Listen to event "didFinishLaunching", this means homebridge already finished loading cached accessories
      // Platform Plugin should only register new accessory that doesn't exist in homebridge after this event.
      // Or start discover new accessories
      this.api.on('didFinishLaunching', function() {
        platform.log("DidFinishLaunching");
      }.bind(this));
  }
}

// Function invoked when homebridge tries to restore cached accessory
// Developer can configure accessory at here (like setup event handler)
// Update current value
BigAssFansPlatform.prototype.configureAccessory = function(accessory) {
  this.log(accessory.displayName, "Configure Accessory", accessory.UUID);
  var platform = this;

  // set the accessory to reachable if plugin can currently process the accessory
  // otherwise set to false and update the reachability later by invoking
  // accessory.updateReachability()
  accessory.reachable = false;

  accessory.on('identify', function(paired, callback) {
    platform.log(accessory.displayName, "Identify!!!");
    callback();
  });

  this.accessoriesHashed[accessory.UUID] = accessory;
}

// Sample function to show how developer can add accessory dynamically from outside event
BigAssFansPlatform.prototype.addAccessory = function(theFan) {
  var platform = this;
  var newAccessory;
  var uuid;

  var doctoredConfig = {
    "name"               : theFan.name,
    "fan_name"           : theFan.name,
    "fan_id"             : theFan.id,
    "fan_ip_address"     : theFan.address,
    "light_on"           : platform.config.light_on,
    "fan_on"             : platform.config.fan_on,
    "homekit_fan_name"   : platform.config.homekit_fan_name,
    "homekit_light_name" : platform.config.homekit_light_name,
    "fan_master"         : theFan.master,
  }

  //Check if we have a cached accessory and link it to runtime fan instance, or create new service
  uuid = UUIDGen.generate(theFan.name);

  if (platform.accessoriesHashed[uuid]) {
    newAccessory = platform.accessoriesHashed[uuid];
  } else {
    newAccessory = new PlatformAccessory(theFan.name, uuid);
  }

  var newInnerFanAccessory = new BigAssFanAccessory(platform.log, doctoredConfig, newAccessory);

  // Adds "identify" functionality
  newAccessory.on('identify', function(paired, callback) {
    platform.log(newAccessory.displayName, "Identified fan (homekit setup)");
    callback();
  });

  // Plugin can save context on accessory
  // To help restore accessory in configureAccessory()
  newAccessory.context.doctoredConfig = this.fan_ip_address;

  this.accessories.push(newAccessory);
  if (!platform.accessoriesHashed[uuid]) {
    this.api.registerPlatformAccessories("homebridge-bigAssFans", "BigAssFans", [newAccessory]);
  }
}

// Sample function to show how developer can remove accessory dynamically from outside event
BigAssFansPlatform.prototype.removeAccessory = function() {
  this.log("Remove Accessory");
  this.api.unregisterPlatformAccessories("homebridge-bigAssFans", "BigAssFans", this.accessories);

  this.accessories = [];
}

function BigAssFanAccessory(log, config, existingAccessory) {
  this.log              = log;
  this.name             = config["name"];
  this.fanName          = config["fan_name"];        // TODO: Allow this to be null
  this.fanID            = config["fan_id"];
  this.fanIPAddress     = config["fan_ip_address"];  // Can be null - resorts to broadcasting
  this.lightOn          = config["light_on"];        // Can be null - default is below
  this.fanOn            = config["fan_on"];          // Can be null - default is below
  this.homekitFanName   = config["homekit_fan_name"]
  this.homekitLightName = config["homekit_light_name"]
  this.fanMaster        = config["fan_master"]       // Can NOT be entered by user

  // Set defaults
  var setDefault = function(property, value) {
    if (!this[property]) {this[property] = value}
  }.bind(this);

  setDefault("fanIPAddress", "255.255.255.255");
  setDefault("lightOn", 16);
  setDefault("fanOn", 3);

  setDefault("name", this.fanName);
  setDefault("homekitFanName", this.name + " Fan");
  setDefault("homekitLightName", this.name + " Fan Light");
  setDefault("homekitOccupancyName", this.name + " Occupancy Sensor");
  // Don't scan for any fans since we know the exact address of the fan (faster!)
  // TODO: Make fan_id optional and do the scan for the user
  if (!this.fanMaster) {
    this.fanMaster = new bigAssApi.FanMaster(this.numberOfFans);
  }

  // Put in exact information for the fan you're trying to reach
  this.myBigAss = new bigAssApi.BigAssFan(this.fanName, this.fanID, this.fanIPAddress, this.fanMaster);

  // this.myBigAss.updateAll();

  var setCharacteristicOnService = function(service,
                                            characteristic,
                                            propertyToWrap,
                                            subProperty,
                                            getOutputMapping,
                                            setOutputMapping) {

    var thisChar = service.getCharacteristic(characteristic)

    if (getOutputMapping) {
      thisChar.on('get', this.getStateFactory(propertyToWrap,
                                              subProperty,
                                              getOutputMapping).bind(this));

      // Register for updates outside of the homekit system
      this.myBigAss[propertyToWrap].registerUpdateCallback(subProperty, function(newValue) {
        if (thisChar.emit) {
          // Emit this change to the homekit system
          // oldValue : Grabs the old cached value for this characterisitic
          // newValue : The value we just recieved
          // context  : Gives context so that whoever requested the update doesn't recieve it.
          //            In this case we need everyone to get the update
          thisChar.emit('change', {
              oldValue:thisChar.value,
              newValue:getOutputMapping(newValue),
              context:null });
        }
      });
    }

    if (setOutputMapping) {
      thisChar.on('set', this.setStateFactory(propertyToWrap,
                                              subProperty,
                                              setOutputMapping).bind(this));
    }

  }.bind(this);

  /********************************************
   * Wrappers for various get and set functions
   ********************************************/

  var passThroughWrapper = function(value) {
    return value;
  }

  var setScalingWrapper = function(maxValue) {
    return function(value) {
      return Math.round(value * maxValue / 100);
    }
  }

  var getScalingWrapper = function(maxValue) {
    return function(value) {
      return Math.round(value * 100 / maxValue);
    }
  }

  var boolGetWrapper = function(value) {
    return value > 0;
  }

  var lightSetWrapper = function(value) {
    // We define that returning null will ignore the command
    // For some reason homekit likes to send extraneous "On" commands
    if (value && this.myBigAss.light.brightness > 0) {
      return null;
    }
    return (value ? this.lightOn : 0);
  }.bind(this)

  var fanSetWrapper = function(value) {
    // We define that returning null will ignore the command
    // For some reason homekit likes to send extraneous "On" commands
    if (value && this.myBigAss.fan.speed > 0) {
      return null;
    }
    return (value ? this.fanOn : 0);
  }.bind(this)

  var fanRotationSetWrapper = function(value) {
    return value == Characteristic.RotationDirection.COUNTER_CLOCKWISE;
  }

  var fanRotationGetWrapper = function(value) {
    return (value ? Characteristic.RotationDirection.COUNTER_CLOCKWISE : Characteristic.RotationDirection.CLOCKWISE);
  }

  var occupancyGetWrapper = function(value) {
    return (value ? Characteristic.OccupancyDetected.OCCUPANCY_DETECTED : Characteristic.OccupancyDetected.OCCUPANCY_NOT_DETECTED);
  }

  var lightMaxBrightness = this.myBigAss.light.max ? this.myBigAss.light.max : 16;
  var fanMaxSpeed        = this.myBigAss.fan.max ? this.myBigAss.fan.max : 7;

  var existingLightBulbService;
  if (existingAccessory){
    existingLightBulbService = existingAccessory.getService(this.homekitLightName);
  }
  this.lightService = existingLightBulbService || new Service.Lightbulb(this.homekitLightName);

  setCharacteristicOnService(this.lightService, Characteristic.On,
                             "light", "brightness",
                             boolGetWrapper, lightSetWrapper)

  setCharacteristicOnService(this.lightService, Characteristic.Brightness,
                             "light", "brightness",
                             getScalingWrapper(lightMaxBrightness), setScalingWrapper(lightMaxBrightness))

  if (existingAccessory && !existingLightBulbService){
    existingAccessory.addService(this.lightService);
  }
  var existingFanService;
  if (existingAccessory){
    existingFanService = existingAccessory.getService(this.homekitFanName);
  }
  this.fanService = existingFanService || new Service.Fan(this.homekitFanName);

  setCharacteristicOnService(this.fanService, Characteristic.On,
                             "fan", "speed",
                             boolGetWrapper, fanSetWrapper)

  setCharacteristicOnService(this.fanService, Characteristic.RotationDirection,
                             "fan", "isSpinningForwards",
                             fanRotationGetWrapper, fanRotationSetWrapper)

  setCharacteristicOnService(this.fanService, Characteristic.RotationSpeed,
                             "fan", "speed",
                             getScalingWrapper(fanMaxSpeed), setScalingWrapper(fanMaxSpeed))
  if (existingAccessory && !existingFanService){
    existingAccessory.addService(this.fanService);
  }
/*
  var existingOccupancyService;
  if (existingAccessory){
    existingOccupancyService = existingAccessory.getService(this.homekitOccupancyName);
  }

  this.occupancyService = existingOccupancyService || new Service.OccupancySensor(this.homekitOccupancyName);

  setCharacteristicOnService(this.occupancyService, Characteristic.OccupancyDetected,
                              "room", "isOccupied",
                              occupancyGetWrapper, null)

  if (existingAccessory && !existingOccupancyService){
    existingAccessory.addService(this.occupancyService);
  }
*/
  this.getServices = function() {
    return [this.lightService, this.fanService]; //this.occupancyService];
  }
  if (existingAccessory){
    existingAccessory.updateReachability(true);
  }
}

BigAssFanAccessory.prototype.getStateFactory = function(propertyToWrap, subProperty, outputMapping) {
  return function(callback) {
    this.myBigAss[propertyToWrap].update(subProperty, function(err, value) {
      var returnVal = outputMapping(value);
      callback(err, returnVal);
    });
  }
}

BigAssFanAccessory.prototype.setStateFactory = function(propertyToWrap, subProperty, outputMapping) {
  return function(state, callback) {
    var valToSet = outputMapping(state)
    if (valToSet != null) {
      this.myBigAss[propertyToWrap].setProperty(subProperty, valToSet, function(err) {
        callback(err);
      });
    } else {
      // If null is returned, ignore the command
      callback(null);
    }
  }
}

<commit_msg>Removed second identify callback causing crash<commit_after>var bigAssApi = require("BigAssFansAPI");
bigAssApi.logging = false;

var Service, Characteristic;

module.exports = function(homebridge) {
  // Platform Accessory must be created from PlatformAccessory Constructor
  PlatformAccessory = homebridge.platformAccessory;
  Service = homebridge.hap.Service;
  Characteristic = homebridge.hap.Characteristic;
  UUIDGen = homebridge.hap.uuid;

  homebridge.registerPlatform("homebridge-bigAssFans", "BigAssFans", BigAssFansPlatform, true);
  homebridge.registerAccessory("homebridge-bigAssFan", "BigAssFan", BigAssFanAccessory);
}

function BigAssFansPlatform(log, config, api) {
  // If config is not specified do not attempt to load platform
  // or else it will eat the port.
  if (!config) {
    return;
  }
  log("Big Ass Fans Platform Init");
  var platform = this;
  this.log = log;
  this.config = config;
  this.accessories = [];
  this.accessoriesHashed = {};
  this.numberOfFans = config ? (config.fan_count || 1) : 1;
  this.fanMaster = new bigAssApi.FanMaster(this.numberOfFans);

  this.fanMaster.onFanFullyUpdated = function(myBigAss){
    platform.addAccessory(myBigAss);
  }

  if (api) {
      // Save the API object as plugin needs to register new accessory via this object.
      this.api = api;

      // Listen to event "didFinishLaunching", this means homebridge already finished loading cached accessories
      // Platform Plugin should only register new accessory that doesn't exist in homebridge after this event.
      // Or start discover new accessories
      this.api.on('didFinishLaunching', function() {
        platform.log("DidFinishLaunching");
      }.bind(this));
  }
}

// Function invoked when homebridge tries to restore cached accessory
// Developer can configure accessory at here (like setup event handler)
// Update current value
BigAssFansPlatform.prototype.configureAccessory = function(accessory) {
  this.log(accessory.displayName, "Configure Accessory", accessory.UUID);
  var platform = this;

  // set the accessory to reachable if plugin can currently process the accessory
  // otherwise set to false and update the reachability later by invoking
  // accessory.updateReachability()
  accessory.reachable = false;

  this.accessoriesHashed[accessory.UUID] = accessory;
}

// Sample function to show how developer can add accessory dynamically from outside event
BigAssFansPlatform.prototype.addAccessory = function(theFan) {
  var platform = this;
  var newAccessory;
  var uuid;

  var doctoredConfig = {
    "name"               : theFan.name,
    "fan_name"           : theFan.name,
    "fan_id"             : theFan.id,
    "fan_ip_address"     : theFan.address,
    "light_on"           : platform.config.light_on,
    "fan_on"             : platform.config.fan_on,
    "homekit_fan_name"   : platform.config.homekit_fan_name,
    "homekit_light_name" : platform.config.homekit_light_name,
    "fan_master"         : theFan.master,
  }

  //Check if we have a cached accessory and link it to runtime fan instance, or create new service
  uuid = UUIDGen.generate(theFan.name);

  if (platform.accessoriesHashed[uuid]) {
    newAccessory = platform.accessoriesHashed[uuid];
  } else {
    newAccessory = new PlatformAccessory(theFan.name, uuid);
  }

  var newInnerFanAccessory = new BigAssFanAccessory(platform.log, doctoredConfig, newAccessory);

  // Adds "identify" functionality
  newAccessory.on('identify', function(paired, callback) {
    platform.log(newAccessory.displayName, "Identified fan (homekit setup)");
    callback();
  });

  // Plugin can save context on accessory
  // To help restore accessory in configureAccessory()
  newAccessory.context.doctoredConfig = this.fan_ip_address;

  this.accessories.push(newAccessory);
  if (!platform.accessoriesHashed[uuid]) {
    this.api.registerPlatformAccessories("homebridge-bigAssFans", "BigAssFans", [newAccessory]);
  }
}

// Sample function to show how developer can remove accessory dynamically from outside event
BigAssFansPlatform.prototype.removeAccessory = function() {
  this.log("Remove Accessory");
  this.api.unregisterPlatformAccessories("homebridge-bigAssFans", "BigAssFans", this.accessories);

  this.accessories = [];
}

function BigAssFanAccessory(log, config, existingAccessory) {
  this.log              = log;
  this.name             = config["name"];
  this.fanName          = config["fan_name"];        // TODO: Allow this to be null
  this.fanID            = config["fan_id"];
  this.fanIPAddress     = config["fan_ip_address"];  // Can be null - resorts to broadcasting
  this.lightOn          = config["light_on"];        // Can be null - default is below
  this.fanOn            = config["fan_on"];          // Can be null - default is below
  this.homekitFanName   = config["homekit_fan_name"]
  this.homekitLightName = config["homekit_light_name"]
  this.fanMaster        = config["fan_master"]       // Can NOT be entered by user

  // Set defaults
  var setDefault = function(property, value) {
    if (!this[property]) {this[property] = value}
  }.bind(this);

  setDefault("fanIPAddress", "255.255.255.255");
  setDefault("lightOn", 16);
  setDefault("fanOn", 3);

  setDefault("name", this.fanName);
  setDefault("homekitFanName", this.name + " Fan");
  setDefault("homekitLightName", this.name + " Fan Light");
  setDefault("homekitOccupancyName", this.name + " Occupancy Sensor");
  // Don't scan for any fans since we know the exact address of the fan (faster!)
  // TODO: Make fan_id optional and do the scan for the user
  if (!this.fanMaster) {
    this.fanMaster = new bigAssApi.FanMaster(this.numberOfFans);
  }

  // Put in exact information for the fan you're trying to reach
  this.myBigAss = new bigAssApi.BigAssFan(this.fanName, this.fanID, this.fanIPAddress, this.fanMaster);

  // this.myBigAss.updateAll();

  var setCharacteristicOnService = function(service,
                                            characteristic,
                                            propertyToWrap,
                                            subProperty,
                                            getOutputMapping,
                                            setOutputMapping) {

    var thisChar = service.getCharacteristic(characteristic)

    if (getOutputMapping) {
      thisChar.on('get', this.getStateFactory(propertyToWrap,
                                              subProperty,
                                              getOutputMapping).bind(this));

      // Register for updates outside of the homekit system
      this.myBigAss[propertyToWrap].registerUpdateCallback(subProperty, function(newValue) {
        if (thisChar.emit) {
          // Emit this change to the homekit system
          // oldValue : Grabs the old cached value for this characterisitic
          // newValue : The value we just recieved
          // context  : Gives context so that whoever requested the update doesn't recieve it.
          //            In this case we need everyone to get the update
          thisChar.emit('change', {
              oldValue:thisChar.value,
              newValue:getOutputMapping(newValue),
              context:null });
        }
      });
    }

    if (setOutputMapping) {
      thisChar.on('set', this.setStateFactory(propertyToWrap,
                                              subProperty,
                                              setOutputMapping).bind(this));
    }

  }.bind(this);

  /********************************************
   * Wrappers for various get and set functions
   ********************************************/

  var passThroughWrapper = function(value) {
    return value;
  }

  var setScalingWrapper = function(maxValue) {
    return function(value) {
      return Math.round(value * maxValue / 100);
    }
  }

  var getScalingWrapper = function(maxValue) {
    return function(value) {
      return Math.round(value * 100 / maxValue);
    }
  }

  var boolGetWrapper = function(value) {
    return value > 0;
  }

  var lightSetWrapper = function(value) {
    // We define that returning null will ignore the command
    // For some reason homekit likes to send extraneous "On" commands
    if (value && this.myBigAss.light.brightness > 0) {
      return null;
    }
    return (value ? this.lightOn : 0);
  }.bind(this)

  var fanSetWrapper = function(value) {
    // We define that returning null will ignore the command
    // For some reason homekit likes to send extraneous "On" commands
    if (value && this.myBigAss.fan.speed > 0) {
      return null;
    }
    return (value ? this.fanOn : 0);
  }.bind(this)

  var fanRotationSetWrapper = function(value) {
    return value == Characteristic.RotationDirection.COUNTER_CLOCKWISE;
  }

  var fanRotationGetWrapper = function(value) {
    return (value ? Characteristic.RotationDirection.COUNTER_CLOCKWISE : Characteristic.RotationDirection.CLOCKWISE);
  }

  var occupancyGetWrapper = function(value) {
    return (value ? Characteristic.OccupancyDetected.OCCUPANCY_DETECTED : Characteristic.OccupancyDetected.OCCUPANCY_NOT_DETECTED);
  }

  var lightMaxBrightness = this.myBigAss.light.max ? this.myBigAss.light.max : 16;
  var fanMaxSpeed        = this.myBigAss.fan.max ? this.myBigAss.fan.max : 7;

  var existingLightBulbService;
  if (existingAccessory){
    existingLightBulbService = existingAccessory.getService(this.homekitLightName);
  }
  this.lightService = existingLightBulbService || new Service.Lightbulb(this.homekitLightName);

  setCharacteristicOnService(this.lightService, Characteristic.On,
                             "light", "brightness",
                             boolGetWrapper, lightSetWrapper)

  setCharacteristicOnService(this.lightService, Characteristic.Brightness,
                             "light", "brightness",
                             getScalingWrapper(lightMaxBrightness), setScalingWrapper(lightMaxBrightness))

  if (existingAccessory && !existingLightBulbService){
    existingAccessory.addService(this.lightService);
  }
  var existingFanService;
  if (existingAccessory){
    existingFanService = existingAccessory.getService(this.homekitFanName);
  }
  this.fanService = existingFanService || new Service.Fan(this.homekitFanName);

  setCharacteristicOnService(this.fanService, Characteristic.On,
                             "fan", "speed",
                             boolGetWrapper, fanSetWrapper)

  setCharacteristicOnService(this.fanService, Characteristic.RotationDirection,
                             "fan", "isSpinningForwards",
                             fanRotationGetWrapper, fanRotationSetWrapper)

  setCharacteristicOnService(this.fanService, Characteristic.RotationSpeed,
                             "fan", "speed",
                             getScalingWrapper(fanMaxSpeed), setScalingWrapper(fanMaxSpeed))
  if (existingAccessory && !existingFanService){
    existingAccessory.addService(this.fanService);
  }
/*
  var existingOccupancyService;
  if (existingAccessory){
    existingOccupancyService = existingAccessory.getService(this.homekitOccupancyName);
  }

  this.occupancyService = existingOccupancyService || new Service.OccupancySensor(this.homekitOccupancyName);

  setCharacteristicOnService(this.occupancyService, Characteristic.OccupancyDetected,
                              "room", "isOccupied",
                              occupancyGetWrapper, null)

  if (existingAccessory && !existingOccupancyService){
    existingAccessory.addService(this.occupancyService);
  }
*/
  this.getServices = function() {
    return [this.lightService, this.fanService]; //this.occupancyService];
  }
  if (existingAccessory){
    existingAccessory.updateReachability(true);
  }
}

BigAssFanAccessory.prototype.getStateFactory = function(propertyToWrap, subProperty, outputMapping) {
  return function(callback) {
    this.myBigAss[propertyToWrap].update(subProperty, function(err, value) {
      var returnVal = outputMapping(value);
      callback(err, returnVal);
    });
  }
}

BigAssFanAccessory.prototype.setStateFactory = function(propertyToWrap, subProperty, outputMapping) {
  return function(state, callback) {
    var valToSet = outputMapping(state)
    if (valToSet != null) {
      this.myBigAss[propertyToWrap].setProperty(subProperty, valToSet, function(err) {
        callback(err);
      });
    } else {
      // If null is returned, ignore the command
      callback(null);
    }
  }
}

<|endoftext|>


<commit_before>var Entity = require('sourced').Entity;
var EventEmitter = require('events').EventEmitter;
var log = require('debug')('sourced-repo-mongo');
var mongo = require('./mongo');
var Promise = require('bluebird');
var util = require('util');
var _ = require('lodash');

function Repository (entityType, indices) {
  EventEmitter.call(this);
  if ( ! mongo.db) {
    throw new Error('mongo has not been initialized. you must call require(\'sourced-repo-mongo/mongo\').connect(config.MONGO_URL); before instantiating a Repository');
  }
  indices = _.union(indices, ['id']);
  var self = this;
  var db = mongo.db;
  self.entityType = entityType;
  self.indices = indices;
  self.initialized = new Promise(function (resolve, reject) {
    var snapshotCollectionName = util.format('%s.snapshots', entityType.name);
    var snapshots = db.collection(snapshotCollectionName);
    self.snapshots = snapshots;
    var eventCollectionName = util.format('%s.events', entityType.name);
    var events = db.collection(eventCollectionName);
    self.events = events;
    self.indices.forEach(function (index) {
      snapshots.ensureIndex(index, reject);
      events.ensureIndex(index, reject);
    });
    log('initialized %s entity store', self.entityType.name);
    resolve();
    self.emit('ready');
  });
  log('connecting to %s entity store', this.entityType.name);
}

util.inherits(Repository, EventEmitter);

Repository.prototype.get = function get (id, cb) {
  var self = this;
  log('getting %s for id %s', this.entityType.name, id);
  this.initialized.done(function () {
    self.snapshots
      .find({ id: id })
      .sort({ version: -1 })
      .limit(-1)
      .toArray(function (err, snapshots) {
        if (err) return cb(err);
        var snapshot = snapshots[0];
        var criteria = (snapshot) ? { id: id, version: { $gt: snapshot.version } } : { id: id };
        self.events.find(criteria)
          .sort({ version: 1 })
          .toArray(function (err, events) {
            if (err) return cb(err);
            if (snapshot) delete snapshot._id;
            var entity = self.deserialize(id, snapshot, events);
            return cb(null, entity);
          });
    });
  });
};

Repository.prototype._getAllSnapshots = function _getAllSnapshots (ids) {
  var self = this;
  return new Promise(function (resolve, reject) {
    var match = { $match: { id: { $in: ids } } };
    var group = { $group: { _id: '$id', snapshotVersion: { $last: '$snapshotVersion' } } };
    self.snapshots.aggregate([match, group], function (err, idVersionPairs) {
      if (err) return reject(err);
      var criteria = {};
      if (idVersionPairs.length === 0) {
        return resolve([]);
      } else if (idVersionPairs.length === 1) {
        criteria = { id: idVersionPairs[0]._id };
      } else {
        criteria.$or = [];
        idVersionPairs.forEach(function (pair) {
          var cri = { id: pair._id, snapshotVersion: pair.snapshotVersion };
          criteria.$or.push(cri);
        });
      }
      self.snapshots
        .find(criteria)
        .toArray(function (err, snapshots) {
          if (err) reject(err);
          resolve(snapshots);
        });
    });
  });
};

Repository.prototype._getAllEvents = function _getAllEvents (ids, snapshots) {
  var self = this;
  return new Promise(function (resolve, reject) {
    var criteria = { $or: [] };
    ids.forEach(function (id) {
      var snapshot;
      if ( ! (snapshot = _.find(snapshots, function (snapshot) {
        return id === snapshot.id;
      }))) {
        criteria.$or.push({ id: id });
      } else {
        criteria.$or.push({ id: snapshot.id, version: { $gt: snapshot.snapshotVersion } });
      }
    });
    self.events.find(criteria)
      .sort({ id: 1, version: 1 })
      .toArray(function (err, events) {
        if (err) return reject(err);
        var results = [];
        ids.forEach(function (id) {
          var snapshot = _.find(snapshots, function (snapshot) {
            return snapshot.id === id;
          });
          if (snapshot) delete snapshot._id;
          var evnts = _.filter(events, function (event) {
            return event.id === id;
          });
          var entity = self.deserialize(id, snapshot, evnts);
          results.push(entity);
        });
        return resolve(results);
      });
  });
};

Repository.prototype.getAll = function getAll (ids, cb) {
  var self = this;
  log('getting %ss for ids %j', this.entityType.name, ids);
  this.initialized.done(function () {
    self._getAllSnapshots(ids)
      .catch(cb)
      .done(function _afterGetAllSnapshots (snapshots) {
        self._getAllEvents(ids, snapshots)
          .catch(cb)
          .done(function (entities) {
            cb(null, entities);
          });
    });
  });
};

Repository.prototype._commitEvents = function _commitEvents (entity) {
  var self = this;
  return new Promise(function (resolve, reject) {
    if (entity.newEvents.length === 0) return resolve();
    var events = entity.newEvents;
    events.forEach(function (event) {
      if (event && event._id) delete event._id; // mongo will blow up if we try to insert multiple _id keys
      self.indices.forEach(function (index) {
        event[index] = entity[index];
      });
    });
    self.events.insert(events, function (err) {
      if (err) return reject(err);
      log('committed %s.events for id %s', self.entityType.name, entity.id);
      entity.newEvents = [];
      return resolve();
    });
  });
};

Repository.prototype._commitAllEvents = function _commitEvents (entities) {
  var self = this;
  return new Promise(function (resolve, reject) {
    var events = [];
    entities.forEach(function (entity) {
      if (entity.newEvents.length === 0) return;
      var evnts = entity.newEvents;
      evnts.forEach(function _applyIndices (event) {
        if (event && event._id) delete event._id; // mongo will blow up if we try to insert multiple _id keys
        self.indices.forEach(function (index) {
          event[index] = entity[index];
        });
      });
      Array.prototype.unshift.apply(events, evnts);
    });
    if (events.length === 0) return resolve();
    self.events.insert(events, function (err) {
      if (err) return reject(err);
      log('committed %s.events for ids %j', self.entityType.name, _.pluck(entities, 'id'));
      entities.forEach(function (entity) {
        entity.newEvents = [];
      });
      return resolve();
    });
  });
};

Repository.prototype._commitSnapshots = function _commitSnapshots (entity) {
  var self = this;
  return new Promise(function (resolve, reject) {
    if (entity.version >= entity.snapshotVersion + 10) {
      var snapshot = entity.snapshot();
      if (snapshot && snapshot._id) delete snapshot._id; // mongo will blow up if we try to insert multiple _id keys
      self.snapshots.insert(snapshot, function (err) {
        if (err) return reject(err);
        log('committed %s.snapshot for id %s %j', self.entityType.name, entity.id, snapshot);
        resolve(entity);
      });
    } else {
      resolve(entity);
    }
  });
};

Repository.prototype._commitAllSnapshots = function _commitAllSnapshots (entities) {
  var self = this;
  return new Promise(function (resolve, reject) {
    var snapshots = [];
    entities.forEach(function (entity) {
      if (entity.version >= entity.snapshotVersion + 10) {
        var snapshot = entity.snapshot();
        if (snapshot) {
          if (snapshot._id) delete snapshot._id; // mongo will blow up if we try to insert multiple _id keys)
          snapshots.push(snapshot);
        }
      }
    });
    if (snapshots.length === 0) return resolve();
    self.snapshots.insert(snapshots, function (err) {
      if (err) return reject(err);
      log('committed %s.snapshot for ids %s %j', self.entityType.name, _.pluck(entities, 'id'), snapshots);
      resolve(entities);
    });
  });
};

Repository.prototype._emitEvents = function _emitEvents (entity) {
  var self = this;
  return new Promise(function (resolve, reject) {
    var eventsToEmit = entity.eventsToEmit;
    entity.eventsToEmit = [];
    eventsToEmit.forEach(function (eventToEmit) {
      var args = Array.prototype.slice.call(eventToEmit);
      self.entityType.prototype.emit.apply(entity, args);
    });
    log('emitted local events for id %s', entity.id);
    return resolve();
  });
};

Repository.prototype.commit = function commit (entity, cb) {
  var self = this;
  log('committing %s for id %s', this.entityType.name, entity.id);
  this.initialized.done(function () {
    self._commitSnapshots(entity).then(function _afterCommitSnapshots () {
      self._commitEvents(entity).then(function _afterCommitEvents () {
        self._emitEvents(entity).then(function _afterEmitEvents () {
          return cb();
        });
      }).catch(cb);
    }).catch(cb);
  });
};

Repository.prototype.commitAll = function commit (entities, cb) {
  var self = this;
  log('committing %s for id %j', this.entityType.name, _.pluck(entities, 'id'));
  this.initialized.done(function () {
    self._commitAllSnapshots(entities).then(function _afterCommitSnapshots () {
      self._commitAllEvents(entities).then(function _afterCommitEvents () {
        var promises = [];
        entities.forEach(function (entity) {
          promises.push(self._emitEvents(entity));
        });
        Promise.all(promises).then(function _afterEmitAllEvents () {
          return cb();
        });
      }).catch(cb);
    }).catch(cb);
    // // save snapshots before saving events
    // new Promise(function (resolve, reject) {
    //   entities.forEach(function (entity) {

    //   });
    //   if (entity.version >= entity.snapshotVersion + 10) {
    //     var snapshot = entity.snapshot();
    //     if (snapshot && snapshot._id) delete snapshot._id; // mongo will blow up if we try to insert multiple _id keys
    //     self.snapshots.insert(snapshot, function (err) {
    //       if (err) return reject(err);
    //       log('committed %s.snapshot for id %s %j', self.entityType.name, entity.id, snapshot);
    //       resolve(entity);
    //     });
    //   } else {
    //     resolve(entity);
    //   }
    // }).done(function (entity) {
    //   function done () {
    //     var eventsToEmit = entity.eventsToEmit;
    //     entity.eventsToEmit = [];
    //     eventsToEmit.forEach(function (eventToEmit) {
    //       var args = Array.prototype.slice.call(eventToEmit);
    //       self.entityType.prototype.emit.apply(entity, args);
    //     });
    //     log('emitted local events for id %s', entity.id);
    //     return cb();
    //   }
    //   // when finished, save events
    //   if (entity.newEvents.length === 0) return done();
    //   var events = entity.newEvents;
    //   events.forEach(function (event) {
    //     if (event && event._id) delete event._id; // mongo will blow up if we try to insert multiple _id keys
    //     self.indices.forEach(function (index) {
    //       event[index] = entity[index];
    //     });
    //   });
    //   self.events.insert(events, function (err) {
    //     if (err) return cb(err);
    //     log('committed %s.events for id %s', self.entityType.name, entity.id);
    //     entity.newEvents = [];
    //     return done();
    //   });
    // });
  });
};

Repository.prototype.deserialize = function deserialize (id, snapshot, events) {
  log('deserializing %s entity ', this.entityType.name);
  var entity = new this.entityType(snapshot, events);
  entity.id = id;
  return entity;
};

module.exports.Repository = Repository;<commit_msg>rearrange / refactoring<commit_after>var Entity = require('sourced').Entity;
var EventEmitter = require('events').EventEmitter;
var log = require('debug')('sourced-repo-mongo');
var mongo = require('./mongo');
var Promise = require('bluebird');
var util = require('util');
var _ = require('lodash');

function Repository (entityType, indices) {
  EventEmitter.call(this);
  if ( ! mongo.db) {
    throw new Error('mongo has not been initialized. you must call require(\'sourced-repo-mongo/mongo\').connect(config.MONGO_URL); before instantiating a Repository');
  }
  indices = _.union(indices, ['id']);
  var self = this;
  var db = mongo.db;
  self.entityType = entityType;
  self.indices = indices;
  self.initialized = new Promise(function (resolve, reject) {
    var snapshotCollectionName = util.format('%s.snapshots', entityType.name);
    var snapshots = db.collection(snapshotCollectionName);
    self.snapshots = snapshots;
    var eventCollectionName = util.format('%s.events', entityType.name);
    var events = db.collection(eventCollectionName);
    self.events = events;
    self.indices.forEach(function (index) {
      snapshots.ensureIndex(index, reject);
      events.ensureIndex(index, reject);
    });
    log('initialized %s entity store', self.entityType.name);
    resolve();
    self.emit('ready');
  });
  log('connecting to %s entity store', this.entityType.name);
}

util.inherits(Repository, EventEmitter);

Repository.prototype.commit = function commit (entity, cb) {
  var self = this;
  log('committing %s for id %s', this.entityType.name, entity.id);
  this.initialized.done(function () {
    self._commitSnapshots(entity).then(function _afterCommitSnapshots () {
      self._commitEvents(entity).then(function _afterCommitEvents () {
        self._emitEvents(entity).then(function _afterEmitEvents () {
          return cb();
        });
      }).catch(cb);
    }).catch(cb);
  });
};

Repository.prototype.commitAll = function commit (entities, cb) {
  var self = this;
  log('committing %s for id %j', this.entityType.name, _.pluck(entities, 'id'));
  this.initialized.done(function () {
    self._commitAllSnapshots(entities).then(function _afterCommitSnapshots () {
      self._commitAllEvents(entities).then(function _afterCommitEvents () {
        var promises = [];
        entities.forEach(function (entity) {
          promises.push(self._emitEvents(entity));
        });
        Promise.all(promises).then(function _afterEmitAllEvents () {
          return cb();
        });
      }).catch(cb);
    }).catch(cb);
  });
};

Repository.prototype.get = function get (id, cb) {
  var self = this;
  log('getting %s for id %s', this.entityType.name, id);
  this.initialized.done(function () {
    self.snapshots
      .find({ id: id })
      .sort({ version: -1 })
      .limit(-1)
      .toArray(function (err, snapshots) {
        if (err) return cb(err);
        var snapshot = snapshots[0];
        var criteria = (snapshot) ? { id: id, version: { $gt: snapshot.version } } : { id: id };
        self.events.find(criteria)
          .sort({ version: 1 })
          .toArray(function (err, events) {
            if (err) return cb(err);
            if (snapshot) delete snapshot._id;
            var entity = self._deserialize(id, snapshot, events);
            return cb(null, entity);
          });
    });
  });
};

Repository.prototype.getAll = function getAll (ids, cb) {
  var self = this;
  log('getting %ss for ids %j', this.entityType.name, ids);
  this.initialized.done(function () {
    self._getAllSnapshots(ids)
      .catch(cb)
      .done(function _afterGetAllSnapshots (snapshots) {
        self._getAllEvents(ids, snapshots)
          .catch(cb)
          .done(function (entities) {
            cb(null, entities);
          });
    });
  });
};

Repository.prototype._commitEvents = function _commitEvents (entity) {
  var self = this;
  return new Promise(function (resolve, reject) {
    if (entity.newEvents.length === 0) return resolve();
    var events = entity.newEvents;
    events.forEach(function (event) {
      if (event && event._id) delete event._id; // mongo will blow up if we try to insert multiple _id keys
      self.indices.forEach(function (index) {
        event[index] = entity[index];
      });
    });
    self.events.insert(events, function (err) {
      if (err) return reject(err);
      log('committed %s.events for id %s', self.entityType.name, entity.id);
      entity.newEvents = [];
      return resolve();
    });
  });
};

Repository.prototype._commitAllEvents = function _commitEvents (entities) {
  var self = this;
  return new Promise(function (resolve, reject) {
    var events = [];
    entities.forEach(function (entity) {
      if (entity.newEvents.length === 0) return;
      var evnts = entity.newEvents;
      evnts.forEach(function _applyIndices (event) {
        if (event && event._id) delete event._id; // mongo will blow up if we try to insert multiple _id keys
        self.indices.forEach(function (index) {
          event[index] = entity[index];
        });
      });
      Array.prototype.unshift.apply(events, evnts);
    });
    if (events.length === 0) return resolve();
    self.events.insert(events, function (err) {
      if (err) return reject(err);
      log('committed %s.events for ids %j', self.entityType.name, _.pluck(entities, 'id'));
      entities.forEach(function (entity) {
        entity.newEvents = [];
      });
      return resolve();
    });
  });
};

Repository.prototype._commitSnapshots = function _commitSnapshots (entity) {
  var self = this;
  return new Promise(function (resolve, reject) {
    if (entity.version >= entity.snapshotVersion + 10) {
      var snapshot = entity.snapshot();
      if (snapshot && snapshot._id) delete snapshot._id; // mongo will blow up if we try to insert multiple _id keys
      self.snapshots.insert(snapshot, function (err) {
        if (err) return reject(err);
        log('committed %s.snapshot for id %s %j', self.entityType.name, entity.id, snapshot);
        resolve(entity);
      });
    } else {
      resolve(entity);
    }
  });
};

Repository.prototype._commitAllSnapshots = function _commitAllSnapshots (entities) {
  var self = this;
  return new Promise(function (resolve, reject) {
    var snapshots = [];
    entities.forEach(function (entity) {
      if (entity.version >= entity.snapshotVersion + 10) {
        var snapshot = entity.snapshot();
        if (snapshot) {
          if (snapshot._id) delete snapshot._id; // mongo will blow up if we try to insert multiple _id keys)
          snapshots.push(snapshot);
        }
      }
    });
    if (snapshots.length === 0) return resolve();
    self.snapshots.insert(snapshots, function (err) {
      if (err) return reject(err);
      log('committed %s.snapshot for ids %s %j', self.entityType.name, _.pluck(entities, 'id'), snapshots);
      resolve(entities);
    });
  });
};

Repository.prototype._deserialize = function _deserialize (id, snapshot, events) {
  log('deserializing %s entity ', this.entityType.name);
  var entity = new this.entityType(snapshot, events);
  entity.id = id;
  return entity;
};

Repository.prototype._emitEvents = function _emitEvents (entity) {
  var self = this;
  return new Promise(function (resolve, reject) {
    var eventsToEmit = entity.eventsToEmit;
    entity.eventsToEmit = [];
    eventsToEmit.forEach(function (eventToEmit) {
      var args = Array.prototype.slice.call(eventToEmit);
      self.entityType.prototype.emit.apply(entity, args);
    });
    log('emitted local events for id %s', entity.id);
    return resolve();
  });
};

Repository.prototype._getAllSnapshots = function _getAllSnapshots (ids) {
  var self = this;
  return new Promise(function (resolve, reject) {
    var match = { $match: { id: { $in: ids } } };
    var group = { $group: { _id: '$id', snapshotVersion: { $last: '$snapshotVersion' } } };
    self.snapshots.aggregate([match, group], function (err, idVersionPairs) {
      if (err) return reject(err);
      var criteria = {};
      if (idVersionPairs.length === 0) {
        return resolve([]);
      } else if (idVersionPairs.length === 1) {
        criteria = { id: idVersionPairs[0]._id };
      } else {
        criteria.$or = [];
        idVersionPairs.forEach(function (pair) {
          var cri = { id: pair._id, snapshotVersion: pair.snapshotVersion };
          criteria.$or.push(cri);
        });
      }
      self.snapshots
        .find(criteria)
        .toArray(function (err, snapshots) {
          if (err) reject(err);
          resolve(snapshots);
        });
    });
  });
};

Repository.prototype._getAllEvents = function _getAllEvents (ids, snapshots) {
  var self = this;
  return new Promise(function (resolve, reject) {
    var criteria = { $or: [] };
    ids.forEach(function (id) {
      var snapshot;
      if ( ! (snapshot = _.find(snapshots, function (snapshot) {
        return id === snapshot.id;
      }))) {
        criteria.$or.push({ id: id });
      } else {
        criteria.$or.push({ id: snapshot.id, version: { $gt: snapshot.snapshotVersion } });
      }
    });
    self.events.find(criteria)
      .sort({ id: 1, version: 1 })
      .toArray(function (err, events) {
        if (err) return reject(err);
        var results = [];
        ids.forEach(function (id) {
          var snapshot = _.find(snapshots, function (snapshot) {
            return snapshot.id === id;
          });
          if (snapshot) delete snapshot._id;
          var evnts = _.filter(events, function (event) {
            return event.id === id;
          });
          var entity = self._deserialize(id, snapshot, evnts);
          results.push(entity);
        });
        return resolve(results);
      });
  });
};

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


<commit_before>var System = require('./dist/es6-module-loader.src');

System.transpiler = 'traceur';
try {
  System.paths.traceur = require.resolve('traceur/bin/traceur.js');
}
catch(e) {}
try {
  System.paths.babel = require.resolve('babel-core/browser.js');
}
catch(e) {}
try {
  System.paths.babel = System.paths.babel || require.resolve('babel/browser.js');
}
catch(e) {}

module.exports = {
  Loader: global.LoaderPolyfill,
  System: System
};
<commit_msg>Traceur and Babel file URL fix on Windows (#342)<commit_after>var System = require('./dist/es6-module-loader.src');

System.transpiler = 'traceur';
try {
  System.paths.traceur = 'file:' + require.resolve('traceur/bin/traceur.js');
}
catch(e) {}
try {
  System.paths.babel = 'file:' + require.resolve('babel-core/browser.js');
}
catch(e) {}
try {
  System.paths.babel = System.paths.babel || 'file:' + require.resolve('babel/browser.js');
}
catch(e) {}

module.exports = {
  Loader: global.LoaderPolyfill,
  System: System
};
<|endoftext|>


<commit_before>function escapeCarriageReturn(txt) {
  txt = txt.replace(/\r+\n/gm, '\n'); // \r followed by \n --> newline
  while (txt.search(/\r[^$]/g) > -1) {
      var base = txt.match(/^(.*)\r+/m)[1];
      var insert = txt.match(/\r+(.*)$/m)[1];
      insert = insert + base.slice(insert.length, base.length);
      txt = txt.replace(/\r+.*$/m, '\r').replace(/^.*\r/m, insert);
  }
  return txt;
}

module.exports = escapeCarriageReturn;
<commit_msg>Convert undefined to ''<commit_after>function escapeCarriageReturn(txt) {
  if(!txt) return '';
  txt = txt.replace(/\r+\n/gm, '\n'); // \r followed by \n --> newline
  while (txt.search(/\r[^$]/g) > -1) {
      var base = txt.match(/^(.*)\r+/m)[1];
      var insert = txt.match(/\r+(.*)$/m)[1];
      insert = insert + base.slice(insert.length, base.length);
      txt = txt.replace(/\r+.*$/m, '\r').replace(/^.*\r/m, insert);
  }
  return txt;
}

module.exports = escapeCarriageReturn;
<|endoftext|>


<commit_before>'use strict';
const os = require('os');
const execa = require('execa');
const mem = require('mem');

function getEnvVar() {
	const env = process.env;

	return env.SUDO_USER ||
		env.C9_USER /* Cloud9 */ ||
		env.LOGNAME ||
		env.USER ||
		env.LNAME ||
		env.USERNAME;
}

function cleanWinCmd(x) {
	return x.replace(/^.*\\/, '');
}

function noop() {}

module.exports = mem(() => {
	const envVar = getEnvVar();

	if (envVar) {
		return Promise.resolve(envVar);
	}

	if (os.userInfo) {
		return Promise.resolve(os.userInfo().username);
	}

	if (process.platform === 'darwin' || process.platform === 'linux') {
		return execa('id', ['-un']).then(x => x.stdout).catch(noop);
	} else if (process.platform === 'win32') {
		return execa('whoami').then(x => cleanWinCmd(x.stdout)).catch(noop);
	}

	return Promise.resolve();
});

module.exports.sync = mem(() => {
	const envVar = getEnvVar();

	if (envVar) {
		return envVar;
	}

	if (os.userInfo) {
		return os.userInfo().username;
	}

	try {
		if (process.platform === 'darwin' || process.platform === 'linux') {
			return execa.sync('id', ['-un']).stdout;
		} else if (process.platform === 'win32') {
			return cleanWinCmd(execa.sync('whoami').stdout);
		}
	} catch (err) {}
});
<commit_msg>Support more Unix-like operating system (#20)<commit_after>'use strict';
const os = require('os');
const execa = require('execa');
const mem = require('mem');

function getEnvVar() {
	// eslint-disable-next-line prefer-destructuring
	const env = process.env;

	return env.SUDO_USER ||
		env.C9_USER /* Cloud9 */ ||
		env.LOGNAME ||
		env.USER ||
		env.LNAME ||
		env.USERNAME;
}

function cleanWinCmd(x) {
	return x.replace(/^.*\\/, '');
}

function noop() {}

module.exports = mem(() => {
	const envVar = getEnvVar();

	if (envVar) {
		return Promise.resolve(envVar);
	}

	if (os.userInfo) {
		return Promise.resolve(os.userInfo().username);
	}

	if (process.platform === 'win32') {
		return execa('whoami').then(x => cleanWinCmd(x.stdout)).catch(noop);
	}

	return execa('id', ['-un']).then(x => x.stdout).catch(noop);
});

module.exports.sync = mem(() => {
	const envVar = getEnvVar();

	if (envVar) {
		return envVar;
	}

	if (os.userInfo) {
		return os.userInfo().username;
	}

	try {
		if (process.platform === 'win32') {
			return cleanWinCmd(execa.sync('whoami').stdout);
		}
		return execa.sync('id', ['-un']).stdout;
	} catch (err) {}
});
<|endoftext|>


<commit_before>var aws = require('aws-sdk');
var s3 = new aws.S3();
var exec = require('child_process').execSync;
var fs = require('fs');

exports.handler = function(event, context, callback) {
    //console.log(JSON.stringify(process.env));
    console.log('gdal args: ' + process.env.gdalArgs);
    console.log('Bucket Name: ' + event.sourceBucket);
    console.log('Object Key: ' + event.sourceObjectKey);
    console.log('Bucket Name: ' + event.targetBucket);
    console.log('target prefix: ' + event.targetPrefix);
    console.log('find: ' + process.env.findVal);
    console.log('replace: ' + process.env.replaceVal);
    var inputStream = fs.createWriteStream('/tmp/input.tif');
    s3.getObject({Bucket: event.sourceBucket, Key: event.sourceObjectKey, RequestPayer: 'requester'})
      .createReadStream()
      .pipe(inputStream)
      .on('finish', function() {
          inputStream.end;
          var gdalParams = 'env AWS_ACCESSS_KEY_ID=' + process.env.AWS_ACCESS_KEY_ID
            + ' AWS_SECRET_ACCESS_KEY=' + process.env.AWS_SECRET_ACCESS_KEY
            + ' AWS_SESSION_TOKEN=' + process.env.AWS_SESSION_TOKEN
            + ' ./bin/gdal_translate '
            + process.env.gdalArgs
            + ' /tmp/input.tif /tmp/output.tif';
          console.log('gdalParams: ' + gdalParams);
          cmdoutput = exec(gdalParams);
          //var cmdoutput = exec('ls -alh /tmp/input.tif');
          console.log('stdout: ' + cmdoutput);

          if (process.env.replaceVal) {
           var uploadObjectKey = event.sourceObjectKey.replace(process.env.findVal, process.env.replaceVal);
          }
          else {
           var uploadObjectKey = event.sourceObjectKey;
          }
          if (event.targetPrefix) {
           var uploadObjectKey = event.targetPrefix + '/' + uploadObjectKey;
          }
          console.log('uploadObjectKey: ' + uploadObjectKey);

          var body = fs.createReadStream('/tmp/output.tif');

          var s3obj = new aws.S3({params: {Bucket: event.targetBucket, Key: uploadObjectKey}});
          s3obj.upload({Body: body})
            .on('httpUploadProgress', function(evt) {
		//console.log(evt);
		})
            .send(function(err, data) {callback(err, 'Process complete!');});
     })
};
<commit_msg>Update console.log line<commit_after>var aws = require('aws-sdk');
var s3 = new aws.S3();
var exec = require('child_process').execSync;
var fs = require('fs');

exports.handler = function(event, context, callback) {
    //console.log(JSON.stringify(process.env));
    console.log('gdal args: ' + process.env.gdalArgs);
    console.log('Bucket Name: ' + event.sourceBucket);
    console.log('Object Key: ' + event.sourceObjectKey);
    console.log('Bucket Name: ' + event.targetBucket);
    console.log('target prefix: ' + event.targetPrefix);
    //console.log('find: ' + process.env.findVal);
    console.log('replace: ' + process.env.replaceVal);
    var inputStream = fs.createWriteStream('/tmp/input.tif');
    s3.getObject({Bucket: event.sourceBucket, Key: event.sourceObjectKey, RequestPayer: 'requester'})
      .createReadStream()
      .pipe(inputStream)
      .on('finish', function() {
          inputStream.end;
          var gdalParams = 'env AWS_ACCESSS_KEY_ID=' + process.env.AWS_ACCESS_KEY_ID
            + ' AWS_SECRET_ACCESS_KEY=' + process.env.AWS_SECRET_ACCESS_KEY
            + ' AWS_SESSION_TOKEN=' + process.env.AWS_SESSION_TOKEN
            + ' ./bin/gdal_translate '
            + process.env.gdalArgs
            + ' /tmp/input.tif /tmp/output.tif';
          console.log('gdalParams: ' + gdalParams);
          cmdoutput = exec(gdalParams);
          //var cmdoutput = exec('ls -alh /tmp/input.tif');
          console.log('stdout: ' + cmdoutput);

          if (process.env.replaceVal) {
           var uploadObjectKey = event.sourceObjectKey.replace(process.env.findVal, process.env.replaceVal);
          }
          else {
           var uploadObjectKey = event.sourceObjectKey;
          }
          if (event.targetPrefix) {
           var uploadObjectKey = event.targetPrefix + '/' + uploadObjectKey;
          }
          console.log('uploadObjectKey: ' + uploadObjectKey);

          var body = fs.createReadStream('/tmp/output.tif');

          var s3obj = new aws.S3({params: {Bucket: event.targetBucket, Key: uploadObjectKey}});
          s3obj.upload({Body: body})
            .on('httpUploadProgress', function(evt) {
		//console.log(evt);
		})
            .send(function(err, data) {callback(err, 'Process complete!');});
     })
};
<|endoftext|>


<commit_before>/*
  Copyright 2013-2014, Marten de Vries

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License 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.
*/

"use strict";

var extend = require("pouchdb-extend");
var nodify = require("promise-nodify");

var couchdb_objects = require("couchdb-objects");
var render = require("couchdb-render");
var httpQuery = require("couchdb-req-http-query");

exports.list = function (listPath, options, callback) {
  //options: values to end up in the request object of the list
  //function (next to their defaults).
  var db = this;

  if (typeof options === "function") {
    callback = options;
    options = {};
  }
  var designDocName = listPath.split("/")[0];
  var listName = listPath.split("/")[1];
  var viewName = listPath.split("/")[2];

  //build request object
  var infoPromise = db.info();
  var pathPromise = infoPromise.then(function (info) {
    var path = [info.db_name, "_design", designDocName, "_list", listName];
    if (viewName) {
      path.push(viewName);
    }
    return path;
  });
  var reqPromise = couchdb_objects.buildRequestObject(options, pathPromise, infoPromise, db);
  return reqPromise.then(function (req) {
    var promise;
    if (["http", "https"].indexOf(db.type()) === -1) {
      promise = offlineQuery(db, designDocName, listName, viewName, req, options);
    } else {
      promise = httpQuery(db, req);
    }
    nodify(promise, callback);
    return promise;
  });
};

function offlineQuery(db, designDocName, listName, viewName, req, options) {
  var Promise = db.constructor.utils.Promise;

  //get the data involved.
  var ddocPromise = db.get("_design/" + designDocName).then(function (designDoc) {
    if (!(designDoc.lists || {}).hasOwnProperty(listName)) {
      throw {
        status: 404,
        error: "not_found",
        reason: "missing list function " + listName + " on design doc _design/" + designDocName
      };
    }
    return designDoc;
  });
  var viewPromise = db.query(designDocName + "/" + viewName, options);

  return Promise.all([ddocPromise, viewPromise]).then(function (args) {
    var designDoc = args[0];
    var viewResp = args[1];

    var head = {
      offset: viewResp.offset,
      total_rows: viewResp.total_rows
    };

    var respInfo;
    var chunks = [];

    var listApi = {
      getRow: function () {
        listApi.start({});
        return viewResp.rows.shift() || null;
      },
      send: function (chunk) {
        listApi.start({});
        chunks.push(chunk);
      },
      start: function (respBegin) {
        if (!respInfo) {
          respInfo = respBegin;
        }
      }
    };

    var resp = render(designDoc.lists[listName], designDoc, head, req, listApi);
    if (respInfo) {
      extend(resp, respInfo);
      resp.body = chunks.join("") + resp.body;
      resp.headers["Transfer-Encoding"] = "chunked";
    }
    return resp;
  });
}
<commit_msg>JS coverage is back at 100%. Added viewCleanup() wrapper function. Removed unintentional side effects for some tests, and made them faster. Improved tests + .coveragerc file. Added httpQuery function to the pouchdb-update plug-in too.<commit_after>/*
  Copyright 2013-2014, Marten de Vries

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License 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.
*/

"use strict";

var extend = require("extend");
var nodify = require("promise-nodify");

var couchdb_objects = require("couchdb-objects");
var render = require("couchdb-render");
var httpQuery = require("couchdb-req-http-query");

exports.list = function (listPath, options, callback) {
  //options: values to end up in the request object of the list
  //function (next to their defaults).
  var db = this;

  if (typeof options === "function") {
    callback = options;
    options = {};
  }
  var designDocName = listPath.split("/")[0];
  var listName = listPath.split("/")[1];
  var viewName = listPath.split("/")[2];

  //build request object
  var infoPromise = db.info();
  var pathPromise = infoPromise.then(function (info) {
    var path = [info.db_name, "_design", designDocName, "_list", listName];
    if (viewName) {
      path.push(viewName);
    }
    return path;
  });
  var reqPromise = couchdb_objects.buildRequestObject(options, pathPromise, infoPromise, db);
  return reqPromise.then(function (req) {
    var promise;
    if (["http", "https"].indexOf(db.type()) === -1) {
      promise = offlineQuery(db, designDocName, listName, viewName, req, options);
    } else {
      promise = httpQuery(db, req);
    }
    nodify(promise, callback);
    return promise;
  });
};

function offlineQuery(db, designDocName, listName, viewName, req, options) {
  var Promise = db.constructor.utils.Promise;

  if (req.headers["Content-Type"] && req.headers["Content-Type"] !== "application/json") {
    return Promise.reject({
      status: 400,
      name: "bad_request",
      message: "invalid_json"
    });
  }

  //get the data involved.
  var ddocPromise = db.get("_design/" + designDocName).then(function (designDoc) {
    if (!(designDoc.lists || {}).hasOwnProperty(listName)) {
      throw {
        status: 404,
        error: "not_found",
        reason: "missing list function " + listName + " on design doc _design/" + designDocName
      };
    }
    return designDoc;
  });
  var viewPromise = db.query(designDocName + "/" + viewName, options);

  return Promise.all([ddocPromise, viewPromise]).then(function (args) {
    var designDoc = args[0];
    var viewResp = args[1];

    var head = {
      offset: viewResp.offset,
      total_rows: viewResp.total_rows
    };

    var respInfo;
    var chunks = [];

    var listApi = {
      getRow: function () {
        listApi.start({});
        return viewResp.rows.shift() || null;
      },
      send: function (chunk) {
        listApi.start({});
        chunks.push(chunk);
      },
      start: function (respBegin) {
        if (!respInfo) {
          respInfo = respBegin;
        }
      }
    };

    var resp = render(designDoc.lists[listName], designDoc, head, req, listApi);
    if (respInfo) {
      extend(resp, respInfo);
      resp.body = chunks.join("") + resp.body;
      resp.headers["Transfer-Encoding"] = "chunked";
    }
    return resp;
  });
}
<|endoftext|>


<commit_before>const axios = require('axios')

function detectIssueId (ref) {
    const reg = /^(feature|fix|hotfix|fixbug|bugfix|improve|solve|update)-(\d+)/i
    const matches = reg.exec(ref) || []
    return matches[2]
}

const USERMAP = {
    'ijse': '@清凌渡',
    'wang-jia': '@王佳',
    'gao-jx': '@jianxun gao',
    'JeannieMa': '@马柳菁',
    'liushumei': '@刘淑美'
}

module.exports = robot => {
    robot.on('pull_request.review_requested', async context => {
        const payload = context.payload
        const pr = payload.pull_request
        const reviewers = pr.requested_reviewers.map(r => r.login)
        const url = pr.html_url
        const reviewer = USERMAP[payload.requested_reviewer.login]
            || payload.requested_reviewer.login
        axios.post('http://bot.ijser.cn/api/ding', {
            to: 'publish',
            msg: `${USERMAP[pr.user.login]} 喊 ${reviewer} 来Review代码 ${url} !`
        })
    })
    robot.on('pull_request.opened', async context => {
        const repo = context.repo()
        const pr = context.payload.pull_request
        const branchName = pr.head.ref

        pr.body = pr.body || ''
        console.log('check pr: ', pr.number)
        // link with issue
        const issueId = detectIssueId(branchName)
        if (issueId) {
            const ctn = pr.body.replace(/resolve #(\d+)/g, '')
            const newIssue = context.issue({
                number: pr.number,
                body: ctn + `\n\n resolve #${issueId} `
            })

            console.log('link issue: ', issueId)
            // create comment
            context.github.issues.edit(newIssue)
        }

        /*
        // check milestone
        const isMilestoneSetted = !!pr.milestone
        if (!isMilestoneSetted) {
            context.github.issues.getMilestones(context.repo({
                state: 'open',
                sort: 'due_on',
                direction: 'desc',
                per_page: 3
            })).then(({ data: milestones })=> {
                console.log('milestone list:', milestones)
                if (milestones && milestones[0]) {
                    const curMilestone = milestones[0]

                    console.log('set milestone:', curMilestone)
                    // set milestone
                    context.github.issues.edit(context.issue({
                        number: pr.number,
                        milestone: curMilestone.number
                    }))
                }
            })
        }
        */

        // set assignee
        const hasAssignee = !!pr.assignees.length
        if (!hasAssignee) {
            context.github.issues.edit(context.issue({
                number: pr.number,
                assignee: pr.user.login
            }))
        }

        // add labels
        const isFeature = /\[adde?d?\]/ig.test(pr.title)
        const isBug = /\[fixe?d?\]/ig.test(pr.title)
        const isImprove = /\[improve.*\]/ig.test(pr.title)
        const labels = []
        if (isFeature) labels.push('type:feature')
        if (isBug) labels.push('type:bug')
        if (isImprove) labels.push('type:improvement')
        context.github.issues.addLabels(context.repo({
            number: pr.number,
            labels: labels
        }))
    })
}
<commit_msg>add teamates<commit_after>const axios = require('axios')

function detectIssueId (ref) {
    const reg = /^(feature|fix|hotfix|fixbug|bugfix|improve|solve|update)-(\d+)/i
    const matches = reg.exec(ref) || []
    return matches[2]
}

const USERMAP = {
    'ijse': '@清凌渡',
    'wang-jia': '@王佳',
    'gao-jx': '@jianxun gao',
    'JeannieMa': '@马柳菁',
    'liushumei': '@刘淑美',
    'pengcui123': '@彭翠',
    'zhangsundanfeng': '@长孙丹凤'
}

module.exports = robot => {
    robot.on('pull_request.review_requested', async context => {
        const payload = context.payload
        const pr = payload.pull_request
        const reviewers = pr.requested_reviewers.map(r => r.login)
        const url = pr.html_url
        const reviewer = USERMAP[payload.requested_reviewer.login]
            || payload.requested_reviewer.login
        axios.post('http://bot.ijser.cn/api/ding', {
            to: 'publish',
            msg: `${USERMAP[pr.user.login]} 喊 ${reviewer} 来Review代码 ${url} !`
        })
    })
    robot.on('pull_request.opened', async context => {
        const repo = context.repo()
        const pr = context.payload.pull_request
        const branchName = pr.head.ref

        pr.body = pr.body || ''
        console.log('check pr: ', pr.number)
        // link with issue
        const issueId = detectIssueId(branchName)
        if (issueId) {
            const ctn = pr.body.replace(/resolve #(\d+)/g, '')
            const newIssue = context.issue({
                number: pr.number,
                body: ctn + `\n\n resolve #${issueId} `
            })

            console.log('link issue: ', issueId)
            // create comment
            context.github.issues.edit(newIssue)
        }

        /*
        // check milestone
        const isMilestoneSetted = !!pr.milestone
        if (!isMilestoneSetted) {
            context.github.issues.getMilestones(context.repo({
                state: 'open',
                sort: 'due_on',
                direction: 'desc',
                per_page: 3
            })).then(({ data: milestones })=> {
                console.log('milestone list:', milestones)
                if (milestones && milestones[0]) {
                    const curMilestone = milestones[0]

                    console.log('set milestone:', curMilestone)
                    // set milestone
                    context.github.issues.edit(context.issue({
                        number: pr.number,
                        milestone: curMilestone.number
                    }))
                }
            })
        }
        */

        // set assignee
        const hasAssignee = !!pr.assignees.length
        if (!hasAssignee) {
            context.github.issues.edit(context.issue({
                number: pr.number,
                assignee: pr.user.login
            }))
        }

        // add labels
        const isFeature = /\[adde?d?\]/ig.test(pr.title)
        const isBug = /\[fixe?d?\]/ig.test(pr.title)
        const isImprove = /\[improve.*\]/ig.test(pr.title)
        const labels = []
        if (isFeature) labels.push('type:feature')
        if (isBug) labels.push('type:bug')
        if (isImprove) labels.push('type:improvement')
        context.github.issues.addLabels(context.repo({
            number: pr.number,
            labels: labels
        }))
    })
}
<|endoftext|>


<commit_before>var fs = require('fs'),
	path = require('path'),
	_ = require('underscore'),
	express = require('express'),
	async = require('async'),
	jade = require('jade'),
	moment = require('moment'),
	numeral = require('numeral'),
	cloudinary = require('cloudinary'),
	utils = require('keystone-utils');

var templateCache = {};

/**
 * Don't use process.cwd() as it breaks module encapsulation
 * Instead, let's use module.parent if it's present, or the module itself if there is no parent (probably testing keystone directly if that's the case)
 * This way, the consuming app/module can be an embedded node_module and path resolutions will still work
 * (process.cwd() breaks module encapsulation if the consuming app/module is itself a node_module)
 */
var moduleRoot = (function(_rootPath) {
	var parts = _rootPath.split(path.sep);
	parts.pop(); //get rid of /node_modules from the end of the path
	return parts.join(path.sep);
})(module.parent ? module.parent.paths[0] : module.paths[0]);

/**
 * Keystone Class
 *
 * @api public
 */

var Keystone = function() {

	this.lists = {};
	this.paths = {};
	this._options = {
		'name': 'Keystone',
		'brand': 'Keystone',
		'compress': true,
		'headless': false,
		'logger': 'dev',
		'auto update': false,
		'model prefix': null
	};
	this._pre = {
		routes: [],
		render: []
	};
	this._redirects = {};

	// expose express

	this.express = express;

	// init environment defaults

	this.set('env', process.env.NODE_ENV || 'development');

	this.set('port', process.env.PORT || process.env.OPENSHIFT_NODEJS_PORT);
	this.set('host', process.env.HOST || process.env.IP || process.env.OPENSHIFT_NODEJS_IP);
	this.set('listen', process.env.LISTEN);

	this.set('ssl', process.env.SSL);
	this.set('ssl port', process.env.SSL_PORT);
	this.set('ssl host', process.env.SSL_HOST || process.env.SSL_IP);
	this.set('ssl key', process.env.SSL_KEY);
	this.set('ssl cert', process.env.SSL_CERT);

	this.set('cookie secret', process.env.COOKIE_SECRET);
	this.set('cookie signin', (this.get('env') === 'development') ? true : false);

	this.set('embedly api key', process.env.EMBEDLY_API_KEY || process.env.EMBEDLY_APIKEY);
	this.set('mandrill api key', process.env.MANDRILL_API_KEY || process.env.MANDRILL_APIKEY);
	this.set('mandrill username', process.env.MANDRILL_USERNAME);
	this.set('google api key', process.env.GOOGLE_BROWSER_KEY);
	this.set('google server api key', process.env.GOOGLE_SERVER_KEY);
	this.set('ga property', process.env.GA_PROPERTY);
	this.set('ga domain', process.env.GA_DOMAIN);
	this.set('chartbeat property', process.env.CHARTBEAT_PROPERTY);
	this.set('chartbeat domain', process.env.CHARTBEAT_DOMAIN);
	this.set('allowed ip ranges', process.env.ALLOWED_IP_RANGES);

	if (process.env.S3_BUCKET && process.env.S3_KEY && process.env.S3_SECRET) {
		this.set('s3 config', { bucket: process.env.S3_BUCKET, key: process.env.S3_KEY, secret: process.env.S3_SECRET, region: process.env.S3_REGION });
	}

	if (process.env.AZURE_STORAGE_ACCOUNT && process.env.AZURE_STORAGE_ACCESS_KEY) {
		this.set('azurefile config', { account: process.env.AZURE_STORAGE_ACCOUNT, key: process.env.AZURE_STORAGE_ACCESS_KEY });
	}

	if (process.env.CLOUDINARY_URL) {
		// process.env.CLOUDINARY_URL is processed by the cloudinary package when this is set
		this.set('cloudinary config', true);
	}

	// Attach middleware packages, bound to this instance
	this.initAPI = require('./lib/middleware/initAPI')(this);

};

_.extend(Keystone.prototype, require('./lib/core/options')(moduleRoot));

/**
 * Registers a pre-event handler.
 *
 * Valid events include:
 * - `routes` - calls the function before any routes are matched, after all other middleware
 *
 * @param {String} event
 * @param {Function} function to call
 * @api public
 */

Keystone.prototype.pre = function(event, fn) {
	if (!this._pre[event]) {
		throw new Error('keystone.pre() Error: event ' + event + ' does not exist.');
	}
	this._pre[event].push(fn);
	return this;
};

Keystone.prototype.prefixModel = function (key) {
	var modelPrefix = this.get('model prefix');

	if (modelPrefix)
		key = modelPrefix + '_' + key;

	return require('mongoose/lib/utils').toCollectionName(key);
};

/* Attach core functionality to Keystone.prototype */
Keystone.prototype.init = require('./lib/core/init');
Keystone.prototype.initNav = require('./lib/core/initNav');
Keystone.prototype.connect = require('./lib/core/connect');
Keystone.prototype.start = require('./lib/core/start');
Keystone.prototype.mount = require('./lib/core/mount');
Keystone.prototype.routes = require('./lib/core/routes');
Keystone.prototype.static = require('./lib/core/static');
Keystone.prototype.render = require('./lib/core/render');
Keystone.prototype.importer = require('./lib/core/importer');
Keystone.prototype.createItems = require('./lib/core/createItems');
Keystone.prototype.populateRelated = require('./lib/core/populateRelated');
Keystone.prototype.redirect = require('./lib/core/redirect');
Keystone.prototype.list = require('./lib/core/list');
Keystone.prototype.getOrphanedLists = require('./lib/core/getOrphanedLists');
Keystone.prototype.bindEmailTestRoutes = require('./lib/core/bindEmailTestRoutes');
Keystone.prototype.wrapHTMLError = require('./lib/core/wrapHTMLError');

/**
 * The exports object is an instance of Keystone.
 *
 * @api public
 */

var keystone = module.exports = exports = new Keystone();

// Expose modules and Classes
keystone.utils = utils;
keystone.content = require('./lib/content');
keystone.List = require('./lib/list');
keystone.Field = require('./lib/field');
keystone.Field.Types = require('./lib/fieldTypes');
keystone.View = require('./lib/view');
keystone.Email = require('./lib/email');

keystone.security = {
	csrf: require('./lib/security/csrf')
};

/**
 * returns all .js modules (recursively) in the path specified, relative
 * to the module root (where the keystone project is being consumed from).
 *
 * ####Example:
 *
 *     var models = keystone.import('models');
 *
 * @param {String} dirname
 * @api public
 */

Keystone.prototype.import = function(dirname) {

	var initialPath = path.join(moduleRoot, dirname);

	var doImport = function(fromPath) {

		var imported = {};

		fs.readdirSync(fromPath).forEach(function(name) {

			var fsPath = path.join(fromPath, name),
			info = fs.statSync(fsPath);

			// recur
			if (info.isDirectory()) {
				imported[name] = doImport(fsPath);
			} else {
				// only import files that we can `require`
				var ext  = path.extname(name);
				var base = path.basename(name, ext);
				if (require.extensions[ext]) {
					imported[base] = require(fsPath);
				}
			}

		});

		return imported;
	};

	return doImport(initialPath);
};

/**
 * Applies Application updates
 */

Keystone.prototype.applyUpdates = function(callback) {
	require('./lib/updates').apply(callback);
};

/**
 * Logs a configuration error to the console
 *
 * @api public
 */

Keystone.prototype.console = {};
Keystone.prototype.console.err = function(type, msg) {

	if (keystone.get('logger')) {
		var dashes = '\n------------------------------------------------\n';
		console.log(dashes + 'KeystoneJS: ' + type + ':\n\n' + msg + dashes);
	}

};

/**
 * Keystone version
 *
 * @api public
 */

keystone.version = require('./package.json').version;

// Expose Modules
keystone.session = require('./lib/session');
<commit_msg>Expose Keystone class<commit_after>var fs = require('fs'),
	path = require('path'),
	_ = require('underscore'),
	express = require('express'),
	async = require('async'),
	jade = require('jade'),
	moment = require('moment'),
	numeral = require('numeral'),
	cloudinary = require('cloudinary'),
	utils = require('keystone-utils');

var templateCache = {};

/**
 * Don't use process.cwd() as it breaks module encapsulation
 * Instead, let's use module.parent if it's present, or the module itself if there is no parent (probably testing keystone directly if that's the case)
 * This way, the consuming app/module can be an embedded node_module and path resolutions will still work
 * (process.cwd() breaks module encapsulation if the consuming app/module is itself a node_module)
 */
var moduleRoot = (function(_rootPath) {
	var parts = _rootPath.split(path.sep);
	parts.pop(); //get rid of /node_modules from the end of the path
	return parts.join(path.sep);
})(module.parent ? module.parent.paths[0] : module.paths[0]);

/**
 * Keystone Class
 *
 * @api public
 */

var Keystone = function() {

	this.lists = {};
	this.paths = {};
	this._options = {
		'name': 'Keystone',
		'brand': 'Keystone',
		'compress': true,
		'headless': false,
		'logger': 'dev',
		'auto update': false,
		'model prefix': null
	};
	this._pre = {
		routes: [],
		render: []
	};
	this._redirects = {};

	// expose express

	this.express = express;

	// init environment defaults

	this.set('env', process.env.NODE_ENV || 'development');

	this.set('port', process.env.PORT || process.env.OPENSHIFT_NODEJS_PORT);
	this.set('host', process.env.HOST || process.env.IP || process.env.OPENSHIFT_NODEJS_IP);
	this.set('listen', process.env.LISTEN);

	this.set('ssl', process.env.SSL);
	this.set('ssl port', process.env.SSL_PORT);
	this.set('ssl host', process.env.SSL_HOST || process.env.SSL_IP);
	this.set('ssl key', process.env.SSL_KEY);
	this.set('ssl cert', process.env.SSL_CERT);

	this.set('cookie secret', process.env.COOKIE_SECRET);
	this.set('cookie signin', (this.get('env') === 'development') ? true : false);

	this.set('embedly api key', process.env.EMBEDLY_API_KEY || process.env.EMBEDLY_APIKEY);
	this.set('mandrill api key', process.env.MANDRILL_API_KEY || process.env.MANDRILL_APIKEY);
	this.set('mandrill username', process.env.MANDRILL_USERNAME);
	this.set('google api key', process.env.GOOGLE_BROWSER_KEY);
	this.set('google server api key', process.env.GOOGLE_SERVER_KEY);
	this.set('ga property', process.env.GA_PROPERTY);
	this.set('ga domain', process.env.GA_DOMAIN);
	this.set('chartbeat property', process.env.CHARTBEAT_PROPERTY);
	this.set('chartbeat domain', process.env.CHARTBEAT_DOMAIN);
	this.set('allowed ip ranges', process.env.ALLOWED_IP_RANGES);

	if (process.env.S3_BUCKET && process.env.S3_KEY && process.env.S3_SECRET) {
		this.set('s3 config', { bucket: process.env.S3_BUCKET, key: process.env.S3_KEY, secret: process.env.S3_SECRET, region: process.env.S3_REGION });
	}

	if (process.env.AZURE_STORAGE_ACCOUNT && process.env.AZURE_STORAGE_ACCESS_KEY) {
		this.set('azurefile config', { account: process.env.AZURE_STORAGE_ACCOUNT, key: process.env.AZURE_STORAGE_ACCESS_KEY });
	}

	if (process.env.CLOUDINARY_URL) {
		// process.env.CLOUDINARY_URL is processed by the cloudinary package when this is set
		this.set('cloudinary config', true);
	}

	// Attach middleware packages, bound to this instance
	this.initAPI = require('./lib/middleware/initAPI')(this);

};

_.extend(Keystone.prototype, require('./lib/core/options')(moduleRoot));

/**
 * Registers a pre-event handler.
 *
 * Valid events include:
 * - `routes` - calls the function before any routes are matched, after all other middleware
 *
 * @param {String} event
 * @param {Function} function to call
 * @api public
 */

Keystone.prototype.pre = function(event, fn) {
	if (!this._pre[event]) {
		throw new Error('keystone.pre() Error: event ' + event + ' does not exist.');
	}
	this._pre[event].push(fn);
	return this;
};

Keystone.prototype.prefixModel = function (key) {
	var modelPrefix = this.get('model prefix');

	if (modelPrefix)
		key = modelPrefix + '_' + key;

	return require('mongoose/lib/utils').toCollectionName(key);
};

/* Attach core functionality to Keystone.prototype */
Keystone.prototype.init = require('./lib/core/init');
Keystone.prototype.initNav = require('./lib/core/initNav');
Keystone.prototype.connect = require('./lib/core/connect');
Keystone.prototype.start = require('./lib/core/start');
Keystone.prototype.mount = require('./lib/core/mount');
Keystone.prototype.routes = require('./lib/core/routes');
Keystone.prototype.static = require('./lib/core/static');
Keystone.prototype.render = require('./lib/core/render');
Keystone.prototype.importer = require('./lib/core/importer');
Keystone.prototype.createItems = require('./lib/core/createItems');
Keystone.prototype.populateRelated = require('./lib/core/populateRelated');
Keystone.prototype.redirect = require('./lib/core/redirect');
Keystone.prototype.list = require('./lib/core/list');
Keystone.prototype.getOrphanedLists = require('./lib/core/getOrphanedLists');
Keystone.prototype.bindEmailTestRoutes = require('./lib/core/bindEmailTestRoutes');
Keystone.prototype.wrapHTMLError = require('./lib/core/wrapHTMLError');

/**
 * The exports object is an instance of Keystone.
 *
 * @api public
 */

var keystone = module.exports = exports = new Keystone();

// Expose modules and Classes
keystone.utils = utils;
keystone.Keystone = Keystone;
keystone.content = require('./lib/content');
keystone.List = require('./lib/list');
keystone.Field = require('./lib/field');
keystone.Field.Types = require('./lib/fieldTypes');
keystone.View = require('./lib/view');
keystone.Email = require('./lib/email');

keystone.security = {
	csrf: require('./lib/security/csrf')
};

/**
 * returns all .js modules (recursively) in the path specified, relative
 * to the module root (where the keystone project is being consumed from).
 *
 * ####Example:
 *
 *     var models = keystone.import('models');
 *
 * @param {String} dirname
 * @api public
 */

Keystone.prototype.import = function(dirname) {

	var initialPath = path.join(moduleRoot, dirname);

	var doImport = function(fromPath) {

		var imported = {};

		fs.readdirSync(fromPath).forEach(function(name) {

			var fsPath = path.join(fromPath, name),
			info = fs.statSync(fsPath);

			// recur
			if (info.isDirectory()) {
				imported[name] = doImport(fsPath);
			} else {
				// only import files that we can `require`
				var ext  = path.extname(name);
				var base = path.basename(name, ext);
				if (require.extensions[ext]) {
					imported[base] = require(fsPath);
				}
			}

		});

		return imported;
	};

	return doImport(initialPath);
};

/**
 * Applies Application updates
 */

Keystone.prototype.applyUpdates = function(callback) {
	require('./lib/updates').apply(callback);
};

/**
 * Logs a configuration error to the console
 *
 * @api public
 */

Keystone.prototype.console = {};
Keystone.prototype.console.err = function(type, msg) {

	if (keystone.get('logger')) {
		var dashes = '\n------------------------------------------------\n';
		console.log(dashes + 'KeystoneJS: ' + type + ':\n\n' + msg + dashes);
	}

};

/**
 * Keystone version
 *
 * @api public
 */

keystone.version = require('./package.json').version;

// Expose Modules
keystone.session = require('./lib/session');
<|endoftext|>


<commit_before>var url = require('url');
var path = require('path');
var configure = require('open-in-editor').configure;
var MESSAGE_PREFIX = '[' + require('./package.json').name + '] ';

function fail(res, code, message) {
    res.statusCode = code;
    res.end(MESSAGE_PREFIX + message);
}

module.exports = function(options) {
    var cwd = path.resolve((options && options.cwd) || process.cwd());
    var opener = configure(options || {}, function(err) {
        console.warn(MESSAGE_PREFIX + 'Configure error:', err);
    });

    return function openInEditor(req, res) {
        if (!opener) {
            var msg = 'Request to open file failed, editor is not set up';
            console.warn(MESSAGE_PREFIX + msg);
            return fail(res, 400, msg);
        }

        var filename = url.parse(req.url, true).query.file;

        if (!filename) {
            return fail(res, 400, 'Parameter missed: file');
        }

        // temporary solution
        // should take in account options.base
        filename = path
            .join(cwd, path.resolve('/', filename))
            .replace(/^[a-z]+:/i, ''); // cut drive from path on Windows platform

        opener.open(filename).then(
            function() {
                res.statusCode = 200;
                res.end('Open in editor: ' + filename);
            },
            function(e) {
                fail(res, 500, 'ERROR: ' + e);
            }
        );
    };
};
<commit_msg>fix cut drive on Windows<commit_after>var url = require('url');
var path = require('path');
var configure = require('open-in-editor').configure;
var MESSAGE_PREFIX = '[' + require('./package.json').name + '] ';

function fail(res, code, message) {
    res.statusCode = code;
    res.end(MESSAGE_PREFIX + message);
}

module.exports = function(options) {
    var cwd = path.resolve((options && options.cwd) || process.cwd());
    var opener = configure(options || {}, function(err) {
        console.warn(MESSAGE_PREFIX + 'Configure error:', err);
    });

    return function openInEditor(req, res) {
        if (!opener) {
            var msg = 'Request to open file failed, editor is not set up';
            console.warn(MESSAGE_PREFIX + msg);
            return fail(res, 400, msg);
        }

        var filename = url.parse(req.url, true).query.file;

        if (!filename) {
            return fail(res, 400, 'Parameter missed: file');
        }

        // temporary solution
        // should take in account options.base
        filename = path.join(
            cwd,
            path
                .resolve('/', filename)
                .replace(/^[a-z]+:/i, '') // cut drive from path on Windows platform
        );

        opener.open(filename).then(
            function() {
                res.statusCode = 200;
                res.end('Open in editor: ' + filename);
            },
            function(e) {
                fail(res, 500, 'ERROR: ' + e);
            }
        );
    };
};
<|endoftext|>