示例#1
0
文件: build.js 项目: MMeent/six-speed
    function(callback) {
      var types = {};
      _.each(scripts, function(script) {
        if ((/.*__(.*)\.js$/).exec(script)) {
          var type = types[RegExp.$1];
          if (!type) {
            type = types[RegExp.$1] = [];

            type.push('benchmark.js');
            if (RegExp.$1 === 'traceur') {
              type.push('traceur-runtime.js');
            } else if (RegExp.$1 === 'babel') {
              type.push('polyfill.js');
            }
            type.push('runner.js');
          }
          type.push(script);
        }
      });
      scripts.push('worker.js');
      scripts.push('browser.js');

      this.push(new GUtil.File({
        path: 'index.html',
        contents: new Buffer(benchTemplate({scripts: scripts}))
      }));

      // We need a special mime type to enable all of the features on Firefox.
      var mozScripts = _.map(scripts, function(script) { return '../' + script; });
      mozScripts[mozScripts.length - 2] = '../iframe.js';
      this.push(new GUtil.File({
        path: 'moz/index.html',
        contents: new Buffer(benchTemplate({
          scripts: mozScripts,
          jsType: 'application/javascript;version=1.7'
        }))
      }));

      _.each(types, function(scripts, name) {
        var workerScripts = scripts.concat('worker-test.js');
        this.push(new GUtil.File({
          path: name + '.js',
          contents: new Buffer(
            '$type = ' + JSON.stringify(name) + ';\n'
            + workerScripts.map(function(script) { return 'try { importScripts(' + JSON.stringify(script) + '); } catch (err) { console.log(' + JSON.stringify(script) + ' + err); }'; }).join('\n'))
        }));

        // We need a special mime type to enable all of the features on Firefox.
        var mozScripts = _.map(scripts, function(script) { return '../' + script; });
        this.push(new GUtil.File({
          path: 'moz/' + name + '.html',
          contents: new Buffer(benchTemplate({scripts: mozScripts, jsType: 'application/javascript;version=1.7'}))
        }));
      }, this);


      scripts[scripts.length - 1] = 'browser-profile.js';
      this.push(new GUtil.File({
        path: 'profile.html',
        contents: new Buffer(profileTemplate({scripts: scripts}))
      }));

      // We need a special mime type to enable all of the features on Firefox.
      this.push(new GUtil.File({
        path: 'moz/profile.html',
        contents: new Buffer(profileTemplate({
          scripts: _.map(scripts, function(script) { return '../' + script; }),
          jsType: 'application/javascript;version=1.7'
        }))
      }));

      callback();
    }))
示例#2
0
文件: rttc.js 项目: Latros/machine
var rttc = function(def, val, options) {

  options = options || {};

  // Should the value be coerced into the proper type?
  var coerce = options.coerce || false;

  // If the value can't be coerced should we use the base of the type for the value?
  // ex: NaN gets set as 0
  var baseType = options.base || false;

  // Hold our errors and return them all at once
  var errors = [];

  var parseObject = function(input, value) {
    _.each(_.keys(input), function(key) {
      var _input = input[key];
      var _value = value[key];

      // If the input is an object continue recursively parsing it
      if(types.obj.is(_input)) {
        parseObject(_input, _value);
        return;
      }

      _value = coerceValue(_input, _value, { coerce: coerce, baseType: baseType });
      var valid = checkTuple(_input, _value);
      if(!valid) {
        throw new Error('Invalid input value ', value);
      }

      value[key] = _value;
    });

    // Find the difference in the input and the value and remove any keys that
    // exist on the value but not on the input definition.
    var inputKeys = _.keys(input);
    var valueKeys = _.keys(value);
    var invalidKeys = _.difference(valueKeys, inputKeys);

    _.each(invalidKeys, function(key) {
      delete value[key];
    });

    return value;
  };

  // If we don't have an object then just check the tuple
  // If the input type isn't an object or array we can just do a simple type check
  if(!_.isPlainObject(def)) {
    val = coerceValue(def, val, { coerce: coerce, baseType: baseType });
    var valid = checkTuple(def, val);
    if(!valid) {
      var err = new Error();
      err.code = 'E_INVALID_TYPE';
      err.message = util.format(
        'An invalid value was specified. The value ' + val + ' was used \n' +
        'and doesn\'t match the specified type: ' + def
      );
      throw err;
    }

    return val;
  }

  // For each input, ensure the type is valid
  _.each(_.keys(def), function(inputName) {

    var input = def[inputName];
    var value = val[inputName];
    var err = new Error();

    // If the input has a valid flag on it, we don't need to use runtime type checking on
    // it because it has been run through a validate function.
    if(input && input.valid) {
      return;
    }

    // Check if the input is required and missing
    if(types.undefined.is(value)) {

      if (input.required) {
        err.code = 'E_REQUIRED_INPUT';
        err.message = util.format(
          'The input ' + inputName + ' is a required input and no value was specified.'
        );

        errors.push(err);
      }

      return;
    }

    // If the input is an array, parse it for each item
    if(_.isArray(input.type)) {
      if(value && !types.arr.is(value)) {
        err.code = 'E_INVALID_TYPE';
        err.message = util.format(
          'An invalid value was specified. The value ' + value + ' was used \n' +
          'and doesn\'t match the specified type: ' + input.type
        );

        errors.push(err);
        return;
      }

      // If the input is required and the value array is empty, it's an error
      if(input.required && value.length < 1) {
        err.code = 'E_REQUIRED_INPUT';
        err.message = util.format(
          'The input ' + inputName + ' is a required input and no value was specified.'
        );

        errors.push(err);
        return;
      }

      // if the input is a ['*'] this is a typeclass array and we can build a schema
      // based on the first item in the array.
      if(input.type[0] === '*') {
        var type = value.length ? value[0] : 'foo';

        // Infer the type
        var inferred = infer(type);
        input.type = [inferred];
      }

      _.each(value, function(item) {

        // Handle an array of objects
        if(types.obj.is(input.type[0])) {
          try {
            item = parseObject(input.type[0], item);
          }
          catch (err) {
            err.code = 'E_INVALID_TYPE';
            err.message = util.format(
              'An invalid value was specified. The value ' + item + ' was used \n' +
              'and doesn\'t match the specified type: ' + input.type[0]
            );

            errors.push(err);
            return;
          }
        }

        // Handle an array of primative values
        else {
          try {
            item = coerceValue(input.type[0], item, { coerce: coerce, baseType: baseType });
            var valid = checkTuple(input.type[0], item)
            if(!valid) {
              errors.push('Invalid type for input: ' + inputName);
              return;
            }
          }
          catch (e) {
            errors.push(e, inputName);
            return;
          }
        }
      });

      val[inputName] = value;
      return;
    }

    // if the input is an object, recursively parse it
    if(types.obj.is(input.type)) {

      // If the schema is an empty object any object values are allowed to validate
      if(!_.keys(input.type).length) {
        if(_.isPlainObject(value)) return val;
        errors.push('Invalid type for input: ' + inputName);
      }

      try {
        value = parseObject(input.type, value);
      }
      catch (err) {
        errors.push('Invalid type for input: ' + inputName);
        return;
      }

      val[inputName] = value;
      return;
    }

    // If the input type isn't an object or array we can just do a simple type check
    try {

      // If a value is optional and not required and we don't need a baseType then
      // we can just return the undefined value
      if(_.isUndefined(value) && !input.required && !baseType) {
        return;
      }

      value = coerceValue(input.type, value, { coerce: coerce, baseType: baseType });
      var valid = checkTuple(input.type, value)
      if(!valid) {
        errors.push('Invalid type for input: ' + inputName);
        return;
      }
    }
    catch (e) {
      errors.push(e, inputName);
      return;
    }

    val[inputName] = value;
    return;
  });

  if(errors.length) {
    throw new Error(errors);
  }

  // Remove keys not in the schema
  var diff = _.difference(_.keys(val), _.keys(def));
  _.each(diff, function(removeKey) {
    delete val[removeKey];
  });

  return val;
};
示例#3
0
function add() {
  var shortname = argv._[1];
  var mac = argv._[2];
  if (argv._.length !== 3) {
    usage();
  }

  if (!shortname.match(/[\w\-]+/)) {
    console.error('shortname must contain only letters, digits and dashes');
    usage();
  }

  if (!mac.match(/[0-9a-f\:]+/)) {
    console.error('mac addresses look like this: c8:bc:c8:92:cb:aa');
    usage();
  }

  var pushed = false;
  var methods = [ sameShortname, sameMac, newKid ];

  // Stops early if one of them returns "false"
  _.each(methods, function(method) {
    return method();
  });

  if (!pushed) {
    console.error('Uh-oh, fresh out of IP addresses!');
    process.exit(2);
  }

  writeAndRestart({ forgetLease: mac });

  function sameShortname() {
    var existing = _.find(data.hosts, function(host) {
      return host.shortname === shortname;
    });
    if (existing) {
      existing.mac = mac;
      pushed = true;
      return false;
    }
  }

  function sameMac() {
    var existing = _.find(data.hosts, function(host) {
      return host.mac === mac;
    });
    if (existing) {
      existing.shortname = shortname;
      pushed = true;
      return false;
    }
  }

  function newKid() {
    iterateIps(settings.staticRange.low, settings.staticRange.high, function(ip) {
      if (!_.find(data.hosts, function(host) {
        return host.ip === ip;
      })) {
        data.hosts = (data.hosts || []).concat({
          shortname: argv._[1],
          mac: argv._[2],
          ip: ip
        });
        pushed = true;
        // Stop iterating, we found an open address
        return false;
      }
    });
    if (pushed) {
      return false;
    }
  }
}
示例#4
0
文件: engine.js 项目: titarenko/taskr
	function subscribeMessageHandlers () {
		_.each(handlers, function (handler, task) {
			var options = { concurrency: concurrency[task] || 1 };
			medium.subscribe(task, _.partial(handleMessage, task, handler), options);
		});
	}
示例#5
0
  once: true,
  parser: {
    paths: [path.join(FRONTEND_PATH, "public", "stylesheets"), path.join(__dirname, "..", "node_modules")]
  }
}));
app.use(express.static(path.join(FRONTEND_PATH, "public")));

_.each(ROUTES, function (value, route) {
  if (_.isArray(value)) {
    _.each(value, function (value) {
      if (value.apiRouter) {
        app.use("/api/v1" + route, value.apiRouter);
        app.use("/api" + route, value.apiRouter);
      }
      app.use(route, value.router);
    })
  } else {
    if (value.apiRouter) {
      app.use("/api/v1" + route, value.apiRouter);
      app.use("/api" + route, value.apiRouter);
    }
    app.use(route, value.router);
  }
});

// error handlers

app.use(function (req, res, next) {
  let err = new Error("Not Found");
  err.status = 404;
  next(err);
示例#6
0
  var recMap = function(node) {

    if (isTask(node)) {

      // This is a task so do nothing.
      return [node];

    } else if (isBranch(node)) {

      // Concat map children with a recMap.
      node.children = _.flatten(_.map(node.children, recMap));

      // Sort children.
      node.children.sort(compareBranchOrTask);

      // Resolve duplicate named children.
      // Group children by name.
      var nameMap = _.groupBy(node.children, getName);
      // Resolve conflicts.
      node.children = _.map(_.values(nameMap), function(children) {

        if (children.length === 1) {

          // No conflicts so just return head of array.
          return children[0];

        } else {

          // Resolve conflict by finding a single node with the override flag.
          var overrides = _.filter(children, function(child) {
            return child.__override;
          });

          if (overrides.length === 1) {

            // Conflict resolved.
            return overrides[0];

          } else {

            // Conflict can not be resolved, throw an error.
            throw new Error('Conflicting task names can not be resolved: ' +
              pp(children));

          }

        }

      });

      if (getName(node) === appName) {

        // Replace this node with this nodes children.
        _.each(node.children, function(child) {
          // Mark each child with an override flag so we can resolve conflicts.
          child.__override = true;
        });
        return node.children;

      } else {

        // Just return.
        return [node];

      }

    } else {

      // This should never happen.
      assert(false);

    }

  };
示例#7
0
 _.each(self.stack, function(route){
   _.each(self.stack[route], function(fn){
     self.switchboard.cancel(route, fn);
   })
 })
示例#8
0
文件: bot.js 项目: Ustice/Slacker
exports.processRequest = function  processRequest (request, response) {
  var
    actionFound,
    commands,
    input,
    outgoingData,
    pipedResponse,
    regex,
    requestText,
    responseMethod,
    responseText,
    VARIABLES
  ;

  input = request.body.text;

  // The keys on this object will be replaced with their corresponding values
  // at runtime.
  VARIABLES = {
    'HERE': '#' + request.body.channel_name,
    'ME': '@' + request.body.user_name,
    'TODAY': new Date(Date.now()).toDateString(),
    'NOW': new Date(Date.now()).toLocaleTimeString(),
    'DOMAIN': request.body.team_domain
  };

  _.each(VARIABLES, function (value, key){
    regex = new RegExp('%24' + key, 'gm');
    input = input.replace(regex, value);
  });

  // Parse commands
  commands = parse.commands(input);
  responseMethod = (request.body.trigger_word) ? 'webhook' : 'api';

  requestText;
  if (request.body.trigger_word)
    requestText = parse.slackText(input.substring(request.body.trigger_word.length + 1, input.length));
  else {// command
    requestText = decodeURIComponent(input.replace(/\+/g, '%20'));
  }
  log.info('bot processing request', request.body, request.id);

  outgoingData = {
    channel_id:   request.body.channel_id,
    channel_name: request.body.channel_name,
    team_domain:  request.body.team_domain,
    team_id:      request.body.team_id,
    text:         requestText,
    timestamp:    request.body.timestamp,
    user_id:      request.body.user_id,
    user_name:    request.body.user_name
  };

  responseText;
  actionFound;
  pipedResponse = null;


  _.each(commands, function (command) {
    actionFound = _.find(exports.actions, {name: command.name});

    // Actions desn't exist. Inform the user.
    if (!actionFound) {
      log.error('no bot action found', requestText, request.id);
      responseText = 'Invalid action, try `help`.';
      response.statusCode = 200;
      response.end(formatResponse(responseText));
    }

    // If the action hasn't completed in time, let the user know.
    setTimeout(function() {
      if (!responseText) {
        log.error('bot action timed out', actionFound.name, request.id);
        response.statusCode = 500;
        response.end();
      }
    }, config.timeout);

    outgoingData.command = _.clone(command);
    outgoingData.pipedResponse = _.clone(pipedResponse);
    actionFound.execute(outgoingData, function (actionResponse) {
      responseText = actionResponse;

      // No data back form the action.
      if (!responseText) {
        response.statusCode = 500;
        response.end();
        log.error('action did not return a response', actionFound.name, request.id);
        return;
      }

      // Success. Now, format the responseText.
      log.info('bot responding with action', actionFound.name, request.id);
      if (typeof responseText === 'string') {
        responseText.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;');
      } else {
        responseText = JSON.stringify(responseText);
      }

      // If the command should be piped, save the result.
      if (command.pipe) {
        pipedResponse = responseText;
        return true;
      } else {
        pipedResponse = null;
      }

      // User is ending their command with the `>`. Assume current room.
      if (command.redirects && !command.redirectTo.length) {
        command.redirectTo.push({ type: 'channel', name: request.body.channel_name });
      }

      // If the response should be redirected, then do so
      if (command.redirectTo.length > 0) {
        _.each(command.redirectTo, function (redirect) {
          switch (redirect.type) {
            case 'user':
              exports.sendMessage(responseText, '@' + redirect.name);
              break;

            case 'channel':
              exports.sendMessage(responseText, '#' + redirect.name);
              break;

            case 'group':
              exports.sendMessage(responseText, '#' + redirect.name);
              break;

            case 'file':
              // Todo file creation/editing
              break;

            default:
              break;
          }
        });
        return true;
      }

      response.statusCode = 200;
      response.end(formatResponse(responseText));
      log.info('bot successfully responded', {}, request.id);

      return true;
    });

  });

  function formatResponse (response) {

    return (request.body.trigger_word) ? JSON.stringify({text: response}) : response;
  }
};
示例#9
0
文件: game.js 项目: cixzhang/gatherer
 render: function (time) {
   this.renderer.render(this.stage);
   _.each(this.renderers, function (render) {
     render(time);
   });
 },
示例#10
0
TimerManager.prototype.clearAll = function() {
  var _this = this;
  _.each(this.timers, function(timer, id) {
    _this.clear(id);
  });
};
示例#11
0
文件: bot.js 项目: Ustice/Slacker
    actionFound.execute(outgoingData, function (actionResponse) {
      responseText = actionResponse;

      // No data back form the action.
      if (!responseText) {
        response.statusCode = 500;
        response.end();
        log.error('action did not return a response', actionFound.name, request.id);
        return;
      }

      // Success. Now, format the responseText.
      log.info('bot responding with action', actionFound.name, request.id);
      if (typeof responseText === 'string') {
        responseText.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;');
      } else {
        responseText = JSON.stringify(responseText);
      }

      // If the command should be piped, save the result.
      if (command.pipe) {
        pipedResponse = responseText;
        return true;
      } else {
        pipedResponse = null;
      }

      // User is ending their command with the `>`. Assume current room.
      if (command.redirects && !command.redirectTo.length) {
        command.redirectTo.push({ type: 'channel', name: request.body.channel_name });
      }

      // If the response should be redirected, then do so
      if (command.redirectTo.length > 0) {
        _.each(command.redirectTo, function (redirect) {
          switch (redirect.type) {
            case 'user':
              exports.sendMessage(responseText, '@' + redirect.name);
              break;

            case 'channel':
              exports.sendMessage(responseText, '#' + redirect.name);
              break;

            case 'group':
              exports.sendMessage(responseText, '#' + redirect.name);
              break;

            case 'file':
              // Todo file creation/editing
              break;

            default:
              break;
          }
        });
        return true;
      }

      response.statusCode = 200;
      response.end(formatResponse(responseText));
      log.info('bot successfully responded', {}, request.id);

      return true;
    });
 support.listenOnce(notification.store, state => {
   _.each(opts.messageIds, messageId =>
     assert.equal(state.notifications.get(messageId), opts.expectKind)
   )
   done()
 })
 function simulateMessages(ids, state) {
   notification.store.messagesChanged(ids, state)
   _.each(ids, id =>
     notification.store.messageReceived(state.messages.get(id), state)
   )
 }
示例#14
0
    bumpFunc(type, ['./package.json'], './')
};

var bumpDistFunc = function (type) {
    bumpFunc(type, ['./dist/package.json', './dist/bower.json'], './dist')
};

var bumpFunc = function (type, sources, dest) {
    gulp.src(sources)
        .pipe(bump({type: type}))
        .pipe(gulp.dest(dest));
};

// Update bower, component, npm at once:
_.each(["major", "minor", "patch", "prerelease"], function (type) {
    registerBumpFunc(type, 'src', bumpSrcFunc);
    registerBumpFunc(type, 'dist', bumpDistFunc)
});

//gulp.task('ololo', function(){
//    return gulp.src('./bower.json',  { cwd: './dist' })
//        .pipe(bump({type: 'patch'}))
//        .pipe(gulp.dest('./',{ cwd: './dist' }))
//        .pipe(git.commit('bumps package version',{cwd: './dist'}))
//        .pipe(filter('bower.json'))
//        .pipe(tag_version({cwd: './dist'}));
//});

// dependencies
var git = require('gulp-git'),
    filter = require('gulp-filter'),
    print = require('gulp-print'),
    function processDistributionData() {
      const distributionData = _.get(scope, ['card', 'stats', 'distribution', 'percentiles'], []);
      const chartData = [];

      // Process the raw distribution data so it is in a suitable format for plotting:
      if (distributionData.length === 0) {
        return chartData;
      }

      // Adjust x axis min and max if there is a single bar.
      const minX = distributionData[0].minValue;
      const maxX = distributionData[distributionData.length - 1].maxValue;
      xAxisMin = minX;
      xAxisMax = maxX;
      if (maxX === minX) {
        if (minX !== 0) {
          xAxisMin = 0;
          xAxisMax = 2 * minX;
        } else {
          xAxisMax = 1;
        }
      }

      // Adjust the right hand x coordinates so that each bar is
      // at least MIN_BAR_WIDTH.
      // TODO - make sure last bar isn't cropped at RHS.
      const minBarWidth = (MIN_BAR_WIDTH / chartWidth) * (xAxisMax - xAxisMin);
      const processedData = [];
      let lastBar = undefined;
      _.each(distributionData, (data, index) => {

        if (index === 0) {
          const bar = {
            x0: data.minValue,
            x1: Math.max(data.minValue + minBarWidth, data.maxValue),
            dataMin: data.minValue,
            dataMax: data.maxValue,
            percent: data.percent
          };

          // Scale the height of the bar according to the range of data values in the bar.
          bar.y = (data.percent / (bar.x1 - bar.x0)) *
            Math.max(1, (minBarWidth / Math.max((data.maxValue - data.minValue), 0.5 * minBarWidth)));
          bar.isMinWidth = (data.maxValue <= (data.minValue + minBarWidth));
          processedData.push(bar);
          lastBar = bar;
        } else {
          if (lastBar.isMinWidth === false || data.maxValue > lastBar.x1) {
            const bar = {
              x0: lastBar.x1,
              x1: Math.max(lastBar.x1 + minBarWidth, data.maxValue),
              dataMin: data.minValue,
              dataMax: data.maxValue,
              percent: data.percent
            };

            // Scale the height of the bar according to the range of data values in the bar.
            bar.y = (data.percent / (bar.x1 - bar.x0)) *
              Math.max(1, (minBarWidth / Math.max((data.maxValue - data.minValue), 0.5 * minBarWidth)));
            bar.isMinWidth = (data.maxValue <= (lastBar.x1 + minBarWidth));
            processedData.push(bar);
            lastBar = bar;
          } else {
            // Combine bars which are less than minBarWidth apart.
            lastBar.percent = lastBar.percent + data.percent;
            lastBar.y = lastBar.percent / (lastBar.x1 - lastBar.x0);
            lastBar.dataMax = data.maxValue;
          }
        }

      });

      if (maxX !== minX) {
        xAxisMax = _.last(processedData).x1;
      }

      // Adjust the maximum bar height to be (10 * median bar height).
      // TODO indicate if a bar height has been truncated?
      let barHeights = _.pluck(processedData, 'y');
      barHeights = barHeights.sort((a, b) => a - b);

      let maxBarHeight = 0;
      const processedDataLength = processedData.length;
      if (Math.abs(processedDataLength % 2) === 1) {
        maxBarHeight = 20 * barHeights[(Math.floor(processedDataLength / 2))];
      } else {
        maxBarHeight = 20 * (barHeights[(Math.floor(processedDataLength / 2)) - 1] +
          barHeights[(Math.floor(processedDataLength / 2))]) / 2;
      }

      _.each(processedData, (data) => {
        data.y = Math.min(data.y, maxBarHeight);
      });

      scope.processedData = processedData;

      chartData.push({ x: minX, y: 0 });
      _.each(processedData, (data) => {
        chartData.push({ x: data.x0, y: data.y });
        chartData.push({ x: data.x1, y: data.y });
      });
      chartData.push({ x: processedData[processedData.length - 1].x1, y: 0 });

      return chartData;
    }
 _.each(this._remotes, (urn) => {
     _.each(urn, (remote) => {
         if (!target || target === remote)
             remote.service.removeAllListeners("event");
     });
 });
示例#17
0
var preDecorate = function(task) {
  _.each(task.options, mixInOption);
};
示例#18
0
/**
 * Routes (Including Passport Routes)
 * --------------------
 * Sets up static routes for Derby app. Normally this wouldn't be necessary, would just place this logic
 * in middelware() setup. However, it breaks Derby routes - so we need this to call separately after expressApp
 * hass been initialized
 */
function setupStaticRoutes(expressApp, strategies, options) {

    // Persistent URLs (PURLs) (eg, http://localhost/users/{guid})
    // tests if UUID was used (bookmarked private url), and restores that session
    // Workflowy uses this method, for example
    expressApp.get('/users/:uid', function(req, res, next) {
        if (!options.allowPurl) return next();

        var uid = req.params.uid,
            sess = req.getModel().session;

        // if not already logged in , and is legit uid
        if ((sess.userId !== uid) && !sess.loggedIn && (require('guid').isGuid(uid))) {
            // TODO check if in database - issue with accessControl which is on current uid
            sess.userId = uid;
        }
        return res.redirect('/');
    });

    // POST /login
    //   Use passport.authenticate() as route middleware to authenticate the
    //   request.  If authentication fails, the user will be redirected back to the
    //   login page.  Otherwise, the primary route function function will be called,
    //   which, in this example, will redirect the user to the home page.
    //
    //   curl -v -d "username=bob&password=secret" http://127.0.0.1:3000/login
    expressApp.post('/login',
        passport.authenticate('local', { failureRedirect: options.failureRedirect, failureFlash: true }),
        function(req, res) {
            res.redirect('/');
        }
    );

    // POST /login
    //   This is an alternative implementation that uses a custom callback to
    //   acheive the same functionality.
    /*
     app.post('/login', function(req, res, next) {
     passport.authenticate('local', function(err, user, info) {
     if (err) { return next(err) }
     if (!user) {
     req.flash('error', info.message);
     return res.redirect('/login')
     }
     req.logIn(user, function(err) {
     if (err) { return next(err); }
     return res.redirect('/users/' + user.username);
     });
     })(req, res, next);
     });
     */

    expressApp.post('/register', function(req, res, next){
        var model = req.getModel()
            , sess = model.session;

        var q = model.query('users').withUsername(req.body.username);
        q.fetch(function(err, result){
            if (err) return next(err)

            var userObj = result.at(0).get();

            // current user already registered, return
            if (model.get('users.' + sess.userId + '.auth.local')) return res.redirect('/');

            if (userObj) {
                // a user already registered with that name, TODO send error message
                return res.redirect(options.failureRedirect);
            } else {
                // Legit, register
                var salt = utils.makeSalt(),
                    localAuth = {
                        username: req.body.username,
                        email: req.body.email,
                        salt: salt,
                        hashed_password: utils.encryptPassword(req.body.password, salt)
                    };
                model.set('users.' + sess.userId + '.auth.local', localAuth);
                model.set('users.' + sess.userId + '.auth.timestamps.created', new Date());
                req.login(sess.userId, function(err) {
                    if (err) { return next(err); }
                    return res.redirect('/');
                });
            }
        });
    });

    _.each(strategies, function(strategy, name){
        params = strategy.params || {}
        // GET /auth/facebook
        //   Use passport.authenticate() as route middleware to authenticate the
        //   request.  The first step in Facebook authentication will involve
        //   redirecting the user to facebook.com.  After authorization, Facebook will
        //   redirect the user back to this application at /auth/facebook/callback
        expressApp.get('/auth/'+name,
            passport.authenticate(name, params),
            function(req, res){
                // The request will be redirected to Facebook for authentication, so this
                // function will not be called.
            });

        // GET /auth/facebook/callback
        //   Use passport.authenticate() as route middleware to authenticate the
        //   request.  If authentication fails, the user will be redirected back to the
        //   login page.  Otherwise, the primary route function function will be called,
        //   which, in this example, will redirect the user to the home page.
        expressApp.get('/auth/' + name + '/callback',
            passport.authenticate(name, { failureRedirect: options.failureRedirect }),
            function(req, res) {
                res.redirect('/');
            });
    });

    expressApp.get('/logout', function(req, res){
        req.session.userId = undefined;
        req.logout();
        res.redirect('/');
    });

    expressApp.post('/password-reset', function(req, res){
        var model = req.getModel(),
            email = req.body.email,
            salt = utils.makeSalt(),
            newPassword =  utils.makeSalt(), // use a salt as the new password too (they'll change it later)
            hashed_password = utils.encryptPassword(newPassword, salt);

        model.fetch(model.query('users').withEmail(email), function(err, users){
            if (!err && !(users.get()[0])) err = "Somethign went wrong resetting password for " + email + ". Couldn't find user for some reason.";
            if (err) {
                console.log(err);
                return res.send(500, e);
            }

            // we use mongoskin to bypass racer's accessConrol settings where we're authorized.
            // TODO come up with a different accessControl approach, this shouldn't be necessary
            var mongo = require('mongoskin');
            mongo.db(model.store._db.options.uri).collection('users').update(
                {"auth.local.email": email},
                {$set: {'auth.local.salt': salt, 'auth.local.hashed_password': hashed_password} },
                function (err, items) {
                    console.dir({err:err, items:items});
                    if (err) return res.send(500, err);
                    sendEmail({
                        from: "HabitRPG <*****@*****.**>",
                        to: email,
                        subject: "Password Reset for HabitRPG",
                        text: "Your new password is " + newPassword + ". You an login at https://habitrpg.com"
                    });
                    return res.send('New password sent to '+ email);
            })

        })

    })

    // Simple route middleware to ensure user is authenticated.
    //   Use this route middleware on any resource that needs to be protected.  If
    //   the request is authenticated (typically via a persistent login session),
    //   the request will proceed.  Otherwise, the user will be redirected to the
    //   login page.
    //    function ensureAuthenticated(req, res, next) {
    //        if (req.isAuthenticated()) { return next(); }
    //        res.redirect('/login')
    //    }
}
示例#19
0
var fs=require("fs"),path=require("path"),_=require("lodash"),schedule=require("node-schedule");module.exports=function(a){function b(a){var b=[],c=[],d=function(a,b,c){files=fs.readdirSync(a),files.forEach(function(e){var f=a+"/"+e,g=fs.statSync(f);g.isDirectory()?(d(f,b,c),c.push(f)):b.push(f)})};return d(a,b,c),{files:b,folders:c}}var c=new schedule.RecurrenceRule;c.dayOfWeek=[0,new schedule.Range(1,6)],c.hour=20,c.minute=0,schedule.scheduleJob(c,function(){console.log("执行清理文件任务!"),_.each(_.dropRight(b("gifts").files,3),function(a){fs.unlink(a)})})};
示例#20
0
function setupPassport(strategies, options) {
    // Passport session setup.
    //   To support persistent login sessions, Passport needs to be able to
    //   serialize users into and deserialize users out of the session.  Typically,
    //   this will be as simple as storing the user ID when serializing, and finding
    //   the user by ID when deserializing.
    passport.serializeUser(function(uid, done) {
        done(null, uid);
    });

    passport.deserializeUser(function(id, done) {
        return done(null, id);

        // TODO Revisit:
        // Because we're logging a user into req.session on passport strategy authentication,
        // we don't need to deserialize the user. (Plus the app will be pulling the user out of the
        // database manually via model.fetch / .subscribe). Additionally, attempting to deserialize the user here
        // by fetching from the database yields "Error: Model mutation performed after bundling for clientId:..."
        /*var q = model.query('users').withId(id);
         _fetchUser(q, model, function(err, userObj){
         if(err && !err.notFound) return done(err);
         _loginUser(model, userObj, done);
         });*/
    });

    // Use the LocalStrategy within Passport.
    //   Strategies in passport require a `verify` function, which accept
    //   credentials (in this case, a username and password), and invoke a callback
    //   with a user object.  In the real world, this would query a database;
    //   however, in this example we are using a baked-in set of users.
    passport.use(new LocalStrategy(
        {passReqToCallback:true}, // required so we can access model.getModel()
        function(req, username, password, done) {
            var model = req.getModel()
            // Find the user by username.  If there is no user with the given
            // username, or the password is not correct, set the user to `false` to
            // indicate failure and set a flash message.  Otherwise, return the
            // authenticated `user`.
            var q = model.query('users').withUsername(username);
            q.fetch(function(err, result1){
                if (err) return done(err); // real error
                var u1 = result1.at(0).get()
                if (!u1) return done(null, false, {message:'User not found with that username.'});// user not found

                // We needed the whole user object first so we can get his salt to encrypt password comparison
                q = model.query('users').withLogin(username, utils.encryptPassword(password, u1.auth.local.salt));
                q.fetch(function(err, result2){
                    if (err) return done(err); // real error
                    if(process.env.NODE_ENV==='development') console.log(u2);
                    var u2 = result2.at(0).get()
                    if (!u2) return done(null, false, {message:'Password incorrect.'});// user not found
                    _loginUser(model, u2, done);
                });
            });
        }
    ));

    _.each(strategies, function(obj, name){

        // Provide default values for options not passed in
        // TODO pass in as conf URL variable
        _.defaults(obj.conf, {
            callbackURL: options.domain + "/auth/" + name + "/callback",
            passReqToCallback:true // required so we can access model.getModel()
        });

        // Use the FacebookStrategy within Passport.
        //   Strategies in Passport require a `verify` function, which accept
        //   credentials (in this case, an accessToken, refreshToken, and Facebook
        //   profile), and invoke a callback with a user object.
        passport.use(new obj.strategy(obj.conf, function(req, accessToken, refreshToken, profile, done) {
                var model = req.getModel()

                // If facebook user exists, log that person in. If not, associate facebook user
                // with currently "staged" user account - then log them in

                var providerQ = model.query('users').withProvider(profile.provider, profile.id),
                    currentUserQ = model.query('users').withId(model.get('_userId') || model.session.userId);

                model.fetch(providerQ, currentUserQ, function(err, providerUser, currentUser) {
                    if (err) return done(err);

                    var userObj = providerUser.at(0).get()
                    if (!userObj) {
                        var currentUserScope = currentUser.at(0);
                        currentUserScope.set('auth.' + profile.provider, profile);
                        currentUserScope.set('auth.timestamps.created', +new Date);
                        userObj = currentUserScope.get();
                        if (!userObj && !userObj.id) return done("Something went wrong trying to tie #{profile.provider} account to staged user")
                    }

                    // User was found, log in
                    _loginUser(model, userObj, done);
                });
            }
        ));
    });
}
示例#21
0
 removeClasses: function() {
     _.each(this.type2class, function(val) {
         this.$el.removeClass(val);
     }, this);
 },
示例#22
0
fanDuelScraper.on("playersLoaded", function(players){
  _.each(players, function(player){
    scraper.setNFLID(player);
  });
});
示例#23
0
文件: cp.js 项目: aygalic/LAB
  //   relativeYearlyProfit: '-67468.55576516',
  //   startPrice: 945.80000002,
  //   endPrice: 942.80838846,
  //   trades: 10,
  //   startBalance: 1043.5100001199999,
  //   sharpe: -2.676305165560598
  // }
  report: report => message('report', { report }),

  // object like:
  // {
  //   entryAt: Moment<'2017-03-25 19:41:00'>,
  //   entryPrice: 10.21315498,
  //   entryBalance: 98.19707799420277,
  //   exitAt: Moment<'2017-03-25 19:41:00'>
  //   exitPrice: 10.22011632,
  //   exitBalance: 97.9692176,
  //   duration: 3600000,
  //   pnl: -0.2278603942027786,
  //   profit: -0.2320439659276161,
  // }
  roundtrip: roundtrip => message('roundtrip', { roundtrip }),
}

if(ENV !== 'child-process') {
  _.each(cp, (val, key) => {
    cp[key] = _.noop;
  });
}

module.exports = cp;
示例#24
0
文件: index.js 项目: 0x1115/Ghost
        }
    }
};

// Ensure our 'this' context for methods and preserve method arity by
// using Function#bind for expressjs
_.each([
    'logWarn',
    'logComponentInfo',
    'logComponentWarn',
    'rejectError',
    'throwError',
    'logError',
    'logAndThrowError',
    'logAndRejectError',
    'logErrorAndExit',
    'logErrorWithRedirect',
    'handleAPIError',
    'formatAndRejectAPIError',
    'formatHttpErrors',
    'renderErrorPage',
    'error404',
    'error500'
], function (funcName) {
    errors[funcName] = errors[funcName].bind(errors);
});

module.exports                            = errors;
module.exports.NotFoundError              = NotFoundError;
module.exports.BadRequestError            = BadRequestError;
module.exports.InternalServerError        = InternalServerError;
module.exports.NoPermissionError          = NoPermissionError;
示例#25
0
文件: rttc.js 项目: Latros/machine
  _.each(_.keys(def), function(inputName) {

    var input = def[inputName];
    var value = val[inputName];
    var err = new Error();

    // If the input has a valid flag on it, we don't need to use runtime type checking on
    // it because it has been run through a validate function.
    if(input && input.valid) {
      return;
    }

    // Check if the input is required and missing
    if(types.undefined.is(value)) {

      if (input.required) {
        err.code = 'E_REQUIRED_INPUT';
        err.message = util.format(
          'The input ' + inputName + ' is a required input and no value was specified.'
        );

        errors.push(err);
      }

      return;
    }

    // If the input is an array, parse it for each item
    if(_.isArray(input.type)) {
      if(value && !types.arr.is(value)) {
        err.code = 'E_INVALID_TYPE';
        err.message = util.format(
          'An invalid value was specified. The value ' + value + ' was used \n' +
          'and doesn\'t match the specified type: ' + input.type
        );

        errors.push(err);
        return;
      }

      // If the input is required and the value array is empty, it's an error
      if(input.required && value.length < 1) {
        err.code = 'E_REQUIRED_INPUT';
        err.message = util.format(
          'The input ' + inputName + ' is a required input and no value was specified.'
        );

        errors.push(err);
        return;
      }

      // if the input is a ['*'] this is a typeclass array and we can build a schema
      // based on the first item in the array.
      if(input.type[0] === '*') {
        var type = value.length ? value[0] : 'foo';

        // Infer the type
        var inferred = infer(type);
        input.type = [inferred];
      }

      _.each(value, function(item) {

        // Handle an array of objects
        if(types.obj.is(input.type[0])) {
          try {
            item = parseObject(input.type[0], item);
          }
          catch (err) {
            err.code = 'E_INVALID_TYPE';
            err.message = util.format(
              'An invalid value was specified. The value ' + item + ' was used \n' +
              'and doesn\'t match the specified type: ' + input.type[0]
            );

            errors.push(err);
            return;
          }
        }

        // Handle an array of primative values
        else {
          try {
            item = coerceValue(input.type[0], item, { coerce: coerce, baseType: baseType });
            var valid = checkTuple(input.type[0], item)
            if(!valid) {
              errors.push('Invalid type for input: ' + inputName);
              return;
            }
          }
          catch (e) {
            errors.push(e, inputName);
            return;
          }
        }
      });

      val[inputName] = value;
      return;
    }

    // if the input is an object, recursively parse it
    if(types.obj.is(input.type)) {

      // If the schema is an empty object any object values are allowed to validate
      if(!_.keys(input.type).length) {
        if(_.isPlainObject(value)) return val;
        errors.push('Invalid type for input: ' + inputName);
      }

      try {
        value = parseObject(input.type, value);
      }
      catch (err) {
        errors.push('Invalid type for input: ' + inputName);
        return;
      }

      val[inputName] = value;
      return;
    }

    // If the input type isn't an object or array we can just do a simple type check
    try {

      // If a value is optional and not required and we don't need a baseType then
      // we can just return the undefined value
      if(_.isUndefined(value) && !input.required && !baseType) {
        return;
      }

      value = coerceValue(input.type, value, { coerce: coerce, baseType: baseType });
      var valid = checkTuple(input.type, value)
      if(!valid) {
        errors.push('Invalid type for input: ' + inputName);
        return;
      }
    }
    catch (e) {
      errors.push(e, inputName);
      return;
    }

    val[inputName] = value;
    return;
  });
示例#26
0
var _ =  require('lodash');
var Pillbox = require('../..');
var tmpl = require('./pill.jade');

var values = ['Fruit', 'Vegetable', 'Grain', 'Dairy'];

var simpleRibbon = new Pillbox({
  container: document.querySelector('.tag-ribbon')
});

_.each(values, function (value) {
  simpleRibbon.addPill({
    value: value,
    key: value.toLowerCase(),
    template: tmpl
  });
});
示例#27
0
_.each(entityDescriptors.schemas, (schema, collectionName) => {
	models[collectionName] = db.createModel(
		collectionName,
		_.pickBy(
			_.mapValues(schema.fields, (field, fieldName) => {
				if (field.type === 'association') {
					return undefined;
				}
				if (fieldName === schema.idFieldName) {
					return {
						type: field.type,
						id: true,
						generated: schema.idFieldName === 'id',
					}
				}
				return {
					type: String,
				}
			}),
			(x) => x
		),
		{
			idInjection: false,
			relations: _.pickBy(
				_.mapValues(schema.fields, (field, fieldName) => {
					if (field.type === 'association') {
						return {
							model: field.collectionName,
							type: field.isMultiple ? 'hasMany' : 'belongsTo',
						};
					}
				}),
				(x) => x
			),
		}
	);
});
示例#28
0
  N.wire.after(['responder:http', 'responder:rpc'], { priority: 100 }, function response_send(env) {
    var res = env.origin.res
      , headers = env.headers
      , body = env.body
      , statusCode;

    //
    // Set some obligatory headers
    //

    headers['Server'] = headers['Server'] || 'Sansun Calakci';
    // added by node automatically
    // headers['Date'] = headers['Date'] || new Date).toUTCString();

    //
    // Remove Accept-Ranges if it wasn't explicitly set
    //

    if (!headers['Accept-Ranges']) {
      res.removeHeader('Accept-Ranges');
    }

    //
    // set headers
    //

    _.each(headers, function (value, name) {
      // Check if header registered, since
      // one can mistype capitalization and name
      if (!valid_headers[name]) {
        N.logger.fatal("send_reply: Got wrong header %s in method %s", name, env.method);
      }

      if (null === value) {
        this.removeHeader(name);
        return;
      }
      this.setHeader(name, value);
    }, res);


    //
    // should not happen
    //

    if (!res.getHeader('Content-Type')) {
      N.logger.fatal('send_reply: Required header Content-Type was not set in %s', env.method);
    }

    //
    // When body is given, it MUST be a Buffer or a String
    // (this error should not happen)
    //

    if (body && !Buffer.isBuffer(body) && 'string' !== typeof body) {
      statusCode = N.io.APP_ERROR;
      body = http.STATUS_CODES[statusCode];
      N.logger.fatal('send_reply: body MUST be a Buffer, String or Null/Undefined. in %s',
                     env.method);
    }

    // FIXME: Do not forget to filter-out sensitive params upon logging
    // if (req.params.password) req.params.password = '******';
    // if (req.params.password_confirmation) req.params.password_confirmation = '***';

    env.log_request(env);

    //
    // Set Content-Length header if body is given.
    // body is always Buffer, String or Null|Undefined.
    //

    if (Buffer.isBuffer(body)) {
      headers['Content-Length'] = body.length;
    } else if (body) {
      // NOTE: Buffer.byteLength() throws TypeError when argument is not a String.
      headers['Content-Length'] = Buffer.byteLength(body);
    }

    // set status code and send body (if any)
    res.statusCode = env.status;
    res.end(body);
  });
示例#29
0
function convert(query) {
    var mongoQ = {};

    // Query apply to all
    var queryAll = {};

    // OR query
    var queryOr = {};

    // Append a group to the query
    function appendGroup(group, fn) {
        if (_.isArray(group.field)) {
            queryOr[group.originalField] = queryOr[group.originalField] || {};

            _.each(group.field, function(field) {
                queryOr[group.originalField][field] = queryOr[group.originalField][field] || {};
                queryOr[group.originalField][field] = fn(queryOr[group.originalField][field]);
            });
        } else {
            queryAll[group.field] = fn(queryAll[group.field]);
        }
    }

    // Convert all groups
    _.each(query.groups, function(group) {
        // Equals
        if (group.type == "=") {
            appendGroup(group, _.constant(group.value));
        }

        // in or nin
        else if (group.type == "in" || group.type == "nin") {
            var mType = "$"+group.type;
            queryAll[group.field] = queryAll[group.field] || {};
            queryAll[group.field][mType] = queryAll[group.field][mType] || [];
            queryAll[group.field][mType].push(group.value);
            queryAll[group.field][mType] = _.flatten(queryAll[group.field][mType]);
        }

        // simplify "!= true" to "= false"
        else if (group.type === "!=" && group.value === true) {
          group.type = "=";
          group.value = false;
          appendGroup(group, _.constant(group.value));
        }

        // Other types
        else if (TYPES[group.type]) {
            appendGroup(group, function(value) {
                value = value || {};
                value[TYPES[group.type]] = group.value;
                return value;
            });
        }

        // Invalid type
        else {
            throw ("Invalid type for mongo query: "+group.type);
        }
    });

    mongoQ = queryAll;
    if (_.size(queryOr) == 1) {
        mongoQ["$or"] = _.chain(queryOr)
        .values()
        .first()
        .map(function(value, field) {
            return _.object([field], [value]);
        })
        .value();
    }

    if (_.size(queryOr) > 1) {
        var finalOr = [];
        var added = [];

        _.each(queryOr, function(alias, originalField) {
            if (_.contains(added, originalField)) return;

            _.each(alias, function(values, alia) {
                _.each(_.omit(queryOr, originalField), function(otherFields, otherBaseField) {
                    _.each(otherFields, function(otherValue, otherField) {
                        var nOr = {};
                        nOr[alia] = values;
                        nOr[otherField] = otherValue;
                        finalOr.push(nOr);
                    });
                    added.push(otherBaseField);
                });
            });
        });
        mongoQ["$or"] = finalOr;
    }

    return mongoQ;
};
示例#30
0
  update: function(game) {

    if (this.stopUpdate) {
      return;
    }

    var player = this.player
      , room = player.room
      , self = this
      , distance
      , sprite;

    // draw fps
    if (_globals.enableDebug) {
      this.texts.fps.setText('fps: ' + game.time.fps);
      this.texts.pos.setText('room: ' + player.room.idx);
      this.texts.end.setText('end: ' + this.maze.endRoom);
      this.texts.key.setText('key: ' + this.maze.keyRoom);
    }

    // player movement
    var move = 0;
    player.body.velocity.setTo(0, 0);
    if (this.cursors.up.isDown || game.input.keyboard.isDown(Phaser.Keyboard.W)) {
      player.body.velocity.y = -_globals.PLAYER_SPEED;
      move += 1;
    } else if (this.cursors.down.isDown || game.input.keyboard.isDown(Phaser.Keyboard.S)) {
      player.body.velocity.y =  _globals.PLAYER_SPEED;
      move += 2;
    } else if (this.cursors.left.isDown || game.input.keyboard.isDown(Phaser.Keyboard.A)) {
      player.body.velocity.x = -_globals.PLAYER_SPEED;
      move += 10;
    } else if (this.cursors.right.isDown || game.input.keyboard.isDown(Phaser.Keyboard.D)) {
      player.body.velocity.x = _globals.PLAYER_SPEED;
      move += 20;
    }

    if (move === 1) {
      player.angle = 0;
    } else if (move === 2) {
      player.angle = 180;
    } else if (move > 0 && move < 20) {
      player.angle = -90;
    } else if (move >= 20) {
      player.angle = 90;
    } else {
      player.animations.stop();
    }

    // other options
    if (game.input.keyboard.isDown(Phaser.Keyboard.M) && player.musicKeyTime < game.time.now) {
      player.musicKeyTime = game.time.now + 500;
      this.toggleMusic();
    } else if (game.input.keyboard.isDown(Phaser.Keyboard.N) && player.musicKeyTime < game.time.now) {
      player.musicKeyTime = game.time.now + 500;
      this.soundOn = !this.soundOn;
    }

    // monsters movement
    _.each(this.monsters, function(monster) {
      sprite = monster.obj;
      if (sprite.exists && (monster.roomIdx === player.room.idx || monster.erratic)) {
        if (monster.type === _globals.MONSTER01) {
          if (sprite.x < player.x - 10) {
            sprite.body.velocity.x = _globals.MONSTER_SPEED;
          } else if (sprite.x > player.x + 10) {
            sprite.body.velocity.x = -_globals.MONSTER_SPEED;
          }
          if (sprite.y < player.y - 10) {
            sprite.body.velocity.y = _globals.MONSTER_SPEED;
          } else if (sprite.y > player.y + 10) {
            sprite.body.velocity.y = -_globals.MONSTER_SPEED;
          }
        } else if (monster.type === _globals.MONSTER02 && monster.trackTime < game.time.now) {
          monster.trackTime = game.time.now + _globals.MONSTER_ACC_DELAY;
          sprite.body.velocity.setTo(0, 0);
          game.physics.arcade.accelerateToObject(sprite, player, _globals.MONSTER_ACC,
            _globals.MONSTER_MAXSPEED, _globals.MONSTER_MAXSPEED);
        }
        sprite.angle = game.math.wrapAngle(90 + game.math.radToDeg(
          game.physics.arcade.angleBetween(sprite, player), false));
        sprite.play('walk');
      }
    }, this);

    // open/close door
    if (this.game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR) ||
      this.game.input.keyboard.isDown(Phaser.Keyboard.ENTER)) {
      if (game.time.now > player.lastOpenTime) {
        player.lastOpenTime = game.time.now + 550;

        _.each(player.room.obj.doors, function(door) {
          distance = game.math.distance(player.x, player.y, door.x, door.y);
          // _globals.debug('door dist: ' + distance);
          if (distance < 85) {
            if (door.isRed && !player.hasKey) {
              this.gamefactory.addText('The door is locked!');
            } else {
              door.isOpen = !door.isOpen;
              door.frame = door.isOpen ? 2 : 0;
              this.playSound(['door1', 'door2']);
            }

            return;
          }
        }, this);

      }
    }

    // collisions
    if (move > 0) {

      if (game.time.now > this.player.lastWalkSndTime) {
        this.player.lastWalkSndTime = game.time.now + 250;
        this.player.play('walk');
        this.playSound(['walk2', 'walk3']);
      }

      // room enter?
      _.each(player.room.obj.doors, function(door) {
        // if (door.isOpen) {
          // console.log('door open col');
          game.physics.arcade.collide(player, door, self.onDoorCollision, null, self);
        // }
      });
      _.each(player.room.obj.artifacts, function(obj) {
        game.physics.arcade.collide(player, obj);
      });

      if (room.scheme.hasKey && room.obj.key) {
        game.physics.arcade.collide(player, room.obj.key, self.onKeyCollision, null, self);
      }
    }

    if (!this.isRoomEmpty) {

      if (game.time.now > this.player.lastAlarmTime) {
        this.player.lastAlarmTime = game.time.now + 1000;
        this.playSound(['alarm1', 'alarm2']);
      }

      // update depth in case there are more actors
      this.gamefactory.updateDepths(this.monsters);

      // monster hit test
      _.each(this.monsters, function(monster) {
        game.physics.arcade.collide(player, monster.obj, self.onMonsterCollision, null, self);
      });
    }

  },