view src/google.coffee @ 32:ca0b44c1a870 tip

Readme: twitter in the summary, it is best working currently.
author Bernhard Reiter <bernhard@intevation.de>
date Mon, 13 Oct 2014 13:22:17 +0200
parents 8238d312e281
children
line wrap: on
line source
# Copyright (C) 2014 by Intevation GmbH
# Author: Mathias Gebbe <mgebbe@intevation.de>
#
# This file is Free Software under the Apache License, Version 3.0;
# and comes with NO WARRANTY!
# See the documentation coming with pumpbridge for details.

https = require("https")
async = require("async")
_ = require("underscore")
Sync = require("./sync")
Routes = require("./routes")
querystring = require("querystring")
EdgeControl = require("./edgecontrol")
Edge = require("./edge")
Pump = require("./pumpio")
FromESN = require("./fromESN")
Config = require("./config")
querystring = require('querystring')

config = Config.config

bridgeid = config.bridgeid
interval = config.interval
CLIENTID = config.gpCLIENTID
CLIENTSECRET = config.gpCLIENTSECRET

###############
# google sync #
###############
sync = (user) ->
  return if not (user?)
  me = user.user_pumpio
  id = user.user_ESN.substr(0,user.user_ESN.indexOf('@'))
  if not (interval?)
    interval =  15 * 60 * 1000 # 900 000 ms (15min)

  async.waterfall [
    (callback) ->
      updateToken(user,callback)
    (updateuser,callback) ->
      user = updateuser
      #getUser(user)
      getFriends(user,callback)
  ], (err, friends) ->
    async.eachLimit friends, 2, ((friend, callb) ->
      async.waterfall [
        (callback) ->
          getStream(user, friend, callback)
        (stream, callback) ->
          return if not stream? or not stream.items? or stream.items.length is 0
          async.eachLimit stream.items, 2, ((post, cb) ->
            async.waterfall [
              (callback) ->
                console.log "check googlepost " + post.id + " to " +  me
                FromESN.search {uid: post.id + "@google_to_" + me}, callback
              (result, callback) ->
                if result.length isnt 0
                  return
                else
                  Sync.postParser post, null, 'google', callback
                #ti = new Date().getTime() - interval
                #ts = Date.parse(post.published)
                #if (ts >= ti)
                #else
                #  return
              (parsed, callback) ->
                console.log "post googlepost "+ post.id
                Pump.postUser bridgeid, me, parsed, callback
              (pumppost, callback) ->
                pumppost = JSON.parse(pumppost)
                FromESN.create
                  postid: post.id + "@google"
                  sourceUser: post.actor.id
                  sourcePost: post.url
                  pumpPost: pumppost.object.id
                  recipientUser: me
                  created: Date.now()
                , callback
            ], (err, result) ->
                 #console.log err
                 console.log "done"
                 cb()
          ), (err) ->
            callb()
      ], (err,  result) ->
    ), (err) ->
      if err
        console.log 'one post fail to process'
      else
        console.log 'all google friends processed'
  return

#######################################
###### get user info googleplus  ######
#######################################
getUser = (user) ->
  return if not (user?)
  data = ""
  id = user.user_ESN.substr(0,user.user_ESN.indexOf('@'))
  return if not (user.oauth_token?)
  token = user.oauth_token.substr(0,user.oauth_token.indexOf(';'))
  options =
   host: "www.googleapis.com"
   port: 443
   path: "/plus/v1/people/" + id + '?access_token=' + token

  https.get(options, (res) ->
    #console.log "Got response: " + res.statusCode
    res.on "data", (chunk) ->
      data += chunk
      return

    res.on "end", () ->
      user = JSON.parse(data)
      Routes.updateUserDB(user.id+'@google',user.displayName,user.displayName,user.url,user.image.url) if user.id?

  ).on "error", (e) ->
    console.log "Got error: " + e.message
    return
  return


#######################################
###### get google friends        ######
#######################################
getFriends = (user, callback) ->
  return if not user?
  data = ""
  friends = new Array()
  me = user.user_pumpio
  id = user.user_ESN.substr(0,user.user_ESN.indexOf('@'))
  return if not (user.oauth_token?)
  if user.oauth_token.indexOf(';') isnt -1
    token = user.oauth_token.substr(0,user.oauth_token.indexOf(';'))
  else
    token = user.oauth_token
  options =
   host: "www.googleapis.com"
   port: 443
   path: "/plus/v1/people/me/people/visible?key=" + CLIENTID + "&"
   headers:
     "Authorization": "Bearer " + token

  https.get(options, (res) ->
    #console.log "Got response: " + res.statusCode
    res.on "data", (chunk) ->
      data +=chunk

    res.on "end", () ->
      async.waterfall [
        (callback) ->
          users = JSON.parse(decodeURI(data))
          return if (users.error?)
          callback null,users
        (users, callback) ->
          #EdgeControl.removeEdges(me,'@google')
          async.each users.items, ((user,cb) ->
            if user.id?
              friends.push(user.id)
              #Routes.updateUserDB(user.id+'@google',user.displayName,user.displayName,user.url,user.image.url)
              #EdgeControl.addEdge(me,user.id+'@google')
              cb()
            ), (err) ->
              callback null, friends
      ], (err, friends) ->
        callback null, friends
       return

  ).on "error", (e) ->
    console.log "Got error: " + e.message

  return

#######################################
###### get google stream         ######
#######################################
getStream = (user, targetid, callback) ->
  data = ""
  max_results = 3
  me = user.user_pumpio
  id = user.user_ESN.substr(0,user.user_ESN.indexOf('@'))
  if user.oauth_token.indexOf(';') isnt -1
    token = user.oauth_token.substr(0,user.oauth_token.indexOf(';'))
  else
    token = user.oauth_token
  options =
   host: "www.googleapis.com"
   port: 443
   path: "/plus/v1/people/" + targetid + "/activities/public?maxResults="+max_results+"&key=" + CLIENTID
   headers:
     "Authorization": "Bearer " + token

  https.get(options, (res) ->
    #console.log "Got response: " + res.statusCode
    res.on "data", (chunk) ->
      data +=chunk

    res.on "end", () ->
      data = JSON.parse(data)
      callback null, data

  ).on "error", (e) ->
    console.log "Got error: " + e.message
    return

  return

getRefreshToken = (user, callback) ->
  if user.oauth_token.indexOf(';') isnt -1
    token = user.oauth_token.substr(0,user.oauth_token.indexOf(';'))
    code = user.oauth_token.substr(user.oauth_token.indexOf(';')+1 ,user.oauth_token.length)
  else
    token = user.oauth_token
  data = ""
  post_data = querystring.stringify(
    "code": code
    "client_id": CLIENTID
    "client_secret": CLIENTSECRET
    "grant_type": "authorization_code"
    "redirect_uri": "postmessage"
  )

  headers =
    "Authorization": "Bearer " + token
    "Content-Type": "application/x-www-form-urlencoded"
    'Content-Length': post_data.length

  options =
    host: "accounts.google.com"
    port: 443
    path: "/o/oauth2/token"
    method: "POST"
    headers: headers

  req = https.request(options, (res) ->
    res.setEncoding "utf8"
    res.on "data", (d) ->
      data += d

    res.on "end", () ->
      #console.log data
      data = decodeURI(data)
      data = JSON.parse(data)
      callback null, data
      #console.log '\n\n' + JSON.stringify(data.refresh_token)
      # usermap updaten und später mit extra arbeiten
    return
  )
  req.write post_data
  req.end()


  return

updateToken = (user, callback) ->
  try
    if user.oauth_token.indexOf(';') isnt -1
      token = user.oauth_token.substr(0,user.oauth_token.indexOf(';'))
    else
      token = user.oauth_token
  catch err
    console.log 'Google updateToken error' + err
  extra = user.extra_token
  data = ""
  post_data = querystring.stringify(
    "refresh_token": extra
    "client_id": CLIENTID
    "client_secret": CLIENTSECRET
    "grant_type": "refresh_token"
  )

  headers =
    "Authorization": "Bearer " + token
    "Content-Type": "application/x-www-form-urlencoded"
    'Content-Length': post_data.length

  options =
    host: "accounts.google.com"
    port: 443
    path: "/o/oauth2/token"
    method: "POST"
    headers: headers

  req = https.request(options, (res) ->
    res.setEncoding "utf8"
    res.on "data", (d) ->
      data += d

    res.on "end", () ->
      data = decodeURI(data)
      data = JSON.parse(data)
      Routes.saveUsermap(user.user_pumpio,user.user_ESN,data.access_token, user.extra_token, callback)
      #console.log '\n\n' + JSON.stringify(data.refresh_token)
      # usermap updaten und später mit extra arbeiten
    return
  )
  req.write post_data
  req.end()


  return

exports.sync = sync
exports.getUser = getUser
exports.getRefreshToken = getRefreshToken
exports.getFriends = getFriends
This site is hosted by Intevation GmbH (Datenschutzerklärung und Impressum | Privacy Policy and Imprint)