Example #1
0
  getUserNamesFromEmails: function(fromEmail,ccEmail, cb) {
    var req = https.request({
      host:    'www.pivotaltracker.com',
      port:    443,
      method:  'GET',
      path:    '/services/v3/projects/' + this.get('projectId') + '/memberships',
      headers: {'X-TrackerToken': this.get('token')}
    }, _.bind(function(res) {
      res.setEncoding('utf8');
      var body = '';

      res.on('data', function(chunk) {
        body += chunk;
      });

      res.on('end', _.bind(function() {
        if(body.match(/<memberships/)) {
          var fromName = this.getUserNameFromXML(body, fromEmail) || '',
              ccName   = this.getUserNameFromXML(body, ccEmail) || '';
          cb(fromName,ccName);
        } else {
          console.log(body);
          this.trigger('error', body);
        }
      }, this));
    }, this));
    req.on('error', _.bind(this.trigger, this, 'error'));
    req.end();
  },
Example #2
0
var Database = function(_settings) {
	//default settings
	var settings = {
		options:{}
	};
	
	var onOpen = function() {
		console.log('Connected to database ' + settings.options.database + ' on ' + settings.options.host + ':' + settings.options.port + ', registering schemas...');
		for (schema in schemas) {
			var s = new mongoose.Schema(schemas[schema].definition);
			mongoose.model(schemas[schema].name, s);
			console.log('- ' + schemas[schema].name);
		}
	};
	
	var onError = function(err) {
		console.log('Database connection error: ' + err.message);
	}
	
	_.extend(settings, _settings);
		
	this.db = mongoose.connect(settings.options.host, settings.options.database, settings.options.port);
	this.db.connection.on('open', onOpen);
	this.db.connection.on('error', onError);
	
	_.bind(this.find, this);
	_.bind(this.save, this);
	_.bind(onOpen, this);
	
	events.EventEmitter.call(this);

	return this;
};
    init:function() {
        this.ssdp = new Client();

        //handle the ssdp response when the roku is found
        this.ssdp.on('response',_.bind(this.handleResponse,this));

        setInterval(_.bind(this.doSearch,this),1000);
        this.doSearch()
    },
	initialize: function(args) {
		client_models.Session.prototype.initialize.call(this, args)
        _.bindAll(this, "onHangoutStarted", "onHangoutStopped")

		// make sure not to overwrite the built-in session-key
		// if we've loaded one through the db.
		if(_.isNull(this.get("session-key"))) {
			var shasum = crypto.createHash('sha256');
			shasum.update(this.get("id") + "");
			shasum.update(new Date().getTime() + "");
			this.set("session-key", shasum.digest('hex'));
		}

		// these listeners are for responding to messages from connected, currently
		// live hangouts. 

		// this particular event triggers when the server makes a change to this 
		// session's hangoutConnected field. It could be changing it in either direction,
		// so we need to disambiguate between starting and stopping by checking
		// the previous state.
		this.on("change:hangoutConnected", _.bind(function() {
			if(this.get("hangoutConnected")) {
                this.onHangoutStarted();
			} else {
                this.onHangoutStopped();
			}
		}, this));
        
        // now check to see if the hangout is already connected when we
        // initialize the serversession. This happens in situations where the
        // server crashes while hangouts are running, and the sockets
        // re-connect.
		if(this.get("hangoutConnected")) {
			logger.debug("server-models triggering hangout-started on load.");

            // this is an annoying hack. it turns out that
            // ServerSession.collection isn't set, because in the
            // initialization process sessions are created before they're
            // assigned to events.  This means that if we try to do a broadcast
            // (the second line of hangout-started event above) it will fail.
            // Instead, we wait until the collection is assigned to do this.
            // (this is triggered manually in Event.addSession, because
            // backbone doesn't seem to fire this event on its own)

            // if it's a permalink session, just start immediately. No need to
            // do the collection hack.
			if(this.get("isPermalinkSession")) {
				this.onHangoutStarted();
			} else {
				this.on("change:collection", _.bind(function() {
                    this.onHangoutStarted
				}, this));
			}
		}
    },
Example #5
0
 _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
   var initial = arguments.length > 2;
   if (obj == null) obj = [];
   if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
     if (context) iterator = _.bind(iterator, context);
     return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
   }
   var reversed = _.toArray(obj).reverse();
   if (context && !initial) iterator = _.bind(iterator, context);
   return initial ? _.reduce(reversed, iterator, memo, context) : _.reduce(reversed, iterator);
 };
Example #6
0
    fs.stat(file, function(err, stats) {
      if (!stats || !stats.isFile()) {
        sys.debug("404: " + file);
        resp.writeHead(404, "Not Found", { 'Content-type': 'text/plain' });
        resp.end("404 Not Found");
        return;
      }

      resp.writeHead(200, "OK", { "Content-type": mimeTypes[ext] });

      var stream = fs.createReadStream(file);
      stream.on("data", _.bind(resp.write, resp));
      stream.on("end", _.bind(resp.end, resp));
    });
Example #7
0
	loadMatchDetails: function(matchMetadata, cb) {
		// check to see if we have a cached result for this match.
		winston.info("contents of matchDetailsCache: " + JSON.stringify(Object.keys(this.matchDetailsCache)));

		// check if we have a cached result for this match, and if we do return it.
		// also make sure the result isn't undefined - this somehow happens sometimes.
		if(matchMetadata.match_id in this.matchDetailsCache &&
			!_.isUndefined(this.matchDetailsCache[matchMetadata.match_id])) {
			// return that result.
			var match = this.matchDetailsCache[matchMetadata.match_id];

			winston.info("Loading match metadata from cache from earlier request.");
			cb && cb(match, matchMetadata);

			// drop out and avoid making the actual request.
			return;
		}

		this.api().getMatchDetails(matchMetadata.match_id, _.bind(function(err, match) {
			if(err || match.error) {
				winston.error("error loading match: " + err);
				// in this case we DON'T pull it from the queue; we want to retry
				// these. But any other type of error we want to toss it.
				if(match.error) {
					this.removeMatchFromQueue(matchMetadata);
				}
				return;
			}

			this.matchDetailsCache[matchMetadata.match_id] = match;

			cb && cb(match, matchMetadata);
		}, this));
	},
Example #8
0
		}, _.bind(function(err, res) {
			if(err) {
				winston.error("error loading matches: " + err);
				return;
			}

			if(_.isUndefined(res)) {
				winston.error("Empty response getting recent matches for: " + league.name);
				return;
			}

			if(res.total_results == 0) {
				winston.warn("No matches returned for league_id: " + league.name);
				return;
			} else {
				// winston.info(res.matches.length + " matches found for " + league.name);
			}

			if(this.isDemo) {
				res.matches = _.first(res.matches, 2);
			}

			_.each(res.matches, _.bind(function(match) {
				this.logRecentMatch(match, this.leagues[leagueId]);
			}, this));

			this.leagues[leagueId].init = false;

			// run the callback if present.
			cb && cb(res.matches);
		}, this));
Example #9
0
	updateLeagueListing: function() {
		winston.info("Updating league listing.");
		this.api().getLeagueListing(_.bind(function(err, res) {
			if(err) {
				winston.error("Error loading league listing: " + err);
				return;
			}

			if(_.isUndefined(res)) {
				winston.error("League listing request returned undefined result.");
				return;
			}

			var that = this;
			this.leagues = {};
			_.each(res.leagues, function(league) {
				if(league.leagueid in that.leagues) {
					var lastSeenMatchIds = that.leagues[league.leagueid].lastSeenMatchIds;
					league.lastSeenMatchIds = lastSeenMatchIds;
				}

				that.leagues[league.leagueid] = league;
			});

			winston.info("Loaded " + Object.keys(this.leagues).length + " leagues.");

			this.lastLeagueUpdate = new Date().getTime();

			this.emit("leagues:update");
			this.saveLeagues();
		}, this));
	},
Example #10
0
/**
 * Map all node-salesforce object to REPL context
 * @private
 */
function defineBuiltinVars(context) {
  // define salesforce package root objects
  for (var key in sf) {
    if (sf.hasOwnProperty(key) && !global[key]) {
      context[key] = sf[key];
    }
  }
  // expose salesforce package root as "$sf" in context.
  context.$sf = sf;

  // create default connection object
  var conn = new sf.Connection();

  for (var prop in conn) {
    if (prop.indexOf('_') === 0) { // ignore private
      continue;
    }
    if (_.isFunction(conn[prop])) {
      context[prop] = _.bind(conn[prop], conn);
    } else if (_.isObject(conn[prop])) {
      defineProp(context, conn, prop);
    }
  }

  // expose default connection as "$conn"
  context.$conn = conn;
}
Example #11
0
	cleanupActiveSeries: function() {
		// run through all active series.
		var idsToRemove = [];
		var now = new Date().getTime();
		_.each(this.activeSeriesIds, function(series, id) {
			if((now - series.time) > 60*60*12*1000) {
				idsToRemove.push(series.series_id);
				winston.info("Removing series_id due to age: " + series.series_id);
			}

			var maxGames = 0;
			_.each(series.teams, function(wins, team_id) {
				maxGames = Math.max(maxGames, wins);
			});

			// series_type is 1 for a bo3, 2 for a bo5, (3 for a bo7?)
			// so just do that number +1 because that's the number of matches
			// it would take to win.
			if(maxGames==(series.series_type+1)) {
				idsToRemove.push(series.series_id);
				winston.info("Removing series_id due to max games hit " + series.series_id);
			}
		});

		_.each(idsToRemove, _.bind(function(id) {
			delete this.activeSeriesIds[id];
		}, this));

		winston.info("After cleaning, # series being tracked: " + Object.keys(this.activeSeriesIds).length);
	},
		this.on("open-sessions", function() {
			// when sessions open
			// start all sessions if they need starting.
			this.get("sessions").each(function(session) {
				if(!session.get("hangoutConnected")) {
					session.set("hangoutConnected", true);
					session.set("hangout-start-time", new Date().getTime());
					session.setConnectedParticipants([this.get("connectedUsers").at(0)]);
				}
			}, this);

			var id = setInterval(_.bind(function() {
				this.get("sessions").each(function(session) {
					var rand = Math.random();

					var numParticipants = session.getNumConnectedParticipants();
					logger.debug("numParticipants: " + numParticipants);

					if(rand > 0.5 && (numParticipants < 10)) {
						var existingParticipants = session.get("connectedParticipants");
						existingParticipants.push(this.get("connectedUsers").at(0));
						session.setConnectedParticipants(existingParticipants);
					} else if(numParticipants > 1) {
						var existingParticipants = session.get("connectedParticipants");
						existingParticipants.shift();
						session.setConnectedParticipants(existingParticipants);
					}
				}, this);
			}, this), 1000);
			this.set("fake-session-activity-id", id);
		}, this);
Example #13
0
  saveCallback: function(res) {
    res.setEncoding('utf8');
    var body = '';

    res.on('data', function(chunk) {
      body += chunk;
    });

    res.on('end', _.bind(function() {
      try {
        if (res.statusCode == "200") {
          var storyId = body.match(/<id.*?>(\d+)<\/id>/m)[1];
          var storyUrl = body.match(/<url>([^<]+)<\/url>/m)[1];
          this.set({id: storyId});
          if(this.get('attachments').length > 0) {
            this.createAttachments(_.bind(this.trigger, this, 'done', storyUrl));
          } else {
            this.trigger('done', storyUrl)
          }
        }else {
          this.handlePivotalError(res,body);
        }
      } catch(e) {
        console.log('PT Response Body: ' + body);
        this.trigger('error', new String(e) + "\n\n" + body);
      }
    }, this));
  },
Example #14
0
    init: function(options) {
        this.options = options;

        // TODO is it bad for this to be the same as the session secret?
        // leaving the same for now.
        models.USER_KEY_SALT = this.options.UNHANGOUT_SESSION_SECRET;

        this.db = new UnhangoutDb(options);
        // Attaching our smtp transport to 'db'.  Kindof makes sense... sending
        // email is persisting data, right?
        this.db.smtpTransport = nodemailer.createTransport("SMTP", options.UNHANGOUT_SMTP);
        this.db.init(_.bind(function(err) {
            if (!err) {
                this.inited = true;
                this.emit("inited");
                logger.analytics("server", {action: "init"});
            }
        }, this));

        // Configure memory leak detection and warnings.
        if (process.env.NODE_DEBUG_LEAKS === "1") {
            memwatch.on('leak', function(info) {
                logger.warn("LEAK", info);
            });
            this.heapDiff = null;
            setInterval(function() {
                // log a heap diff.
                if (this.heapDiff != null) {
                    logger.warn("HEAP DIFF", this.heapDiff.end());
                }
                this.heapDiff = new memwatch.HeapDiff();
            }.bind(this), 1000);
        }
    },
Example #15
0
 fs.readFile(file.path, null, _.bind(function(err, data) {
   if(err) this.trigger('error', err);
   this.createAttachmentFromFile(file, data, _.bind(function() {
     count--;
     if(count == 0) cb();
   }, this));
 }, this));
Example #16
0
			_.bind(function (err, data, response) {
				winston.info("media upload callback firing");
				winston.info("response: " + response);
				winston.info("err: " + err);
				if(err) {
					winston.info("Falling back to text tweet.");

					// winston.error(err);
					// winston.error(response);
					if(t==this.twitter) {
						this.tweet(string, match);						
					} else {
						this.altTweet(string, match);
					}

				} else {
					winston.info("Uploaded media: " + mediaIdStr);

					var mediaIdStr = data.media_id_string;
					var params = { status: string, media_ids: [mediaIdStr] };

					t.post('statuses/update', params,
						_.bind(function(err, data, response) {
							if(err) {
								if(err.message.indexOf('duplicate')!=-1 || err.message.indexOf('update limit')!=-1) {
				  					winston.info("Error posting, duplicate or over limit - drop.");
				  					this.removeMatchFromQueue(match);
	  							}
							} else {
								winston.info("Posted media tweet successfully: " + response);
							}
						}, this));
				}
			}, this));
Example #17
0
 addAdmin: function(user) {
     var admins = this.get("admins");
     var exists = _.any(admins, _.bind(function(admin) {
         return this.adminMatchesUser(admin, user);
     }, this));
     if (!exists) {
         var changed = false;
         if (user.id) {
             admins.push({id: user.id});
             changed = true;
         } else {
             var email;
             if (user.email) {
                 email = user.email;
             } else if (user.get && user.get("emails")[0]) {
                 email = user.get("emails")[0].value;
             }
             if (email) {
                 admins.push({email: email});
                 changed = true;
             }
         }
         if (changed) {
             this.set("admins", admins);
             this.trigger("change:admins", this, admins);
             this.trigger("change", this);
         }
     }
 },
Example #18
0
    stop: function() {
        if(!this.running) {
            logger.warn("Tried to stop a server that was not running.");
            this.emit("error", "Tried to stop a server that was not running.");
            return;
        }
        logger.info("http server shutting down");
        this.emit("stopping");

        this.db.smtpTransport.close();
        this.socketManager.shutdown(_.bind(function(err, message) {
            logger.info("Socket manager stopped");
            if (err) {
                logger.error(err)
            }
            if(this.httpRedirect) {
                this.httpRedirect.close();
            }

            this.http.close();

            this.http.on("close", _.bind(function() {
                logger.info("HTTP Closed");
                this.running = false;
                this.emit("stopped");
                logger.analytics("server", {
                    action: "stop",
                    host: this.options.UNHANGOUT_HOST,
                    port: this.options.UNHANGOUT_PORT
                });
            }, this));
        }, this));
    },
Example #19
0
function prepText(text) {
  if (_.isArray(text)) return text;
  var deduped = _.uniq(tokenizer.tokenize(text));
  if (!this.options.stopwords) return deduped;
  return _.reject(deduped, _.bind(isStopword, null,
      _.isString(this.options.stopwords) ? this.options.stopwords : natural_stopwords
      ));
}
Example #20
0
	getLeaguesWithLiveGames: function() {
		var leagueIds = _.map(this.liveGames, _.bind(function(game) {
			return game.league_id;
		}, this));


		return _.uniq(leagueIds);
	},
Example #21
0
 _.each(module[property], function(item, itemName) {
     item.module = name; 
     if(_.has(config, property) && _.has(config[property], itemName)) {
         _.extend(item, config[property][itemName]);
     }
     module[property][itemName] = _.bind(item, module);
     _.extend(module[property][itemName], item);
 }, this);
Example #22
0
 route : function(route, name, callback) {
   Backbone.history || (Backbone.history = new Backbone.History);
   if (!_.isRegExp(route)) route = this._routeToRegExp(route);
   Backbone.history.route(route, _.bind(function(fragment) {
     var args = this._extractParameters(route, fragment);
     callback.apply(this, args);
     this.trigger.apply(this, ['route:' + name].concat(args));
   }, this));
 },
Example #23
0
	'constructor': function(initialState) {
		this.constructor.__super__.constructor.call(this, initialState);

		this.image = new Image();
		this.image.onload = _.bind(function() {
			this.ready = true;
		}, this);
		this.image.src = 'game-bg.jpg';
	},
    connect:function(socket) {
		this.socket = socket;

		var buffer = "";
		socket.on('data', _.bind(function(data) {
            this.lastReceivedData = new Date().getTime();
            if (this.ignoreData) return;
                /*
            var bytes = [];
            for (var i = 0; i < buffer.length; ++i) {
                bytes.push(buffer.charCodeAt(i));
            }
            console.log("data raw:", bytes);
            */

			data = String(data);
            data = data.replace(/\r/g,"");
			if (data.length == 0) return;
			buffer += data;
            while(true) {
                var index = buffer.indexOf("\n\n");
                if (index == -1) break;

                var line = buffer.substring(0,index);
                this._receivedClientData(socket,line);
                buffer = buffer.substring(index+1);
            }
		},this));
		
		socket.on('disconnect',_.bind(function () {
			this.emit("Disconnect",this);
		},this));

		socket.on('error',_.bind(function(error) {
			if (error.code == "ECONNRESET") {
				this.emit("Disconnect",this,error);
			} else {
				console.log("uncaught error: ",error);
			}
		},this));

        this.idlePingTimer = setInterval(_.bind(this.idlePing,this),1000);
    },
Example #25
0
Tooling.prototype.initialize = function() {
  this.sobjects = {};
  this.cache.clear();
  this.cache.get('describeGlobal').on('value', _.bind(function(res) {
    if (res.result) {
      var types = _.map(res.result.sobjects, function(so) { return so.name; });
      _.each(types, this.sobject, this);
    }
  }, this));
};
Example #26
0
	Parser.prototype.parseFile = function (filePath, callback) {
		this.filePath = filePath;
		this.callback = callback;

		// _.bindAll(this);

		fs.readFile(this.filePath, "utf8", _.bind(function (err, data) {
			data = err ? {error: err} : this.toObject(data);
			callback(data);
		}, this));
	};
Example #27
0
				setTimeout(_.bind(function() {
					winston.info("\tDone delaying match handling for " + match.match_id);

					// add the match to the list of matches to tweet
					this.matchesToTweet.push(match);

					// attempt to proces the match immediately, which will remove it
					// from the above list if successful. If this particular process
					// attempt fails due to API errors, then the matchesToTweet checking
					// will catch it and try again later.
					this.loadMatchDetails(match, _.bind(this.handleFinishedMatch, this));
				}, this), delayDuration);
Example #28
0
 createAttachmentFromFile: function(file, data, cb) {
   var attachment = new Attachment({
     projectId: this.get('projectId'),
     storyId:   this.get('id'),
     token:     this.get('token'),
     file:      file,
     data:      data
   });
   attachment.bind('error', _.bind(this.trigger, this, 'error'));
   attachment.bind('done', cb);
   attachment.save();
 }
Example #29
0
			_.each(Object.keys(this.activeLeagueIds), _.bind(function(leagueId) {
				var league = this.leagues[leagueId];

				// short circuit the whole loop if we're missing a league.
				// if(missingLeague) return;

				if(_.isUndefined(league)) {
					winston.error("League is not defined for " + leagueId);
					// Not really sure what to do in this case.
					// really we need to create a new entry in this list, but I'm not sure
					// what it should have in it.

					// OH I know what happened. The patch hit, new tickets went out, and
					// we didn't have them in the list. I think we need to do a full league
					// update operation.

					// this is a little error prone. The update league listing takes time,
					// and if league is undefined, the next check is DEFINITELY going to fail.
					// really we want to update the league listing, wait for that to execute
					// and then return to this proces. 
					// this.updateLeagueListing();
					// missingLeague = true;
					return;
				}

				if(_.isUndefined(league.lastSeenMatchIds)) {
					winston.info("Found un-initialized league: " + league.name);
					league.lastSeenMatchIds = [];
					league.init = true;
				}

				this.getRecentLeagueMatches(leagueId, _.bind(function(matches) {
					// winston.info("Found " + matches.length + " matches for league: " + this.leagues[leagueId].name);

					matchCounts[leagueId] = matches.length;

					this.leagues[leagueId].init = false;

					// ugly but I'm too lazy to work out the flow control here.
					if(Object.keys(matchCounts).length==Object.keys(this.activeLeagueIds).length) {
						var out = "";

						_.each(Object.keys(matchCounts), function(k) {
							out += k + ":" + matchCounts[k] + "\t";
						});

						winston.info(this.liveGames.length + " -> " + out + " (states: " + Object.keys(this.states.lobbies).length + ")");
					}
				}, this));
			}, this));
Example #30
0
			this.redis.hgetall("global:delayed_matches", _.bind(function(err, reply) {
				if(!err) {
					if(!_.isNull(reply) && reply.length==0) {
						winston.info("No delayed matches found.");
					}
					_.each(reply, _.bind(function(match, match_id) {
						// push it onto matchIdsToTweet
						winston.info("Pushing delayed matches onto list: " + match);
						this.matchesToTweet.push(JSON.parse(match));
					}, this));
				} else {
					winston.warn("Error loading delayed matches from cache: " + err);
				}
			}, this));