-
Notifications
You must be signed in to change notification settings - Fork 17
/
client.py
254 lines (205 loc) · 8.77 KB
/
client.py
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
# coding: utf-8
from __future__ import print_function, unicode_literals
import logging
from uuid import uuid4
from datetime import datetime
from operator import itemgetter
try: # python2
from urlparse import urljoin
from urllib import quote_plus
except ImportError: # python3
from urllib.parse import urljoin, quote_plus
import requests
from .consts import BASE_URL
from .exception import NotLoginError, APIError
from .article import Article
from .subscription import Subscription
LOGGER = logging.getLogger(__name__)
class InoreaderClient(object):
# paths
TOKEN_PATH = '/oauth2/token'
USER_INFO_PATH = 'user-info'
TAG_LIST_PATH = 'tag/list'
SUBSCRIPTION_LIST_PATH = 'subscription/list'
STREAM_CONTENTS_PATH = 'stream/contents/'
EDIT_TAG_PATH = 'edit-tag'
# tags
GENERAL_TAG_TEMPLATE = 'user/-/label/{}'
READ_TAG = 'user/-/state/com.google/read'
STARRED_TAG = 'user/-/state/com.google/starred'
LIKED_TAG = 'user/-/state/com.google/like'
BROADCAST_TAG = 'user/-/state/com.google/broadcast'
def __init__(self, app_id, app_key, access_token, refresh_token,
expires_at, config_manager=None):
self.app_id = app_id
self.app_key = app_key
self.access_token = access_token
self.refresh_token = refresh_token
self.expires_at = float(expires_at)
self.session = requests.Session()
self.session.headers.update({
'AppId': self.app_id,
'AppKey': self.app_key,
'Authorization': 'Bearer {}'.format(self.access_token)
})
self.config_manager = config_manager
self.proxies = self.config_manager.proxies if config_manager else None
def check_token(self):
now = datetime.now().timestamp()
if now >= self.expires_at:
self.refresh_access_token()
@staticmethod
def parse_response(response, json_data=True):
if response.status_code == 401:
raise NotLoginError
elif response.status_code != 200:
raise APIError(response.text)
return response.json() if json_data else response.text
def refresh_access_token(self):
url = urljoin(BASE_URL, self.TOKEN_PATH)
payload = {
'client_id': self.app_id,
'client_secret': self.app_key,
'grant_type': 'refresh_token',
'refresh_token': self.refresh_token,
}
response = self.parse_response(requests.post(url, json=payload, proxies=self.proxies))
self.access_token = response['access_token']
self.refresh_token = response['refresh_token']
self.expires_at = datetime.now().timestamp() + response['expires_in']
self.session.headers['Authorization'] = 'Bear {}'.format(self.access_token)
if self.config_manager:
self.config_manager.access_token = self.access_token
self.config_manager.refresh_token = self.refresh_token
self.config_manager.expires_at = self.expires_at
self.config_manager.save()
def userinfo(self):
self.check_token()
url = urljoin(BASE_URL, self.USER_INFO_PATH)
return self.parse_response(self.session.post(url, proxies=self.proxies))
def get_folders(self):
self.check_token()
url = urljoin(BASE_URL, self.TAG_LIST_PATH)
params = {'types': 1, 'counts': 1}
response = self.parse_response(self.session.post(url, params=params, proxies=self.proxies))
folders = []
for item in response['tags']:
if item.get('type') != 'folder':
continue
folder_name = item['id'].split('/')[-1]
folders.append({'name': folder_name, 'unread_count': item['unread_count']})
folders.sort(key=itemgetter('name'))
return folders
def get_tags(self):
self.check_token()
url = urljoin(BASE_URL, self.TAG_LIST_PATH)
params = {'types': 1, 'counts': 1}
response = self.parse_response(self.session.post(url, params=params, proxies=self.proxies))
tags = []
for item in response['tags']:
if item.get('type') != 'tag':
continue
folder_name = item['id'].split('/')[-1]
tags.append({'name': folder_name, 'unread_count': item['unread_count']})
tags.sort(key=itemgetter('name'))
return tags
def get_subscription_list(self):
self.check_token()
url = urljoin(BASE_URL, self.SUBSCRIPTION_LIST_PATH)
response = self.parse_response(self.session.get(url, proxies=self.proxies))
for item in response['subscriptions']:
yield Subscription.from_json(item)
def get_stream_contents(self, stream_id, c=''):
while True:
articles, c = self.__get_stream_contents(stream_id, c)
for a in articles:
yield Article.from_json(a)
if c is None:
break
def __get_stream_contents(self, stream_id, continuation=''):
self.check_token()
url = urljoin(BASE_URL, self.STREAM_CONTENTS_PATH + quote_plus(stream_id))
params = {
'n': 50, # default 20, max 1000
'r': '',
'c': continuation,
'output': 'json'
}
response = self.parse_response(self.session.post(url, params=params, proxies=self.proxies))
if 'continuation' in response():
return response['items'], response['continuation']
else:
return response['items'], None
def fetch_articles(self, folder=None, tags=None, unread=True, starred=False, limit=None):
self.check_token()
url = urljoin(BASE_URL, self.STREAM_CONTENTS_PATH)
if folder:
url = urljoin(
url,
quote_plus(self.GENERAL_TAG_TEMPLATE.format(folder))
)
params = {'c': str(uuid4())}
if unread:
params['xt'] = self.READ_TAG
if starred:
params['it'] = self.STARRED_TAG
fetched_count = 0
response = self.parse_response(self.session.post(url, params=params, proxies=self.proxies))
for data in response['items']:
categories = set([
category.split('/')[-1] for category in data.get('categories', [])
if category.find('label') > 0
])
if tags and not categories.issuperset(set(tags)):
continue
yield Article.from_json(data)
fetched_count += 1
if limit and fetched_count >= limit:
break
continuation = response.get('continuation') and (not limit or fetched_count < limit)
while continuation:
params['c'] = continuation
response = self.parse_response(
self.session.post(url, params=params, proxies=self.proxies)
)
for data in response['items']:
categories = set([
category.split('/')[-1] for category in data.get('categories', [])
if category.find('label') > 0
])
if tags and not categories.issuperset(set(tags)):
continue
yield Article.from_json(data)
fetched_count += 1
if limit and fetched_count >= limit:
break
continuation = response.get('continuation') and (not limit or fetched_count < limit)
def fetch_unread(self, folder=None, tags=None, limit=None):
for article in self.fetch_articles(folder=folder, tags=tags, unread=True):
yield article
def fetch_starred(self, folder=None, tags=None, limit=None):
for article in self.fetch_articles(folder=folder, tags=tags, unread=False, starred=True):
yield article
def add_general_label(self, articles, label):
self.check_token()
url = urljoin(BASE_URL, self.EDIT_TAG_PATH)
for start in range(0, len(articles), 10):
end = min(start + 10, len(articles))
params = {
'a': label,
'i': [articles[idx].id for idx in range(start, end)]
}
self.parse_response(
self.session.post(url, params=params, proxies=self.proxies),
json_data=False
)
def add_tag(self, articles, tag):
self.add_general_label(articles, self.GENERAL_TAG_TEMPLATE.format(tag))
def mark_as_read(self, articles):
self.add_general_label(articles, self.READ_TAG)
def mark_as_starred(self, articles):
self.add_general_label(articles, self.STARRED_TAG)
def mark_as_liked(self, articles):
self.add_general_label(articles, self.LIKED_TAG)
def broadcast(self, articles):
self.add_general_label(articles, self.BROADCAST_TAG)