~motoster/gwibber/facebook-offers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
#!/usr/bin/env python

from gwibber.microblog import network, util
from gwibber.microblog.util import resources
import hashlib, time
from gettext import lgettext as _
from gwibber.microblog.util.auth import Authentication
from gwibber.microblog.util.const import *
# Try to import * from custom, install custom.py to include packaging 
# customizations like distro API keys, etc
try:
  from gwibber.microblog.util.custom import *
except:
  pass
from gwibber.microblog.util.time import parsetime

from datetime import datetime, timedelta

import logging
logger = logging.getLogger("Facebook")
logger.debug("Initializing.")

import json, urllib

PROTOCOL_INFO = {
  "name": "Facebook",
  "version": "1.1",
  
  "config": [
    "color",
    "receive_enabled",
    "send_enabled",
    "username",
    "uid",
    "private:access_token"
  ],

  "authtype": "facebook",
  "color": "#64006C",

  "features": [
    "send",
    "reply",
    "receive",
    "thread",
    "delete",
    "send_thread",
    "like",
    "unlike",
    "sincetime"
  ],

  "default_streams": [
    "receive",
    "images",
    "links",
    "videos",
  ]
}

URL_PREFIX = "https://graph.facebook.com/"
POST_URL = "http://www.facebook.com/profile.php?id=%s&v=feed&story_fbid=%s&ref=mf"


def convert_time(data):
    """Extract and convert the time to a timestamp (seconds since Epoch).

    First, look for the 'updated_time' key in the data, falling back to
    'created_time' if the former is missing.
    
    """
    # Convert from an ISO 8601 format time string to a Epoch timestamp.
    # Assume standard ISO 8601 'T' separator, no microseconds, and naive
    # time zone as per:
    # https://developers.facebook.com/docs/reference/api/event/
    time_string = data.get('updated_time', data['created_time'])
    return parsetime(time_string)


class Client:
  """Query Facebook and convert data.
  
  The Client class is responsible for querying Facebook and turning the data obtained
  into data that Gwibber can understand. Facebook uses a version of oauth for security.
  Tokens have already been obtained when the account was set up in Gwibber and are used to 
  authenticate when getting data.
  
  """
  def __init__(self, acct):
    self.account = acct
    self.user_id = acct.get("uid", None)
    self._loop = None

  def _check_error(self, data):
    """Checks if data is from the correct form.
    
    Checks to ensure the data obtained by Facebook is on the correct form.
    If not, an error is logged in gwibber.log
    
    Arguments: 
    data -- A data structure obtained from Foursquare
    
    Returns:
    True if data is contains an error or is not a dictionary, otherwise, False.
      
    """
    if isinstance(data, dict):
      if data.has_key("error"):
        logger.info("Facebook error %s - %s", data["error"]["type"], data["error"]["message"])
        return True
      else: 
        return False
    return True
    
  def _retrieve_user_id(self):
    data = json.loads(urllib.urlopen("https://graph.facebook.com/me?access_token=" + self.account["access_token"]).read())
    if isinstance(data, dict):
      if data.has_key("id") and data.has_key("name"):
        self.account["username"] = data["name"]
        self.account["uid"] = data["id"]
    else:
      # Make a desparate attempt to guess the id from the url
      uid = url.split('-')[1].split('%7C')[0]
      if isinstance(uid, int) and len(uid) > 2:
        acct = json.loads(urllib.urlopen("https://graph.facebook.com/" + str(uid)).read())
        if isinstance(acct, dict):
          if acct.has_key("id") and acct.has_key("name"):
            self.account["uid"] = acct["id"]
            self.account["username"] = acct["name"]
        else:
          logger.error("Couldn't get facebook user ID")
    if "uid" in self.account:
      self.user_id = self.account["uid"]

  def _login(self):
    old_token = self.account.get("access_token", None)
    with self.account.login_lock:
      # Perform the login only if it wasn't already performed by another thread
      # while we were waiting to the lock
      if self.account.get("access_token", None) == old_token:
        self._locked_login(old_token)

    return "access_token" in self.account and \
        self.account["access_token"] != old_token

  def _locked_login(self, old_token):
    logger.debug("Re-authenticating" if old_token else "Logging in")

    auth = Authentication(self.account, logger)
    reply = auth.login()
    if reply and reply.has_key("AccessToken"):
      self.account["access_token"] = reply["AccessToken"]
      self._retrieve_user_id()
      logger.debug("User id is: %s" % self.account["uid"])
    else:
      logger.error("Didn't find token in session: %s", (reply,))

  def _get(self, operation, post=False, single=False, **args):
    """Establishes a connection with Facebook and gets the data requested.
    
    Arguments: 
    operation -- The end of the URL to look up on Facebook
    post -- True is this is a send, False if a receive (False by default)
    single -- True if a single checkin is requested, False if multiple (False by default)
    **args -- Arguments to be added to the URL when accessed. 
    
    Returns:
    A list of Facebook objects.
    
    """
    if "access_token" not in self.account and not self._login():
      logstr = """%s: %s - %s""" % (PROTOCOL_INFO["name"], _("Authentication failed"), "Auth needs updating")
      logger.error("%s", logstr)
      return [{"error": {"type": "auth", "account": self.account, "message": _("Authentication failed, please re-authorize")}}]

    args.update({
      "access_token": self.account["access_token"]
    })

    sig = "".join("%s=%s" % (k, v) for k, v in sorted(args.items()))
    args["sig"] = hashlib.md5(sig + self.account["access_token"]).hexdigest()
    data = network.Download((URL_PREFIX + operation), args, post).get_json()

    resources.dump(self.account["service"], self.account["id"], data)

    if isinstance(data, dict) and data.get("error_msg", 0):
      if "permission" in data["error_msg"]:
        # Try again, if we get a new token
        if self._login():
          return self._get(operation, post, single, args)
        else:
          logstr = """%s: %s - %s""" % (PROTOCOL_INFO["name"], _("Authentication failed"), data["error_msg"])
          logger.error("%s", logstr)
          return [{"error": {"type": "auth", "account": self.account, "message": data["error_msg"]}}]
      elif data["error_code"] == 102:
        logstr = """%s: %s - %s""" % (PROTOCOL_INFO["name"], _("Session invalid"), data["error_msg"])
        logger.error("%s", logstr)
        return [{"error": {"type": "auth", "account": self.account, "message": data["error_msg"]}}]
      else:
        logstr = """%s: %s - %s""" % (PROTOCOL_INFO["name"], _("Unknown failure"), data["error_msg"])
        logger.error("%s", logstr)
        return [{"error": {"type": "unknown", "account": self.account, "message": data["error_msg"]}}]

    return data

  def _sender(self, data):
    """Parses the sender of the Facebook object.
    
    Arguments:
    data -- A Facebook object
    
    Returns:
    A sender object in a format compatible with Gwibber's database.
    
    """
    sender = {
      "name": data["name"],
      "id": str(data.get("id", '')),
      "is_me": str(data.get("id", '')) == self.user_id,
      "image": URL_PREFIX + data["id"] + "/picture?type=square" ,
      "url": "https://www.facebook.com/profile.php?id=" + str(data.get("id", ''))
    }
    return sender
  
  def _message(self, data):
    """Parses a Facebook object.
    
    Arguments:
    data -- A Facebook object
    
    Returns:
    A Facebook object in a format compatible with Gwibber's database.
    
    """
    if type(data) != dict:
      logger.error("Cannot parse message data: %s", str(data))
      return {}

    m = {}
    m["mid"] = str(data["id"])
    m["service"] = "facebook"
    m["account"] = self.account["id"]

    m["time"] = convert_time(data)
    m["url"] = "https://facebook.com/" + data["id"].split("_")[0] + "/posts/" + data["id"].split("_")[1]
    

    if data.get("attribution", 0):
      m["source"] = util.strip_urls(data["attribution"]).replace("via ", "")
    
    if data.has_key("message"):
      m["to_me"] = ("@%s" % self.account["username"]) in data["message"]
    if data.get("message", "").strip():
      m["text"] = data["message"]
      m["html"] = util.linkify(data["message"])
      m["content"] = m["html"]
    else:
      m["text"] = ""
      m["html"] = ""
      m["content"] = ""

    m["sender"] = self._sender(data["from"])

    m["type"] = data["type"]

    if data["type"] == "checkin":
      m["location"] = {}
      if isinstance(data["place"], dict):
        m["location"]["id"] = data["place"]["id"]
        m["location"]["name"] = data["place"].get("name", None)
        if m["location"]["name"]:
          m["html"] += " " + _("at").decode('utf8') + " <p><b>%s</b></p>" % m["location"]["name"]
          m["content"] = m["html"]
          m["text"] += " "  + _("at").decode('utf8') + " " + m["location"]["name"]
        if data["place"].has_key("location"):
          m["location"]["latitude"] = data["place"]["location"].get("latitude", None)
          m["location"]["longitude"] = data["place"]["location"].get("longitude", None)
          m["location"]["city"] = data["place"]["location"].get("city", None)
          m["location"]["state"] = data["place"]["location"].get("state", None)
          m["location"]["country"] = data["place"]["location"].get("country", None)
    elif data["type"] == "photo":
      m["photo"] = {}
      m["photo"]["picture"] = data.get("picture", None)
      m["photo"]["url"] = data.get("link", None)
      m["photo"]["name"] = data.get("name", None)
    elif data["type"] == "video":
      m["video"] = {}
      m["video"]["picture"] = data.get("picture", None)
      m["video"]["source"] = data.get("source", None)
      m["video"]["url"] = data.get("link", None)
      m["video"]["name"] = data.get("name", None)
      m["video"]["icon"] = data.get("icon", None)
      m["video"]["properties"] = data.get("properties", {})
    elif data["type"] == "link":
      m["link"] = {}
      m["link"]["picture"] = data.get("picture", None)
      m["link"]["name"] = data.get("name", None)
      m["link"]["description"] = data.get("description", None)
      m["link"]["url"] = data.get("link", None)
      m["link"]["icon"] = data.get("icon", None)
      m["link"]["caption"] = data.get("caption", None)
      m["link"]["properties"] = data.get("properties", {})
    elif data["type"] == "question":
      m["question"] = {}
      m["question"]["id"] = data["id"]
      m["question"]["text"] = data.get("question", None)
      if not m["question"]["text"]:
        m["question"]["text"] = data.get("story", None)
      if data.has_key("options") and isinstance(data["options"], dict):
        if isinstance(data["options"]["data"], dict):
          m["question"]["answers"] = []
          for a in data["options"]["data"]:
            answer = {}
            answer["id"] = a.get("id", None)
            answer["name"] = a.get("name", None)
            answer["votes"] = a.get("votes", None)
            m["question"]["answers"].append(answer)
      if m["question"]["text"] and len(m["text"]) < 1:
        m["text"] = m["question"]["text"]
        m["html"] = m["text"]
        m["content"] = m["html"]
    elif data["type"] == "status":
      pass
    else:
      logger.error ("facebook: unexpected type %s", data["type"])
    
    if data.has_key("privacy"):
      m["privacy"] = {}
      m["privacy"]["description"] = data["privacy"]["description"]
      m["privacy"]["value"] = data["privacy"]["value"]

    # Handle target for wall posts with a specific recipient
    if data.has_key("to"):
      m["sender"]["name"] += u" \u25b8 %s"%(data["to"]["data"][0]["name"])

    if data.has_key("likes"):
      m["likes"] = {}
      m["likes"]["liked"] = False
      if isinstance(data["likes"], dict):
        m["likes"]["count"] = data["likes"]["count"]
        if data["likes"].has_key("data"):
          m["likes"]["data"] = data["likes"]["data"]
          for d in m["likes"]["data"]:
            if self.user_id == str(d["id"]):
              m["likes"]["liked"] = True
      else:
        m["likes"]["count"] = data["likes"]

    if data.get("comments", 0):
      m["comments"] = []
      if data["comments"].has_key("data"):
        for item in data["comments"]["data"]:
          m["comments"].append({
              "text": item["message"],
              "time": convert_time(data),
              "sender": self._sender(item["from"]),
            })

    if data.get("attachment", 0):
      if data["attachment"].get("name", 0):
        m["content"] += "<p><b>%s</b></p>" % data["attachment"]["name"]

      if data["attachment"].get("description", 0):
        m["content"] += "<p>%s</p>" % data["attachment"]["description"]

    return m

  def __call__(self, opname, **args):
    return getattr(self, opname)(**args)

  def receive(self, since=None):
    """Gets a list of Facebook objects and add them to the database.  
    
    Arguments: 
    since -- The time to get Facebook objects from
    
    Returns:
    A list of Gwibber compatible objects which have been parsed by the parse function.
    
    """
    if since is None:
      since = (datetime.now() - timedelta(hours=240.0)).isoformat()
    else:
      since = datetime.fromtimestamp(since).isoformat()

    data = self._get("me/home", since=since, limit=100)
    
    logger.debug("<STATS> facebook:receive account:%s since:%s size:%s",
        self.account["id"], str(since), len(str(data)))
    
    if not self._check_error(data):
      try:
        return [self._message(post) for post in data["data"]]
      except TypeError:
        logger.error("<facebook:receive> failed to parse message data")
        return data
    else: return 

  def delete(self, message):
    """Deletes a specified message from Facebook.
    
    Arguments: 
    message -- A Gwibber compatible message object (from Gwibber's database)
    
    Returns:
    Nothing
    
    """
    result = self._get("stream.remove", post_id=message["mid"])
    if not result:
      logger.error("<facebook:delete> failed")
      return
    return []

  def like(self, message):
    """Likes a specified message on Facebook.
    
    Arguments: 
    message -- a Gwibber compatible message object (from Gwibber's database)
    
    Returns:
    The liked message
    
    """
    result = self._get(message["mid"] + "/likes", post=True)
    if not result:
      logger.error("<facebook:like> failed")
      return []
    data = self.receive ()
    return data

  def unlike(self, message):
    """Unlikes a specified message on Facebook.
    
    Arguments: 
    message -- A Gwibber compatible message object (from Gwibber's database)
    
    Returns:
    The unliked message
    
    """
    result = self._get(message["mid"] + "/likes", post=True, method="delete")
    if not result:
      logger.error("<facebook:like> failed")
      return []
    data = self.receive ()
    return data

  def send(self, message):
    """Sends a message to Facebook.
    
    Arguments: 
    message -- The text of the message
    
    Returns:
    Nothing
    
    """
    result = self._get("me/feed", message=message, status_includes_verb=True, post=True)
    if not result:
      logger.error("<facebook:send> failed")
      return
    return []

  def send_thread(self, message, target):
    """Sends a message to Facebook as a reply to another message.
    
    Arguments: 
    message -- The text of the message
    target -- The person the message is directed at (as a Gwibber compatible object)
    
    Returns:
    Nothing
    
    """
    result = self._get(target["mid"] + "/comments", message=message, post=True)
    if not result:
      logger.error("<facebook:send_thread> failed")
      return
    return []