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
|
# Copyright (C) 2012 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""The Twitter protocol plugin."""
__all__ = [
'Twitter',
]
import logging
from oauthlib.oauth1 import Client
from urllib.parse import quote
from gwibber.utils.authentication import Authentication
from gwibber.utils.base import Base, feature
from gwibber.utils.download import get_json
from gwibber.utils.time import parsetime, iso8601utc
log = logging.getLogger('gwibber.service')
class Twitter(Base):
# StatusNet claims to mimick the Twitter API very closely (so
# closely to the point that they refer you to the twitter API
# reference docs as a starting point for learning about their
# API), So these prefixes are defined here as class attributes
# instead of the usual module globals, in the hopes that the
# StatusNet class will be able to subclass Twitter and change only
# the URLs, with minimal other changes, and magically work.
_api_base = 'https://api.twitter.com/1.1/{endpoint}.json'
_timeline = _api_base.format(endpoint='statuses/{}_timeline')
_user_timeline = _timeline.format('user') + '?screen_name={}'
_lists = _api_base.format(endpoint='lists/statuses') + '?list_id={}'
_destroy = _api_base.format(endpoint='statuses/destroy/{}')
_retweet = _api_base.format(endpoint='statuses/retweet/{}')
_url_prefix = 'https://twitter.com/'
_tweet_permalink = 'https://twitter.com/{user_id}/status/{tweet_id}'
def _locked_login(self, old_token):
result = Authentication(self._account, log).login()
if result is None:
log.error('No Twitter authentication results received.')
return
token = result.get('AccessToken')
if token is None:
log.error('No AccessToken in Twitter session: {!r}', result)
else:
self._account.access_token = token
self._account.secret_token = result.get('TokenSecret')
self._account.user_id = result.get('UserId')
self._account.user_name = result.get('ScreenName')
log.debug('{} UID: {}'.format(self.__class__.__name__,
self._account.user_id))
def _get_url(self, url, data=None):
"""Access the Twitter API with correct OAuth signed headers."""
# TODO start enforcing some rate limiting.
do_post = data is not None
# "Client" == "Consumer" in oauthlib parlance.
client_key = self._account.auth.parameters['ConsumerKey']
client_secret = self._account.auth.parameters['ConsumerSecret']
# "resource_owner" == secret and token.
resource_owner_key = self._get_access_token()
resource_owner_secret = self._account.secret_token
oauth_client = Client(client_key, client_secret,
resource_owner_key, resource_owner_secret)
headers = {}
if do_post:
headers['Content-Type'] = 'application/x-www-form-urlencoded'
# All we care about is the headers, which will contain the
# Authorization header necessary to satisfy OAuth.
uri, headers, body = oauth_client.sign(
url, body=data, headers=headers,
http_method='POST' if do_post else 'GET')
return get_json(url,
params=data,
headers=headers,
post=do_post)
def _publish_tweet(self, tweet):
"""Publish a single tweet into the Dee.SharedModel."""
tweet_id = tweet.get('id_str')
if tweet_id is None:
log.info('We got a tweet with no id! Abort!')
return
user = tweet.get('user', {})
screen_name = user.get('screen_name', '')
self._publish(
message_id=tweet_id,
message=tweet.get('text', ''),
timestamp=iso8601utc(parsetime(tweet.get('created_at', ''))),
stream='messages',
sender=user.get('name', ''),
sender_nick=screen_name,
from_me=(screen_name == self._account.user_id),
icon_uri=user.get('profile_image_url_https', ''),
liked=tweet.get('favorited', False),
url=self._tweet_permalink.format(user_id=screen_name,
tweet_id=tweet_id),
)
# https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline
@feature
def home(self):
"""Gather the user's home timeline."""
url = self._timeline.format('home')
for tweet in self._get_url(url):
self._publish_tweet(tweet)
# https://dev.twitter.com/docs/api/1.1/get/statuses/mentions_timeline
@feature
def mentions(self):
"""Gather the tweets that mention us."""
url = self._timeline.format('mentions')
for tweet in self._get_url(url):
self._publish_tweet(tweet)
# https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline
@feature
def user(self, screen_name=''):
"""Gather the tweets from a specific user.
If screen_name is not specified, then gather the tweets
written by the currently authenticated user.
"""
url = self._user_timeline.format(screen_name)
for tweet in self._get_url(url):
self._publish_tweet(tweet)
# https://dev.twitter.com/docs/api/1.1/get/lists/statuses
@feature
def list(self, list_id):
"""Gather the tweets from the specified list_id."""
url = self._lists.format(list_id)
for tweet in self._get_url(url):
self._publish_tweet(tweet)
# https://dev.twitter.com/docs/api/1.1/get/lists/list
@feature
def lists(self):
"""Gather the tweets from the lists that the we are subscribed to."""
url = self._api_base.format(endpoint='lists/list')
for twitlist in self._get_url(url):
self.list(twitlist.get('id_str', ''))
# https://dev.twitter.com/docs/api/1.1/get/direct_messages
# https://dev.twitter.com/docs/api/1.1/get/direct_messages/sent
@feature
def private(self):
"""Gather the direct messages sent to/from us."""
url = self._api_base.format(endpoint='direct_messages')
for tweet in self._get_url(url):
self._publish_tweet(tweet)
url = self._api_base.format(endpoint='direct_messages/sent')
for tweet in self._get_url(url):
self._publish_tweet(tweet)
@feature
def receive(self):
"""Gather and publish all incoming messages."""
# TODO I know mentions and lists are actually incorporated
# within the home timeline, but calling them explicitly will
# ensure that more of those types of messages appear in the
# timeline (eg, so they don't get drown out by everything
# else). I'm not sure how necessary it is, though.
self.home()
self.mentions()
self.lists()
self.private()
@feature
def send_private(self, screen_name, message):
# TODO: This is utterly broken. 403s no matter what.
url = self._api_base.format(endpoint='direct_messages/new')
tweet = self._get_url(url, dict(text=message, screen_name=screen_name))
self._publish_tweet(tweet)
# https://dev.twitter.com/docs/api/1.1/post/statuses/update
@feature
def send(self, message):
url = self._api_base.format(endpoint='statuses/update')
tweet = self._get_url(url, dict(status=message))
self._publish_tweet(tweet)
# https://dev.twitter.com/docs/api/1.1/post/statuses/update
@feature
def send_thread(self, message_id, message):
"""Send a reply message to message_id.
Note that you have to @mention the message_id owner's screen name in
order for Twitter to actually accept this as a reply. Otherwise it will
just be an ordinary tweet.
"""
url = self._api_base.format(endpoint='statuses/update')
tweet = self._get_url(url, dict(in_reply_to_status_id=message_id,
status=message))
self._publish_tweet(tweet)
# https://dev.twitter.com/docs/api/1.1/post/statuses/destroy/%3Aid
@feature
def delete(self, message_id):
url = self._destroy.format(message_id)
tweet = self._get_url(url, dict(trim_user='true'))
self._unpublish(message_id)
# https://dev.twitter.com/docs/api/1.1/post/statuses/retweet/%3Aid
@feature
def retweet(self, message_id):
url = self._retweet.format(message_id)
tweet = self._get_url(url, dict(trim_user='true'))
self._publish_tweet(tweet)
# https://dev.twitter.com/docs/api/1.1/post/friendships/destroy
@feature
def unfollow(self, screen_name):
url = self._api_base.format(endpoint='friendships/destroy')
self._get_url(url, dict(screen_name=screen_name))
# https://dev.twitter.com/docs/api/1.1/post/friendships/create
@feature
def follow(self, screen_name):
url = self._api_base.format(endpoint='friendships/create')
self._get_url(url, dict(screen_name=screen_name, follow='true'))
# https://dev.twitter.com/docs/api/1.1/post/favorites/create
@feature
def like(self, message_id):
url = self._api_base.format(endpoint='favorites/create')
tweet = self._get_url(url, dict(id=message_id))
# I don't think we need to publish this tweet because presumably
# the user has clicked the 'favorite' button on the message that's
# already in the stream...
# https://dev.twitter.com/docs/api/1.1/post/favorites/destroy
@feature
def unlike(self, message_id):
url = self._api_base.format(endpoint='favorites/destroy')
tweet = self._get_url(url, dict(id=message_id))
# https://dev.twitter.com/docs/api/1.1/get/search/tweets
@feature
def tag(self, hashtag):
"""Return a list of some recent tweets mentioning hashtag."""
url = self._api_base.format(endpoint='search/tweets')
response = self._get_url(
'{}?q=%23{}'.format(url, hashtag.lstrip('#')))
for tweet in response.get('statuses', []):
self._publish_tweet(tweet)
# https://dev.twitter.com/docs/api/1.1/get/search/tweets
@feature
def search(self, query):
"""Search for any arbitrary string."""
url = self._api_base.format(endpoint='search/tweets')
response = self._get_url('{}?q={}'.format(url, quote(query, safe='')))
for tweet in response.get('statuses', []):
self._publish_tweet(tweet)
|