<commit_before>/**
 * Listen to a twitter stream to get the score.
 *
 * Borrowed from https://github.com/xdamman/ReplayLastGoal.
 */

/**
 * Dependencies.
 */
var twitter = require('twitter')
  , humanize = require('humanize')
  , fs = require('fs')
  ;

/**
 * Constants.
 */
var TWITTER_USERNAME = "GoalFlash";

module.exports = function(server) {

  /**
   * Dependencies.
   */
  var Games = server.controllers.games;

  /**
   * Variables.
   */
  var twitterCreds = {
      consumer_key: process.env.TWITTER_KEY
    , consumer_secret: process.env.TWITTER_SECRET
    , access_token_key: process.env.TWITTER_TOKEN
    , access_token_secret: process.env.TWITTER_TOKEN_SECRET
  };
  var twit = new twitter(twitterCreds);
  var isConnected = true;

  /**
   * Map teams.
   */
  var mapTeam = function(team) {
    if (team === "Côte d'Ivoire")
      team = "Ivory Coast";
    if (team === "United States")
      team = "USA";

    return team;
  }

  /**
   * Analyze tweet to extract teams and score.
   */
  var analyzeTweet = function(tweet) {
    var text = tweet.text;
    var arr = /(\D*)\s.?(\d)\-(\d).?\s(\D*)\s\((\d*)\'\)/.exec(text);
    var correction = false;
    if (!arr) { // Correction tweet?
      arr = /(Correction: )?(\D*)\s.?(\d)\-(\d).?\s(\D*) http/.exec(text);
      arr.splice(1, 1);
      correction = true;
    }
    return {
        teams: [mapTeam(arr[1]), mapTeam(arr[4])]
      , score: [parseInt(arr[2]), parseInt(arr[3])]
      , timeGoal: parseInt(arr[5]) || null
      , correction: correction
      , fromTwitter: true
    }
  }

  /**
   * TEMP.
   */
  // var tweets = JSON.parse(fs.readFileSync(__dirname + '/../test/mocks/GoalFlashTweets.json', 'utf-8'));
  // setTimeout(function() {
  //   var data = tweets[0];
  //   var data = {
  //     // text: "Brazil *4-2 Chile (101') http://t.co/blabla #GoalFlash #WorldCup"
  //     // text: "Correction: Brazil 3-2 Chile http://www.goal.com/  #GoalFlash #WorldCup"
  //     text: "Russia 1-3 Saudi Arabia (12') http://t.co/blabla #GoalFlash #WorldCup"
  //     // text: "Correction: Colombia 0-0 Italia http://www.goal.com/  #GoalFlash #WorldCup"
  //   };
  //   if(!data.text) return;       
  //   // if(data.user.screen_name != TWITTER_USERNAME) return;
  //   console.log('GOOOOALLLL : ');
  //   console.log(humanize.date("Y-m-d H:i:s")+" DATA: ", data.text);
  //   isConnected = true;
  //   Games.newScore(analyzeTweet(data));
  // }, 5000);

  /**
   * Connect to the twitter stream.
   */
  var connectStream = function() {
    if (!twitterCreds.consumer_key) {
      console.error('There is no twitter credentials for the stream. Set them in env variables.');
      // process.exit();
      return;
    }
    console.log(humanize.date("Y-m-d H:i:s")+" Connecting to the Twitter Stream for @"+TWITTER_USERNAME);
    twit.stream('user', {track:TWITTER_USERNAME}, function(stream) {
      console.log(humanize.date("Y-m-d H:i:s")+" Connected");
      stream.on('data', function(data) {
        if(!data.text) return;       
        if(data.user.screen_name != TWITTER_USERNAME) return;
        console.log('GOOOOALLLL : ');
        console.log(humanize.date("Y-m-d H:i:s")+" DATA: ", data.text);
        isConnected = true;
        Games.newScore(analyzeTweet(data));
      });

      stream.on('error', function(error) {
        console.error("Error in the twitter stream: ", error);
        isConnected = false;
        // process.exit(1);<commit_msg>listen to 'GoalFlash' (#22)<commit_after>/**
 * Listen to a twitter stream to get the score.
 *
 * Borrowed from https://github.com/xdamman/ReplayLastGoal.
 */

/**
 * Dependencies.
 */
var twitter = require('twitter')
  , humanize = require('humanize')
  , fs = require('fs')
  ;

/**
 * Constants.
 */
var TWITTER_USERNAME = "GoalFlash";

module.exports = function(server) {

  /**
   * Dependencies.
   */
  var Games = server.controllers.games;

  /**
   * Variables.
   */
  var twitterCreds = {
      consumer_key: process.env.TWITTER_KEY
    , consumer_secret: process.env.TWITTER_SECRET
    , access_token_key: process.env.TWITTER_TOKEN
    , access_token_secret: process.env.TWITTER_TOKEN_SECRET
  };
  var twit = new twitter(twitterCreds);
  var isConnected = true;

  /**
   * Map teams.
   */
  var mapTeam = function(team) {
    if (team === "Côte d'Ivoire")
      team = "Ivory Coast";
    if (team === "United States")
      team = "USA";

    return team;
  }

  /**
   * Analyze tweet to extract teams and score.
   */
  var analyzeTweet = function(tweet) {
    var text = tweet.text;
    var arr = /(\D*)\s.?(\d)\-(\d).?\s(\D*)\s\((\d*)\'\)/.exec(text);
    var correction = false;
    if (!arr) { // Correction tweet?
      arr = /(Correction: )?(\D*)\s.?(\d)\-(\d).?\s(\D*) http/.exec(text);
      arr.splice(1, 1);
      correction = true;
    }
    return {
        teams: [mapTeam(arr[1]), mapTeam(arr[4])]
      , score: [parseInt(arr[2]), parseInt(arr[3])]
      , timeGoal: parseInt(arr[5]) || null
      , correction: correction
      , fromTwitter: true
    }
  }

  /**
   * TEMP.
   */
  // var tweets = JSON.parse(fs.readFileSync(__dirname + '/../test/mocks/GoalFlashTweets.json', 'utf-8'));
  // setTimeout(function() {
  //   var data = tweets[0];
  //   var data = {
  //     // text: "Brazil *4-2 Chile (101') http://t.co/blabla #GoalFlash #WorldCup"
  //     // text: "Correction: Brazil 3-2 Chile http://www.goal.com/  #GoalFlash #WorldCup"
  //     text: "Russia 1-3 Saudi Arabia (12') http://t.co/blabla #GoalFlash #WorldCup"
  //     // text: "Correction: Colombia 0-0 Italia http://www.goal.com/  #GoalFlash #WorldCup"
  //   };
  //   if(!data.text) return;       
  //   // if(data.user.screen_name != TWITTER_USERNAME) return;
  //   console.log('GOOOOALLLL : ');
  //   console.log(humanize.date("Y-m-d H:i:s")+" DATA: ", data.text);
  //   isConnected = true;
  //   Games.newScore(analyzeTweet(data));
  // }, 5000);

  /**
   * Connect to the twitter stream.
   */
  var connectStream = function() {
    if (!twitterCreds.consumer_key) {
      console.error('There is no twitter credentials for the stream. Set them in env variables.');
      // process.exit();
      return;
    }
    console.log(humanize.date("Y-m-d H:i:s")+" Connecting to the Twitter Stream for @"+TWITTER_USERNAME);
    twit.stream('statuses/filter', {track: TWITTER_USERNAME}, function(stream) {
      console.log(humanize.date("Y-m-d H:i:s")+" Connected");
      stream.on('data', function(data) {
        console.log('tweet: ', data.user.screen_name, data.text)
        if(!data.text) return;       
        if(data.user.screen_name != TWITTER_USERNAME) return;
        console.log('GOOOOALLLL : ');
        console.log(humanize.date("Y-m-d H:i:s")+" DATA: ", data.text);
        isConnected = true;
        Games.newScore(analyzeTweet(data));
      });

      stream.on('error', function(error) {
        console.error("Error in the twitter stream: ", error);
        isConnected = false;
        // process.exit(1);
{'fraction_non_alphanumeric': 0.1821433681499499, 'fraction_numerical': 0.00801259121476606, 'mean_word_length': 2.5374493927125505, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6506697', 'n_tokens_mistral': 2614, 'n_tokens_neox': 2507, 'n_words': 484}