<commit_before>'use strict';

const _ = require('lodash');
const requireEnvs = require('./require-envs');
const request = require('request');
const FB = require('fb');
const logger = require('./logger')(__filename);
const eventCore = require('../core/event-core');

requireEnvs(['FB_APP_ID', 'FB_APP_SECRET']);

const ACCOUNT_TO_FOLLOW = process.env.FB_PAGE_ID || "retrowappu2015";
const REFRESH_INTERVAL = 15 * 60 * 1000; // 15 min
const FB_CFG = {
  appId:     process.env.FB_APP_ID,
  appSecret: process.env.FB_APP_SECRET,
  toFollow:  ACCOUNT_TO_FOLLOW,
  xfbml:     true,
  version:   'v2.5'
};
FB.options(FB_CFG);

// # State
const state = {
  accessToken: null,
  announcements: null,
  eventIds: []
};

function initialize() {
  state.eventIds = eventCore.getEvents()
    .filter(event => !_.isUndefined(event.facebookId))
    .map(event => event.facebookId);

  _getAccessToken()
    .then(() => {
      setInterval(_updateFromFacebook, REFRESH_INTERVAL);

      // Execute update immediately
      _updateFromFacebook();
    });
}

function getAnnouncements() {
  return state.announcements;
}

function _updateFromFacebook() {
    logger.info('Updating FB data');

    FB.setAccessToken(state.accessToken);

    const promises = state.eventIds
      .map(_fetchAttending)
      .concat(_fetchAnnouncements());

    Promise.all(promises)
    .then(function(eventData) {
        logger.info('Facebook update performed');
        _.assign(state, eventData);
    }, function(error) {
        logger.error('Facebook info could not be updated', error);
    });
}

function _fetchAttending(eventId) {
  return new Promise((resolve, reject) => {

    FB.api(`/${ eventId }/?fields=attending_count`,
      function(response) {
        if (response && !response.error) {
          logger.info("Event attending fetched");

          const attendingCount = response.attending_count;
          eventCore.setAttendingCount(eventId, attendingCount);

          resolve(attendingCount);
        } else {
          logger.error("Failed to fetch event attending:", response);
          reject(response && response.error);
        }
      }
    );
  });
}

function _fetchAnnouncements() {
  return new Promise((resolve, reject) => {

    FB.api(`/${ ACCOUNT_TO_FOLLOW }/feed?fields=message,created_time,picture`,
      function(response) {
        if (response && !response.error) {
          logger.info("Announcements fetched");

          state.announcements = response.data
            .filter(x => !_.isUndefined(x.message))
            .map(x => _.pick(x, 'message', 'created_time', 'picture'));

          resolve(response);
        } else {
          logger.error("Failed to fetch announcements:", response);
          reject(response && response.error);
        }
      }
    );
  });
}

function _getAccessToken() {
  return new Promise(function(resolve, reject) {
    request.get('https://graph.facebook.com/oauth/access_token?' +
      'client_id=' + FB_CFG.appId +
      '&client_secret=' + FB_CFG.appSecret +
      '&grant_type=client_credentials',

      function(error, response, body) {
        if (body.error) {
          console.error('Error occured on Facebook Access Token fetch', body.error);<commit_msg>Fetch full picture from fb api<commit_after>'use strict';

const _ = require('lodash');
const requireEnvs = require('./require-envs');
const request = require('request');
const FB = require('fb');
const logger = require('./logger')(__filename);
const eventCore = require('../core/event-core');

requireEnvs(['FB_APP_ID', 'FB_APP_SECRET']);

const ACCOUNT_TO_FOLLOW = process.env.FB_PAGE_ID || "retrowappu2015";
const REFRESH_INTERVAL = 15 * 60 * 1000; // 15 min
const FB_CFG = {
  appId:     process.env.FB_APP_ID,
  appSecret: process.env.FB_APP_SECRET,
  toFollow:  ACCOUNT_TO_FOLLOW,
  xfbml:     true,
  version:   'v2.5'
};
FB.options(FB_CFG);

// # State
const state = {
  accessToken: null,
  announcements: null,
  eventIds: []
};

function initialize() {
  state.eventIds = eventCore.getEvents()
    .filter(event => !_.isUndefined(event.facebookId))
    .map(event => event.facebookId);

  _getAccessToken()
    .then(() => {
      setInterval(_updateFromFacebook, REFRESH_INTERVAL);

      // Execute update immediately
      _updateFromFacebook();
    });
}

function getAnnouncements() {
  return state.announcements;
}

function _updateFromFacebook() {
    logger.info('Updating FB data');

    FB.setAccessToken(state.accessToken);

    const promises = state.eventIds
      .map(_fetchAttending)
      .concat(_fetchAnnouncements());

    Promise.all(promises)
    .then(function(eventData) {
        logger.info('Facebook update performed');
        _.assign(state, eventData);
    }, function(error) {
        logger.error('Facebook info could not be updated', error);
    });
}

function _fetchAttending(eventId) {
  return new Promise((resolve, reject) => {

    FB.api(`/${ eventId }/?fields=attending_count`,
      function(response) {
        if (response && !response.error) {
          logger.info("Event attending fetched");

          const attendingCount = response.attending_count;
          eventCore.setAttendingCount(eventId, attendingCount);

          resolve(attendingCount);
        } else {
          logger.error("Failed to fetch event attending:", response);
          reject(response && response.error);
        }
      }
    );
  });
}

function _fetchAnnouncements() {
  return new Promise((resolve, reject) => {
    FB.api(`/${ ACCOUNT_TO_FOLLOW }/feed?fields=message,created_time,full_picture`,
      function(response) {
        if (response && !response.error) {
          logger.info("Announcements fetched");

          state.announcements = response.data
            .filter(x => !_.isUndefined(x.message))
            .map(x => {
              return {
                message: x.message,
                created_time: x.created_time,
                picture: x.full_picture
              };
            });

          resolve(response);
        } else {
          logger.error("Failed to fetch announcements:", response);
          reject(response && response.error);
        }
      }
    );
  });
}

function _getAccessToken() {
  return new Promise(function(resolve, reject) {
    request.get('https://graph.facebook.com/oauth/access_token?' +
      'client_id=' + FB_CFG.appId +
      '&client_secret=' + FB_CFG.appSecret +
      '&grant_type=client_credentials',

      function(error, response, body) {
        if (body.error) {
          console.error('Error occured on Facebook Access Token fetch', body.error);
{'fraction_non_alphanumeric': 0.13856427378964942, 'fraction_numerical': 0.0048565791470632875, 'mean_word_length': 2.9746682750301567, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 17, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '602452', 'n_tokens_mistral': 2059, 'n_tokens_neox': 1969, 'n_words': 383}