-
Notifications
You must be signed in to change notification settings - Fork 1
/
discourse2nntp.py
381 lines (322 loc) · 13.5 KB
/
discourse2nntp.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
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
import datetime
import email.Utils
import iso8601
import json
import md5
import socket
import sys
import time
import urllib
from cStringIO import StringIO
from email.Message import Message
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from twisted.internet import reactor, defer
from twisted.news import database, news, nntp
from twisted.python import log
from twisted.web import client
from zope.interface import implements
DEBUG = False
API_HOST = ''
API_KEY = ''
API_USERNAME = ''
API_URL = ''
# TODO: Do not hardcode categories
CATEGORIES = ['category/yleista.json',
'category/ohjelmointi.json',
'category/tiedotus.json',
'category/vapaa-aika.json',
'category/meta.json',
'category/huuhaa.json',
'category/blog.json',
'category/testi.json',
'category/pihvi.json',
]
def api_get(path, params=None):
if params is None:
params = {}
else:
params = params.copy()
defaultParams = {'api_key': API_KEY, 'api_username': API_USERNAME}
params.update(defaultParams)
data = urllib.urlencode(params)
url = "%s/%s?%s" % (API_URL, path, data)
debug('API_GET %s', (url,))
return client.getPage(url)
def debug(msg, params=()):
if DEBUG:
print msg % params
# TODO: Rename topics as posts where applicable
class Category(object):
refreshRate = 60 * 5
def __init__(self, path):
self.title = ""
self.path = path
self.topics = []
self.topicByIdMap = {}
self.postNumberSeen = set()
self.lastRefreshTime = 0
self.refreshing = None
def topicByIdx(self, idx):
"""Return topic using NNTP article id"""
return self.topics[idx - 1]
def topicByMessageId(self, id):
"""Return topic by mail Message-Id"""
return self.topicByIdMap[id]
def postsByTopicId(self, topicId):
"""Return posts for topicId in post number sorted order"""
return sorted([x for x in self.topics if x['TopicId'] == str(topicId)],
key=lambda x: x['PostNumber'])
def hasTopicId(self, id):
return id in self.topicByIdMap
def topicCount(self):
return len(self.topics)
def parsePostsFromTopicJson(self, topicJson, postJson):
guid = md5.md5(str(postJson['topic_id']) +
str(postJson['id'])).hexdigest()
messageId = '<%s@%s>' % (guid, API_HOST)
if messageId in self.topicByIdMap:
# TODO: Detect update/edit
debug('detected duplicate topic')
return None
topic = MIMEMultipart('alternative')
# TODO: Sometimes From is shown as empty in Gnus (invalid data error)
topic['From'] = Header(postJson['name'], 'utf8')
topic['Newsgroups'] = self.path
topic['Message-Id'] = messageId
topic['Subject'] = Header(topicJson['title'], 'utf8')
# TODO: Fix timezone error
topic['Date'] = email.Utils.formatdate(
time.mktime(
iso8601.parse_date(postJson['created_at']).utctimetuple()))
# Discourse stuff
topic['PostNumber'] = str(postJson['post_number'])
topic['ReplyToPostNumber'] = str(postJson['reply_to_post_number'])
topic['TopicId'] = str(postJson['topic_id'])
topic['DiscourseLink'] = (API_URL +
'/t/%s/%i/%i' % (topicJson['slug'],
topicJson['id'],
postJson['post_number']))
# TODO: Fix relative urls in body
# TODO: Youtube inline videos not in cooked?
bodyText = postJson['cooked'].encode('utf8', errors='xmlcharrefreplace')
body = MIMEText(bodyText, 'html')
topic.attach(body)
return topic
def refreshIfNeeded(self):
timeSinceRefresh = time.time() - self.lastRefreshTime
if timeSinceRefresh > self.refreshRate:
if not self.refreshing:
debug("refreshing")
self.refreshing = self._refresh()
d = defer.Deferred()
self.refreshing.chainDeferred(d)
return d
else:
return defer.succeed(None)
@defer.inlineCallbacks
def _refresh(self):
debug('Start refresh')
# Get the category
try:
categoryJson = yield api_get(self.path)
categoryJson = json.loads(categoryJson)
debug('Loaded topic data from %s', (self.path))
except Exception, err:
print 'Failed to get topics for "%s"' % self.path
raise err
# Get topic jsons for category
# TODO: How to detect only new topics?
# - By message count? But that wouldn't support post update
topicIds = [x['id'] for x in categoryJson[u'topic_list'][u'topics']]
for topicId in topicIds:
topicJson = yield api_get('t/%s.json' % topicId)
posts = yield self._retrieveAndParseTopic(json.loads(topicJson))
# Remove the refresh lock
self.refreshing = None
self.lastRefreshTime = time.time()
@defer.inlineCallbacks
def _retrieveAndParseTopic(self, topicJson):
debug("Retrieving and parsing posts for topic")
postIds = topicJson['post_stream']['stream']
# TODO: Fetch multiple posts with one bulk get
# TODO: Sort by post number?
for id in postIds:
if id in self.postNumberSeen:
# TODO: Fix update
debug('Skipped post fetch because number seen')
continue
postJson = yield api_get('t/%s/posts.json' % topicJson['id'], {"post_ids[]": id})
postJson = json.loads(postJson)
post = postJson['post_stream']['posts'][0]
parsedPost = yield self._parsePost(topicJson, post)
if parsedPost:
self.topics.append(parsedPost)
self.topicByIdMap[parsedPost['Message-Id']] = parsedPost
self.postNumberSeen.add(id)
else:
print 'Did not parse post?'
# TODO: Extract method
# 1. Get posts for topic_id
# 2. Get first post number from topic posts
# 3. Map reply to post numbers to post numbers in
# references with first post always assigned
topicId = topicJson['id']
postsForTopic = self.postsByTopicId(topicId)
postsByPostNumber = dict((x['PostNumber'], x) for x in postsForTopic)
firstPost = postsByPostNumber['1']
for post in postsForTopic:
if 'References' in post: continue
refs = [firstPost['Message-Id']]
replyTo = post.get('ReplyToPostNumber', None)
# TODO: Fix recursivity
if replyTo is not None and replyTo != 'None':
byNum = postsByPostNumber.get(replyTo, None)
if byNum:
refs.append(byNum['Message-Id'])
post['References'] = ', '.join(refs)
defer.returnValue(True)
def _parsePost(self, topicJson, postJson):
post = self.parsePostsFromTopicJson(topicJson, postJson)
return defer.succeed(post)
def groupInfo(self):
postingAllowed = 'n'
return (self.path, len(self.topics), 0, postingAllowed)
def groupRequestInfo(self):
return (self.path, len(self.topics), len(self.topics), 1, {})
class CategoryStorage(object):
'keeps articles in memory, loses them when the process exits'
implements(database.INewsStorage)
def __init__(self, categories):
self.categories = {}
for category in categories:
self.categories[category] = Category(category)
def refreshAll(self):
return defer.DeferredList(
category.refreshIfNeeded() for category in self.categories.values())
def _refreshAllAndCall(self, func, *args, **kwargs):
return self.refreshAll().addCallback(
lambda _: func(*args, **kwargs))
def _refreshCategoryAndCall(self, groupName, func, *args, **kwargs):
if groupName in self.categories:
category = self.categories[groupName]
return category.refreshIfNeeded().addCallback(
lambda _: func(*args, **kwargs))
else:
return defer.fail(KeyError(groupName))
def newgroupsRequest(self):
# TODO: Implement real version, now always returns everything
# TODO: Parameters
return defer.succeed(self.categories.keys())
def listRequest(self):
return self._refreshAllAndCall(self._listRequest)
def _listRequest(self):
return [x.groupInfo() for x in self.categories.values()]
def listGroupRequest(self, groupname):
return self._refreshCategoryAndCall(groupName, self._listGroupRequest,
groupName)
def _listGroupRequest(self, groupName):
category = self.categories[groupName]
return range(1, category.topicCount() + 1)
def subscriptionRequest(self):
return defer.succeed(self.categories.keys())
def overviewRequest(self):
return defer.succeed(database.OVERVIEW_FMT)
def groupRequest(self, groupName):
return self._refreshCategoryAndCall(groupName,
self._groupRequest,
groupName)
def _groupRequest(self, groupName):
return defer.succeed(self.categories[groupName].groupRequestInfo())
def xoverRequest(self, groupName, low, high):
return self._refreshCategoryAndCall(groupName,
self._processXOver,
groupName, low, high,
database.OVERVIEW_FMT)
def _processXOver(self, groupName, low, high, headerNames):
category = self.categories[groupName]
if low is None: low = 1
if high is None: high = category.topicCount() - 1
results = []
for i in range(low, high + 1):
topic = category.topicByIdx(i)
topicData = topic.as_string(unixfrom=False)
headerValues = [i]
for header in headerNames:
if header == 'Byte-Count:':
headerValues.append(len(topicData))
elif header == 'Line-Count:':
headerValues.append(len(topicData.split('\n')))
else:
headerValues.append(topic.get(header, ''))
results.append(headerValues)
return defer.succeed(results)
def xhdrRequest(self, groupName, low, high, header):
return self._refreshCategoryAndCall(groupName,
self._processXOver,
groupName, low, high,
[header])
def articleExistsRequest(self, groupName, id):
category = self.categories[groupName]
return defer.succeed(category.hasTopicId(id))
def articleRequest(self, groupName, index, id=None):
category = self.categories[groupName]
if id:
topic = category.topicByMessageId(id)
index = category.topics.index(topic) + 1
else:
topic = category.topicByIdx(index)
for topicId, t, in category.topicByIdMap.items():
if t is topic:
id = topicId
break
topicData = topic.as_string(unixfrom=False)
return defer.succeed((index, id, (StringIO(topicData))))
def headRequest(self, groupName, index=None):
category = self.categories[groupName]
topic = category.topicByIdx(index)
headers = '\n'.join('%s: %s' % (x[0], x[1]) for x in topic.items())
return defer.succeed((index, topic['Message-Id'], headers))
def bodyRequest(self, groupName, index):
category = self.categories[groupName]
topic = categgory.articleByIdx(index)
return defer.succeed(topic.body)
def postRequest(self, message):
return defer.fail(Exception("read-only for now"))
class DebuggingNNTPProtocol(nntp.NNTPServer):
debug = True
COMMANDS = nntp.NNTPServer.COMMANDS
COMMANDS.append('NEWGROUPS')
def do_NEWGROUPS(self, date, time, timezone='GMT'):
defer = self.factory.backend.newgroupsRequest()
defer.addCallbacks(self._gotNewgroups, self._errNewgroups)
def _gotNewgroups(self, groups):
self.sendLine('231 list of new newsgroups follows')
self.sendLine('\t'.join(groups))
self.sendLine('.')
def _errNewgroups(self, failure):
print 'NEWGROUPS failed: ', failure
self.sendLine('500 Failed to get newgroups')
def lineReceived(self, line):
if self.debug:
print 'CLIENT:', line
nntp.NNTPServer.lineReceived(self, line)
def sendLine(self, line):
nntp.NNTPServer.sendLine(self, line)
if self.debug:
print 'SERVER:', line
class DebuggingNNTPFactory(news.NNTPFactory):
protocol = DebuggingNNTPProtocol
if __name__ == '__main__':
if len(sys.argv) == 4:
API_HOST = sys.argv[1]
API_KEY = sys.argv[2]
API_USERNAME = sys.argv[3]
API_URL = 'https://' + API_HOST
else:
print 'Usage: %s api_host api_key api_username' % sys.argv[0]
sys.exit(0)
factory = DebuggingNNTPFactory(CategoryStorage(CATEGORIES))
reactor.listenTCP(8119, factory)
reactor.run()