~ubuntu-branches/ubuntu/precise/gwibber-service-sina/precise-201203201005

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
from gwibber.microblog import network, util
from htmlentitydefs import name2codepoint
import re
import gnomekeyring
from oauth import oauth
from gwibber.microblog.util import log, resources
from gettext import lgettext as _
import sina.utils
log.logger.name = "Sina"

PROTOCOL_INFO = {
  "name": "Sina",
  "version": "1.0",
  
  "config": [
    "private:secret_token",
    "access_token",
    "username",
    "color",
    "receive_enabled",
    "send_enabled",
  ],
 
  "authtype": "oauth1a",
  "color": "#729FCF",

  "features": [
    "send",
    "receive",
    "search",
    "tag",
    "reply",
    "responses",
    "private",
    "public",
    "delete",
    "retweet",
    "like",
    "send_thread",
    "send_private",
    "user_messages",
    "sinceid",
    "lists",
    "list",
  ],

  "default_streams": [
    "receive",
    "images",
    "responses",
    "private",
    "lists",
  ],
}

URL_PREFIX = "http://t.sina.com.cn"
API_PREFIX = "http://api.t.sina.com.cn"


def unescape(s):
  return re.sub('&(%s);' % '|'.join(name2codepoint), 
    lambda m: unichr(name2codepoint[m.group(1)]), s)

class Client:
  def __init__(self, acct):
    self.service = util.getbus("Service")
    if acct.has_key("secret_token") and acct.has_key("password"): acct.pop("password")
    self.account = acct

    if not acct.has_key("access_token") and not acct.has_key("secret_token"):
      return [{"error": {"type": "auth", "account": self.account, "message": _("Failed to find credentials")}}]

    self.sigmethod = oauth.OAuthSignatureMethod_HMAC_SHA1()
    self.consumer = oauth.OAuthConsumer(*sina.utils.get_sina_keys())
    self.token = oauth.OAuthToken(acct["access_token"], acct["secret_token"])

  def _common(self, data):
    m = {};
    try:
      m["mid"] = str(data["id"])
      m["service"] = "sina"
      m["account"] = self.account["id"]
      m["time"] = util.parsetime(data["created_at"])
      m["text"] = unescape(data["text"])
      m["to_me"] = ("@%s" % self.account["username"]) in data["text"]

      m["html"] = util.linkify(data["text"],
        ((util.PARSE_HASH, '#<a class="hash" href="%s#search?q=\\1">\\1</a>' % URL_PREFIX),
        (util.PARSE_NICK, '@<a class="nick" href="%s/\\1">\\1</a>' % URL_PREFIX)), escape=False)

      m["content"] = util.linkify(data["text"],
        ((util.PARSE_HASH, '#<a class="hash" href="gwibber:/tag?acct=%s&query=\\1">\\1</a>' % m["account"]),
        (util.PARSE_NICK, '@<a class="nick" href="gwibber:/user?acct=%s&name=\\1">\\1</a>' % m["account"])), escape=False)

      if data.has_key("retweeted_status"):
        m["retweeted_status"] = data["retweeted_status"]
      else:
        m["retweeted_status"] = None

      images = []
      if data.get("original_pic", 0):
        images.append({"src": data["thumbnail_pic"], "url": data["original_pic"]})
      if data.get("retweeted_status", 0):
        if data["retweeted_status"].get("original_pic"):
          images.append({"src": data["retweeted_status"]["thumbnail_pic"], "url": data["retweeted_status"]["original_pic"]})
      if images:
        m["images"] = images
        m["type"] = "photo"
    except: 
      log.logger.error("%s failure - %s", PROTOCOL_INFO["name"], data)
      return {}
 
    return m

  def _user(self, user):
    return {
        "name": user["name"],
        "nick": user["screen_name"],
        "id": user["id"],
        "location": user["location"],
        "followers": user.get("followers", None),
        "image": user["profile_image_url"],
        "url": "/".join((API_PREFIX, str(user["id"]))),
        "is_me": user["screen_name"] == self.account["username"],
    }
    
  def _message(self, data):
    if type(data) == type(None):
      return []

    m = self._common(data)
    m["source"] = data.get("source", False)
    
    if data.has_key("in_reply_to_status_id"):
      if data["in_reply_to_status_id"]:
        m["reply"] = {}
        m["reply"]["id"] = data["in_reply_to_status_id"]
        m["reply"]["nick"] = data["in_reply_to_screen_name"]
        if m["reply"]["id"] and m["reply"]["nick"]:
          m["reply"]["url"] = "/".join((URL_PREFIX, m["reply"]["nick"], "statuses", str(m["reply"]["id"])))
        else:
          m["reply"]["url"] = None

    m["sender"] = self._user(data["user"] if "user" in data else data["sender"])
    m["url"] = "/".join((m["sender"]["url"], "statuses", str(m["mid"])))

    return m

  def _private(self, data):
    m = self._message(data)
    m["private"] = True

    m["recipient"] = {}
    m["recipient"]["name"] = data["recipient"]["name"]
    m["recipient"]["nick"] = data["recipient"]["screen_name"]
    m["recipient"]["id"] = data["recipient"]["id"]
    m["recipient"]["image"] = data["recipient"]["profile_image_url"]
    m["recipient"]["location"] = data["recipient"]["location"]
    m["recipient"]["url"] = "/".join((URL_PREFIX, m["recipient"]["nick"]))
    m["recipient"]["is_me"] = m["recipient"]["nick"] == self.account["username"]
    m["to_me"] = m["recipient"]["is_me"]

    return m

  def _result(self, data):
    m = self._common(data)
    
    if data["to_user_id"]:
      m["reply"] = {}
      m["reply"]["id"] = data["to_user_id"]
      m["reply"]["nick"] = data["to_user"]

    m["sender"] = {}
    m["sender"]["nick"] = data["from_user"]
    m["sender"]["id"] = data["from_user_id"]
    m["sender"]["image"] = data["profile_image_url"]
    m["sender"]["url"] = "/".join((URL_PREFIX, m["sender"]["nick"]))
    m["sender"]["is_me"] = m["sender"]["nick"] == self.account["username"]
    m["url"] = "/".join((m["sender"]["url"], "statuses", str(m["mid"])))
    return m

  def _list(self, data):
    return {
        "mid": data["id"],
        "service": "sina",
        "account": self.account["id"],
        "time": 0,
        "text": data["description"],
        "html": data["description"],
        "content": data["description"],
        "url": "/".join((URL_PREFIX, data["uri"])),
        "sender": self._user(data["user"]),
        "name": data["name"],
        "nick": data["slug"],
        "key": data["slug"],
        "full": data["full_name"],
        "uri": data["uri"],
        "mode": data["mode"],
        "members": data["member_count"],
        "followers": data["subscriber_count"],
        "kind": "list",
    }

  def _get(self, path, parse="message", post=False, single=False, **args):
    url = "/".join((API_PREFIX, path))

    request = oauth.OAuthRequest.from_consumer_and_token(self.consumer, self.token,
        http_method="POST" if post else "GET", http_url=url, parameters=util.compact(args))
    request.sign_request(self.sigmethod, self.consumer, self.token)
    
    if post:
      data = network.Download(request.http_url, None, post, body=request.to_postdata()).get_json()
      #data = network.Download(request.to_url(), util.compact(args), post).get_json()
    else:
      data = network.Download(request.to_url(), None, post).get_json()

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

    if isinstance(data, dict) and data.get("errors", 0):
      if "authenticate" in data["errors"][0]["message"]:
        logstr = """%s: %s - %s""" % (PROTOCOL_INFO["name"], _("Authentication failed"), error["message"])
        log.logger.error("%s", logstr)
        return [{"error": {"type": "auth", "account": self.account, "message": data["errors"][0]["message"]}}]
      else:
        for error in data["errors"]:
          logstr = """%s: %s - %s""" % (PROTOCOL_INFO["name"], _("Unknown failure"), error["message"])
          return [{"error": {"type": "unknown", "account": self.account, "message": error["message"]}}]
    elif isinstance(data, dict) and data.get("error", 0):
      if "Incorrect signature" in data["error"]:
        logstr = """%s: %s - %s""" % (PROTOCOL_INFO["name"], _("Request failed"), data["error"])
        log.logger.error("%s", logstr)
        return [{"error": {"type": "auth", "account": self.account, "message": data["error"]}}]
    elif isinstance(data, str):
      logstr = """%s: %s - %s""" % (PROTOCOL_INFO["name"], _("Request failed"), data)
      log.logger.error("%s", logstr)
      return [{"error": {"type": "request", "account": self.account, "message": data}}]
    
    if parse == "list":
      return [self._list(l) for l in data["lists"]]
    if single: return [getattr(self, "_%s" % parse)(data)]
    if parse: return [getattr(self, "_%s" % parse)(m) for m in data]
    else: return []

  def _search(self, **args):
    data = network.Download("http://api.t.sina.com.cn/search.json", util.compact(args))
    data = data.get_json()["results"]

    return [self._result(m) for m in data]

  def __call__(self, opname, **args):
    return getattr(self, opname)(**args)
  
  def receive(self, count=util.COUNT, since=None):
    return self._get("statuses/home_timeline.json", count=count, since_id=since)

  def user_messages(self, id=None, count=util.COUNT, since=None):
    return self._get("statuses/user_timeline.json", id=id, count=count, since_id=since)

  def responses(self, count=util.COUNT, since=None):
    return self._get("statuses/mentions.json", count=count, since_id=since)

  def private(self, count=util.COUNT, since=None):
    private = self._get("direct_messages.json", "private", count=count, since_id=since) or []
    private_sent = self._get("direct_messages/sent.json", "private", count=count, since_id=since) or []
    return private + private_sent

  def public(self):
    return self._get("statuses/public_timeline.json")

  def lists(self, **args):
    following = self._get("%s/lists/subscriptions.json" % self.account["username"], "list") or []
    lists = self._get("%s/lists.json" % self.account["username"], "list") or []
    return following + lists

  def list(self, user, id, count=util.COUNT, since=None):
    return self._get("%s/lists/%s/statuses.json" % (user, id), per_page=count, since_id=since)

  def search(self, query, count=util.COUNT, since=None):
    return self._search(q=query, rpp=count, since_id=since)

  def tag(self, query, count=util.COUNT, since=None):
    return self._search(q="#%s" % query, count=count, since_id=since)

  def delete(self, message):
    return self._get("statuses/destroy/%s.json" % message["mid"], None, post=True, do=1)

  def like(self, message):
    return self._get("favorites/create/%s.json" % message["mid"], None, post=True, do=1)

  def send(self, message):
    return self._get("statuses/update.json", post=True, single=True,
        status=message)
  
  def send_private(self, message, private):
    return self._get("direct_messages/new.json", "private", post=True, single=True,
        text=message, screen_name=private["sender"]["nick"])

  def send_thread(self, message, target):
    return self._get("statuses/update.json", post=True, single=True,
        status=message, in_reply_to_status_id=target["mid"])