database.py 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046
  1. # -*- test-case-name: twisted.news.test -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. News server backend implementations.
  6. """
  7. import getpass, pickle, time, socket
  8. import os
  9. import StringIO
  10. from hashlib import md5
  11. from email.Message import Message
  12. from email.Generator import Generator
  13. from zope.interface import implementer, Interface
  14. from twisted.news.nntp import NNTPError
  15. from twisted.mail import smtp
  16. from twisted.internet import defer
  17. from twisted.enterprise import adbapi
  18. from twisted.persisted import dirdbm
  19. ERR_NOGROUP, ERR_NOARTICLE = range(2, 4) # XXX - put NNTP values here (I guess?)
  20. OVERVIEW_FMT = [
  21. 'Subject', 'From', 'Date', 'Message-ID', 'References',
  22. 'Bytes', 'Lines', 'Xref'
  23. ]
  24. def hexdigest(md5): #XXX: argh. 1.5.2 doesn't have this.
  25. return ''.join(map(lambda x: hex(ord(x))[2:], md5.digest()))
  26. class Article:
  27. def __init__(self, head, body):
  28. self.body = body
  29. self.headers = {}
  30. header = None
  31. for line in head.split('\r\n'):
  32. if line[0] in ' \t':
  33. i = list(self.headers[header])
  34. i[1] += '\r\n' + line
  35. else:
  36. i = line.split(': ', 1)
  37. header = i[0].lower()
  38. self.headers[header] = tuple(i)
  39. if not self.getHeader('Message-ID'):
  40. s = str(time.time()) + self.body
  41. id = hexdigest(md5(s)) + '@' + socket.gethostname()
  42. self.putHeader('Message-ID', '<%s>' % id)
  43. if not self.getHeader('Bytes'):
  44. self.putHeader('Bytes', str(len(self.body)))
  45. if not self.getHeader('Lines'):
  46. self.putHeader('Lines', str(self.body.count('\n')))
  47. if not self.getHeader('Date'):
  48. self.putHeader('Date', time.ctime(time.time()))
  49. def getHeader(self, header):
  50. h = header.lower()
  51. if h in self.headers:
  52. return self.headers[h][1]
  53. else:
  54. return ''
  55. def putHeader(self, header, value):
  56. self.headers[header.lower()] = (header, value)
  57. def textHeaders(self):
  58. headers = []
  59. for i in self.headers.values():
  60. headers.append('%s: %s' % i)
  61. return '\r\n'.join(headers) + '\r\n'
  62. def overview(self):
  63. xover = []
  64. for i in OVERVIEW_FMT:
  65. xover.append(self.getHeader(i))
  66. return xover
  67. class NewsServerError(Exception):
  68. pass
  69. class INewsStorage(Interface):
  70. """
  71. An interface for storing and requesting news articles
  72. """
  73. def listRequest():
  74. """
  75. Returns a deferred whose callback will be passed a list of 4-tuples
  76. containing (name, max index, min index, flags) for each news group
  77. """
  78. def subscriptionRequest():
  79. """
  80. Returns a deferred whose callback will be passed the list of
  81. recommended subscription groups for new server users
  82. """
  83. def postRequest(message):
  84. """
  85. Returns a deferred whose callback will be invoked if 'message'
  86. is successfully posted to one or more specified groups and
  87. whose errback will be invoked otherwise.
  88. """
  89. def overviewRequest():
  90. """
  91. Returns a deferred whose callback will be passed the a list of
  92. headers describing this server's overview format.
  93. """
  94. def xoverRequest(group, low, high):
  95. """
  96. Returns a deferred whose callback will be passed a list of xover
  97. headers for the given group over the given range. If low is None,
  98. the range starts at the first article. If high is None, the range
  99. ends at the last article.
  100. """
  101. def xhdrRequest(group, low, high, header):
  102. """
  103. Returns a deferred whose callback will be passed a list of XHDR data
  104. for the given group over the given range. If low is None,
  105. the range starts at the first article. If high is None, the range
  106. ends at the last article.
  107. """
  108. def listGroupRequest(group):
  109. """
  110. Returns a deferred whose callback will be passed a two-tuple of
  111. (group name, [article indices])
  112. """
  113. def groupRequest(group):
  114. """
  115. Returns a deferred whose callback will be passed a five-tuple of
  116. (group name, article count, highest index, lowest index, group flags)
  117. """
  118. def articleExistsRequest(id):
  119. """
  120. Returns a deferred whose callback will be passed with a true value
  121. if a message with the specified Message-ID exists in the database
  122. and with a false value otherwise.
  123. """
  124. def articleRequest(group, index, id = None):
  125. """
  126. Returns a deferred whose callback will be passed a file-like object
  127. containing the full article text (headers and body) for the article
  128. of the specified index in the specified group, and whose errback
  129. will be invoked if the article or group does not exist. If id is
  130. not None, index is ignored and the article with the given Message-ID
  131. will be returned instead, along with its index in the specified
  132. group.
  133. """
  134. def headRequest(group, index):
  135. """
  136. Returns a deferred whose callback will be passed the header for
  137. the article of the specified index in the specified group, and
  138. whose errback will be invoked if the article or group does not
  139. exist.
  140. """
  141. def bodyRequest(group, index):
  142. """
  143. Returns a deferred whose callback will be passed the body for
  144. the article of the specified index in the specified group, and
  145. whose errback will be invoked if the article or group does not
  146. exist.
  147. """
  148. class NewsStorage:
  149. """
  150. Backwards compatibility class -- There is no reason to inherit from this,
  151. just implement INewsStorage instead.
  152. """
  153. def listRequest(self):
  154. raise NotImplementedError()
  155. def subscriptionRequest(self):
  156. raise NotImplementedError()
  157. def postRequest(self, message):
  158. raise NotImplementedError()
  159. def overviewRequest(self):
  160. return defer.succeed(OVERVIEW_FMT)
  161. def xoverRequest(self, group, low, high):
  162. raise NotImplementedError()
  163. def xhdrRequest(self, group, low, high, header):
  164. raise NotImplementedError()
  165. def listGroupRequest(self, group):
  166. raise NotImplementedError()
  167. def groupRequest(self, group):
  168. raise NotImplementedError()
  169. def articleExistsRequest(self, id):
  170. raise NotImplementedError()
  171. def articleRequest(self, group, index, id = None):
  172. raise NotImplementedError()
  173. def headRequest(self, group, index):
  174. raise NotImplementedError()
  175. def bodyRequest(self, group, index):
  176. raise NotImplementedError()
  177. class _ModerationMixin:
  178. """
  179. Storage implementations can inherit from this class to get the easy-to-use
  180. C{notifyModerators} method which will take care of sending messages which
  181. require moderation to a list of moderators.
  182. """
  183. sendmail = staticmethod(smtp.sendmail)
  184. def notifyModerators(self, moderators, article):
  185. """
  186. Send an article to a list of group moderators to be moderated.
  187. @param moderators: A C{list} of C{str} giving RFC 2821 addresses of
  188. group moderators to notify.
  189. @param article: The article requiring moderation.
  190. @type article: L{Article}
  191. @return: A L{Deferred} which fires with the result of sending the email.
  192. """
  193. # Moderated postings go through as long as they have an Approved
  194. # header, regardless of what the value is
  195. group = article.getHeader('Newsgroups')
  196. subject = article.getHeader('Subject')
  197. if self._sender is None:
  198. # This case should really go away. This isn't a good default.
  199. sender = 'twisted-news@' + socket.gethostname()
  200. else:
  201. sender = self._sender
  202. msg = Message()
  203. msg['Message-ID'] = smtp.messageid()
  204. msg['From'] = sender
  205. msg['To'] = ', '.join(moderators)
  206. msg['Subject'] = 'Moderate new %s message: %s' % (group, subject)
  207. msg['Content-Type'] = 'message/rfc822'
  208. payload = Message()
  209. for header, value in article.headers.values():
  210. payload.add_header(header, value)
  211. payload.set_payload(article.body)
  212. msg.attach(payload)
  213. out = StringIO.StringIO()
  214. gen = Generator(out, False)
  215. gen.flatten(msg)
  216. msg = out.getvalue()
  217. return self.sendmail(self._mailhost, sender, moderators, msg)
  218. @implementer(INewsStorage)
  219. class PickleStorage(_ModerationMixin):
  220. """
  221. A trivial NewsStorage implementation using pickles
  222. Contains numerous flaws and is generally unsuitable for any
  223. real applications. Consider yourself warned!
  224. """
  225. sharedDBs = {}
  226. def __init__(self, filename, groups=None, moderators=(),
  227. mailhost=None, sender=None):
  228. """
  229. @param mailhost: A C{str} giving the mail exchange host which will
  230. accept moderation emails from this server. Must accept emails
  231. destined for any address specified as a moderator.
  232. @param sender: A C{str} giving the address which will be used as the
  233. sender of any moderation email generated by this server.
  234. """
  235. self.datafile = filename
  236. self.load(filename, groups, moderators)
  237. self._mailhost = mailhost
  238. self._sender = sender
  239. def getModerators(self, groups):
  240. # first see if any groups are moderated. if so, nothing gets posted,
  241. # but the whole messages gets forwarded to the moderator address
  242. moderators = []
  243. for group in groups:
  244. moderators.extend(self.db['moderators'].get(group, None))
  245. return filter(None, moderators)
  246. def listRequest(self):
  247. "Returns a list of 4-tuples: (name, max index, min index, flags)"
  248. l = self.db['groups']
  249. r = []
  250. for i in l:
  251. if len(self.db[i].keys()):
  252. low = min(self.db[i].keys())
  253. high = max(self.db[i].keys()) + 1
  254. else:
  255. low = high = 0
  256. if i in self.db['moderators']:
  257. flags = 'm'
  258. else:
  259. flags = 'y'
  260. r.append((i, high, low, flags))
  261. return defer.succeed(r)
  262. def subscriptionRequest(self):
  263. return defer.succeed(['alt.test'])
  264. def postRequest(self, message):
  265. cleave = message.find('\r\n\r\n')
  266. headers, article = message[:cleave], message[cleave + 4:]
  267. a = Article(headers, article)
  268. groups = a.getHeader('Newsgroups').split()
  269. xref = []
  270. # Check moderated status
  271. moderators = self.getModerators(groups)
  272. if moderators and not a.getHeader('Approved'):
  273. return self.notifyModerators(moderators, a)
  274. for group in groups:
  275. if group in self.db:
  276. if len(self.db[group].keys()):
  277. index = max(self.db[group].keys()) + 1
  278. else:
  279. index = 1
  280. xref.append((group, str(index)))
  281. self.db[group][index] = a
  282. if len(xref) == 0:
  283. return defer.fail(None)
  284. a.putHeader('Xref', '%s %s' % (
  285. socket.gethostname().split()[0],
  286. ''.join(map(lambda x: ':'.join(x), xref))
  287. ))
  288. self.flush()
  289. return defer.succeed(None)
  290. def overviewRequest(self):
  291. return defer.succeed(OVERVIEW_FMT)
  292. def xoverRequest(self, group, low, high):
  293. if group not in self.db:
  294. return defer.succeed([])
  295. r = []
  296. for i in self.db[group].keys():
  297. if (low is None or i >= low) and (high is None or i <= high):
  298. r.append([str(i)] + self.db[group][i].overview())
  299. return defer.succeed(r)
  300. def xhdrRequest(self, group, low, high, header):
  301. if group not in self.db:
  302. return defer.succeed([])
  303. r = []
  304. for i in self.db[group].keys():
  305. if low is None or i >= low and high is None or i <= high:
  306. r.append((i, self.db[group][i].getHeader(header)))
  307. return defer.succeed(r)
  308. def listGroupRequest(self, group):
  309. if group in self.db:
  310. return defer.succeed((group, self.db[group].keys()))
  311. else:
  312. return defer.fail(None)
  313. def groupRequest(self, group):
  314. if group in self.db:
  315. if len(self.db[group].keys()):
  316. num = len(self.db[group].keys())
  317. low = min(self.db[group].keys())
  318. high = max(self.db[group].keys())
  319. else:
  320. num = low = high = 0
  321. flags = 'y'
  322. return defer.succeed((group, num, high, low, flags))
  323. else:
  324. return defer.fail(ERR_NOGROUP)
  325. def articleExistsRequest(self, id):
  326. for group in self.db['groups']:
  327. for a in self.db[group].values():
  328. if a.getHeader('Message-ID') == id:
  329. return defer.succeed(1)
  330. return defer.succeed(0)
  331. def articleRequest(self, group, index, id = None):
  332. if id is not None:
  333. raise NotImplementedError
  334. if group in self.db:
  335. if index in self.db[group]:
  336. a = self.db[group][index]
  337. return defer.succeed((
  338. index,
  339. a.getHeader('Message-ID'),
  340. StringIO.StringIO(a.textHeaders() + '\r\n' + a.body)
  341. ))
  342. else:
  343. return defer.fail(ERR_NOARTICLE)
  344. else:
  345. return defer.fail(ERR_NOGROUP)
  346. def headRequest(self, group, index):
  347. if group in self.db:
  348. if index in self.db[group]:
  349. a = self.db[group][index]
  350. return defer.succeed((index, a.getHeader('Message-ID'), a.textHeaders()))
  351. else:
  352. return defer.fail(ERR_NOARTICLE)
  353. else:
  354. return defer.fail(ERR_NOGROUP)
  355. def bodyRequest(self, group, index):
  356. if group in self.db:
  357. if index in self.db[group]:
  358. a = self.db[group][index]
  359. return defer.succeed((index, a.getHeader('Message-ID'), StringIO.StringIO(a.body)))
  360. else:
  361. return defer.fail(ERR_NOARTICLE)
  362. else:
  363. return defer.fail(ERR_NOGROUP)
  364. def flush(self):
  365. with open(self.datafile, 'w') as f:
  366. pickle.dump(self.db, f)
  367. def load(self, filename, groups = None, moderators = ()):
  368. if filename in PickleStorage.sharedDBs:
  369. self.db = PickleStorage.sharedDBs[filename]
  370. else:
  371. try:
  372. with open(filename) as f:
  373. self.db = pickle.load(f)
  374. PickleStorage.sharedDBs[filename] = self.db
  375. except IOError:
  376. self.db = PickleStorage.sharedDBs[filename] = {}
  377. self.db['groups'] = groups
  378. if groups is not None:
  379. for i in groups:
  380. self.db[i] = {}
  381. self.db['moderators'] = dict(moderators)
  382. self.flush()
  383. class Group:
  384. name = None
  385. flags = ''
  386. minArticle = 1
  387. maxArticle = 0
  388. articles = None
  389. def __init__(self, name, flags = 'y'):
  390. self.name = name
  391. self.flags = flags
  392. self.articles = {}
  393. @implementer(INewsStorage)
  394. class NewsShelf(_ModerationMixin):
  395. """
  396. A NewStorage implementation using Twisted's dirdbm persistence module.
  397. """
  398. def __init__(self, mailhost, path, sender=None):
  399. """
  400. @param mailhost: A C{str} giving the mail exchange host which will
  401. accept moderation emails from this server. Must accept emails
  402. destined for any address specified as a moderator.
  403. @param sender: A C{str} giving the address which will be used as the
  404. sender of any moderation email generated by this server.
  405. """
  406. self.path = path
  407. self._mailhost = self.mailhost = mailhost
  408. self._sender = sender
  409. if not os.path.exists(path):
  410. os.mkdir(path)
  411. self.dbm = dirdbm.Shelf(os.path.join(path, "newsshelf"))
  412. if not len(self.dbm.keys()):
  413. self.initialize()
  414. def initialize(self):
  415. # A dictionary of group name/Group instance items
  416. self.dbm['groups'] = dirdbm.Shelf(os.path.join(self.path, 'groups'))
  417. # A dictionary of group name/email address
  418. self.dbm['moderators'] = dirdbm.Shelf(os.path.join(self.path, 'moderators'))
  419. # A list of group names
  420. self.dbm['subscriptions'] = []
  421. # A dictionary of MessageID strings/xref lists
  422. self.dbm['Message-IDs'] = dirdbm.Shelf(os.path.join(self.path, 'Message-IDs'))
  423. def addGroup(self, name, flags):
  424. self.dbm['groups'][name] = Group(name, flags)
  425. def addSubscription(self, name):
  426. self.dbm['subscriptions'] = self.dbm['subscriptions'] + [name]
  427. def addModerator(self, group, email):
  428. self.dbm['moderators'][group] = email
  429. def listRequest(self):
  430. result = []
  431. for g in self.dbm['groups'].values():
  432. result.append((g.name, g.maxArticle, g.minArticle, g.flags))
  433. return defer.succeed(result)
  434. def subscriptionRequest(self):
  435. return defer.succeed(self.dbm['subscriptions'])
  436. def getModerator(self, groups):
  437. # first see if any groups are moderated. if so, nothing gets posted,
  438. # but the whole messages gets forwarded to the moderator address
  439. for group in groups:
  440. try:
  441. return self.dbm['moderators'][group]
  442. except KeyError:
  443. pass
  444. return None
  445. def notifyModerator(self, moderator, article):
  446. """
  447. Notify a single moderator about an article requiring moderation.
  448. C{notifyModerators} should be preferred.
  449. """
  450. return self.notifyModerators([moderator], article)
  451. def postRequest(self, message):
  452. cleave = message.find('\r\n\r\n')
  453. headers, article = message[:cleave], message[cleave + 4:]
  454. article = Article(headers, article)
  455. groups = article.getHeader('Newsgroups').split()
  456. xref = []
  457. # Check for moderated status
  458. moderator = self.getModerator(groups)
  459. if moderator and not article.getHeader('Approved'):
  460. return self.notifyModerators([moderator], article)
  461. for group in groups:
  462. try:
  463. g = self.dbm['groups'][group]
  464. except KeyError:
  465. pass
  466. else:
  467. index = g.maxArticle + 1
  468. g.maxArticle += 1
  469. g.articles[index] = article
  470. xref.append((group, str(index)))
  471. self.dbm['groups'][group] = g
  472. if not xref:
  473. return defer.fail(NewsServerError("No groups carried: " + ' '.join(groups)))
  474. article.putHeader('Xref', '%s %s' % (socket.gethostname().split()[0], ' '.join(map(lambda x: ':'.join(x), xref))))
  475. self.dbm['Message-IDs'][article.getHeader('Message-ID')] = xref
  476. return defer.succeed(None)
  477. def overviewRequest(self):
  478. return defer.succeed(OVERVIEW_FMT)
  479. def xoverRequest(self, group, low, high):
  480. if group not in self.dbm['groups']:
  481. return defer.succeed([])
  482. if low is None:
  483. low = 0
  484. if high is None:
  485. high = self.dbm['groups'][group].maxArticle
  486. r = []
  487. for i in range(low, high + 1):
  488. if i in self.dbm['groups'][group].articles:
  489. r.append([str(i)] + self.dbm['groups'][group].articles[i].overview())
  490. return defer.succeed(r)
  491. def xhdrRequest(self, group, low, high, header):
  492. if group not in self.dbm['groups']:
  493. return defer.succeed([])
  494. if low is None:
  495. low = 0
  496. if high is None:
  497. high = self.dbm['groups'][group].maxArticle
  498. r = []
  499. for i in range(low, high + 1):
  500. if i in self.dbm['groups'][group].articles:
  501. r.append((i, self.dbm['groups'][group].articles[i].getHeader(header)))
  502. return defer.succeed(r)
  503. def listGroupRequest(self, group):
  504. if group in self.dbm['groups']:
  505. return defer.succeed((group, self.dbm['groups'][group].articles.keys()))
  506. return defer.fail(NewsServerError("No such group: " + group))
  507. def groupRequest(self, group):
  508. try:
  509. g = self.dbm['groups'][group]
  510. except KeyError:
  511. return defer.fail(NewsServerError("No such group: " + group))
  512. else:
  513. flags = g.flags
  514. low = g.minArticle
  515. high = g.maxArticle
  516. num = high - low + 1
  517. return defer.succeed((group, num, high, low, flags))
  518. def articleExistsRequest(self, id):
  519. return defer.succeed(id in self.dbm['Message-IDs'])
  520. def articleRequest(self, group, index, id = None):
  521. if id is not None:
  522. try:
  523. xref = self.dbm['Message-IDs'][id]
  524. except KeyError:
  525. return defer.fail(NewsServerError("No such article: " + id))
  526. else:
  527. group, index = xref[0]
  528. index = int(index)
  529. try:
  530. a = self.dbm['groups'][group].articles[index]
  531. except KeyError:
  532. return defer.fail(NewsServerError("No such group: " + group))
  533. else:
  534. return defer.succeed((
  535. index,
  536. a.getHeader('Message-ID'),
  537. StringIO.StringIO(a.textHeaders() + '\r\n' + a.body)
  538. ))
  539. def headRequest(self, group, index, id = None):
  540. if id is not None:
  541. try:
  542. xref = self.dbm['Message-IDs'][id]
  543. except KeyError:
  544. return defer.fail(NewsServerError("No such article: " + id))
  545. else:
  546. group, index = xref[0]
  547. index = int(index)
  548. try:
  549. a = self.dbm['groups'][group].articles[index]
  550. except KeyError:
  551. return defer.fail(NewsServerError("No such group: " + group))
  552. else:
  553. return defer.succeed((index, a.getHeader('Message-ID'), a.textHeaders()))
  554. def bodyRequest(self, group, index, id = None):
  555. if id is not None:
  556. try:
  557. xref = self.dbm['Message-IDs'][id]
  558. except KeyError:
  559. return defer.fail(NewsServerError("No such article: " + id))
  560. else:
  561. group, index = xref[0]
  562. index = int(index)
  563. try:
  564. a = self.dbm['groups'][group].articles[index]
  565. except KeyError:
  566. return defer.fail(NewsServerError("No such group: " + group))
  567. else:
  568. return defer.succeed((index, a.getHeader('Message-ID'), StringIO.StringIO(a.body)))
  569. @implementer(INewsStorage)
  570. class NewsStorageAugmentation:
  571. """
  572. A NewsStorage implementation using Twisted's asynchronous DB-API
  573. """
  574. schema = """
  575. CREATE TABLE groups (
  576. group_id SERIAL,
  577. name VARCHAR(80) NOT NULL,
  578. flags INTEGER DEFAULT 0 NOT NULL
  579. );
  580. CREATE UNIQUE INDEX group_id_index ON groups (group_id);
  581. CREATE UNIQUE INDEX name_id_index ON groups (name);
  582. CREATE TABLE articles (
  583. article_id SERIAL,
  584. message_id TEXT,
  585. header TEXT,
  586. body TEXT
  587. );
  588. CREATE UNIQUE INDEX article_id_index ON articles (article_id);
  589. CREATE UNIQUE INDEX article_message_index ON articles (message_id);
  590. CREATE TABLE postings (
  591. group_id INTEGER,
  592. article_id INTEGER,
  593. article_index INTEGER NOT NULL
  594. );
  595. CREATE UNIQUE INDEX posting_article_index ON postings (article_id);
  596. CREATE TABLE subscriptions (
  597. group_id INTEGER
  598. );
  599. CREATE TABLE overview (
  600. header TEXT
  601. );
  602. """
  603. def __init__(self, info):
  604. self.info = info
  605. self.dbpool = adbapi.ConnectionPool(**self.info)
  606. def __setstate__(self, state):
  607. self.__dict__ = state
  608. self.info['password'] = getpass.getpass('Database password for %s: ' % (self.info['user'],))
  609. self.dbpool = adbapi.ConnectionPool(**self.info)
  610. del self.info['password']
  611. def listRequest(self):
  612. # COALESCE may not be totally portable
  613. # it is shorthand for
  614. # CASE WHEN (first parameter) IS NOT NULL then (first parameter) ELSE (second parameter) END
  615. sql = """
  616. SELECT groups.name,
  617. COALESCE(MAX(postings.article_index), 0),
  618. COALESCE(MIN(postings.article_index), 0),
  619. groups.flags
  620. FROM groups LEFT OUTER JOIN postings
  621. ON postings.group_id = groups.group_id
  622. GROUP BY groups.name, groups.flags
  623. ORDER BY groups.name
  624. """
  625. return self.dbpool.runQuery(sql)
  626. def subscriptionRequest(self):
  627. sql = """
  628. SELECT groups.name FROM groups,subscriptions WHERE groups.group_id = subscriptions.group_id
  629. """
  630. return self.dbpool.runQuery(sql)
  631. def postRequest(self, message):
  632. cleave = message.find('\r\n\r\n')
  633. headers, article = message[:cleave], message[cleave + 4:]
  634. article = Article(headers, article)
  635. return self.dbpool.runInteraction(self._doPost, article)
  636. def _doPost(self, transaction, article):
  637. # Get the group ids
  638. groups = article.getHeader('Newsgroups').split()
  639. if not len(groups):
  640. raise NNTPError('Missing Newsgroups header')
  641. sql = """
  642. SELECT name, group_id FROM groups
  643. WHERE name IN (%s)
  644. """ % (', '.join([("'%s'" % (adbapi.safe(group),)) for group in groups]),)
  645. transaction.execute(sql)
  646. result = transaction.fetchall()
  647. # No relevant groups, bye bye!
  648. if not len(result):
  649. raise NNTPError('None of groups in Newsgroup header carried')
  650. # Got some groups, now find the indices this article will have in each
  651. sql = """
  652. SELECT groups.group_id, COALESCE(MAX(postings.article_index), 0) + 1
  653. FROM groups LEFT OUTER JOIN postings
  654. ON postings.group_id = groups.group_id
  655. WHERE groups.group_id IN (%s)
  656. GROUP BY groups.group_id
  657. """ % (', '.join([("%d" % (id,)) for (group, id) in result]),)
  658. transaction.execute(sql)
  659. indices = transaction.fetchall()
  660. if not len(indices):
  661. raise NNTPError('Internal server error - no indices found')
  662. # Associate indices with group names
  663. gidToName = dict([(b, a) for (a, b) in result])
  664. gidToIndex = dict(indices)
  665. nameIndex = []
  666. for i in gidToName:
  667. nameIndex.append((gidToName[i], gidToIndex[i]))
  668. # Build xrefs
  669. xrefs = socket.gethostname().split()[0]
  670. xrefs = xrefs + ' ' + ' '.join([('%s:%d' % (group, id)) for (group, id) in nameIndex])
  671. article.putHeader('Xref', xrefs)
  672. # Hey! The article is ready to be posted! God damn f'in finally.
  673. sql = """
  674. INSERT INTO articles (message_id, header, body)
  675. VALUES ('%s', '%s', '%s')
  676. """ % (
  677. adbapi.safe(article.getHeader('Message-ID')),
  678. adbapi.safe(article.textHeaders()),
  679. adbapi.safe(article.body)
  680. )
  681. transaction.execute(sql)
  682. # Now update the posting to reflect the groups to which this belongs
  683. for gid in gidToName:
  684. sql = """
  685. INSERT INTO postings (group_id, article_id, article_index)
  686. VALUES (%d, (SELECT last_value FROM articles_article_id_seq), %d)
  687. """ % (gid, gidToIndex[gid])
  688. transaction.execute(sql)
  689. return len(nameIndex)
  690. def overviewRequest(self):
  691. sql = """
  692. SELECT header FROM overview
  693. """
  694. return self.dbpool.runQuery(sql).addCallback(lambda result: [header[0] for header in result])
  695. def xoverRequest(self, group, low, high):
  696. sql = """
  697. SELECT postings.article_index, articles.header
  698. FROM articles,postings,groups
  699. WHERE postings.group_id = groups.group_id
  700. AND groups.name = '%s'
  701. AND postings.article_id = articles.article_id
  702. %s
  703. %s
  704. """ % (
  705. adbapi.safe(group),
  706. low is not None and "AND postings.article_index >= %d" % (low,) or "",
  707. high is not None and "AND postings.article_index <= %d" % (high,) or ""
  708. )
  709. return self.dbpool.runQuery(sql).addCallback(
  710. lambda results: [
  711. [id] + Article(header, None).overview() for (id, header) in results
  712. ]
  713. )
  714. def xhdrRequest(self, group, low, high, header):
  715. sql = """
  716. SELECT articles.header
  717. FROM groups,postings,articles
  718. WHERE groups.name = '%s' AND postings.group_id = groups.group_id
  719. AND postings.article_index >= %d
  720. AND postings.article_index <= %d
  721. """ % (adbapi.safe(group), low, high)
  722. return self.dbpool.runQuery(sql).addCallback(
  723. lambda results: [
  724. (i, Article(h, None).getHeader(h)) for (i, h) in results
  725. ]
  726. )
  727. def listGroupRequest(self, group):
  728. sql = """
  729. SELECT postings.article_index FROM postings,groups
  730. WHERE postings.group_id = groups.group_id
  731. AND groups.name = '%s'
  732. """ % (adbapi.safe(group),)
  733. return self.dbpool.runQuery(sql).addCallback(
  734. lambda results, group = group: (group, [res[0] for res in results])
  735. )
  736. def groupRequest(self, group):
  737. sql = """
  738. SELECT groups.name,
  739. COUNT(postings.article_index),
  740. COALESCE(MAX(postings.article_index), 0),
  741. COALESCE(MIN(postings.article_index), 0),
  742. groups.flags
  743. FROM groups LEFT OUTER JOIN postings
  744. ON postings.group_id = groups.group_id
  745. WHERE groups.name = '%s'
  746. GROUP BY groups.name, groups.flags
  747. """ % (adbapi.safe(group),)
  748. return self.dbpool.runQuery(sql).addCallback(
  749. lambda results: tuple(results[0])
  750. )
  751. def articleExistsRequest(self, id):
  752. sql = """
  753. SELECT COUNT(message_id) FROM articles
  754. WHERE message_id = '%s'
  755. """ % (adbapi.safe(id),)
  756. return self.dbpool.runQuery(sql).addCallback(
  757. lambda result: bool(result[0][0])
  758. )
  759. def articleRequest(self, group, index, id = None):
  760. if id is not None:
  761. sql = """
  762. SELECT postings.article_index, articles.message_id, articles.header, articles.body
  763. FROM groups,postings LEFT OUTER JOIN articles
  764. ON articles.message_id = '%s'
  765. WHERE groups.name = '%s'
  766. AND groups.group_id = postings.group_id
  767. """ % (adbapi.safe(id), adbapi.safe(group))
  768. else:
  769. sql = """
  770. SELECT postings.article_index, articles.message_id, articles.header, articles.body
  771. FROM groups,articles LEFT OUTER JOIN postings
  772. ON postings.article_id = articles.article_id
  773. WHERE postings.article_index = %d
  774. AND postings.group_id = groups.group_id
  775. AND groups.name = '%s'
  776. """ % (index, adbapi.safe(group))
  777. return self.dbpool.runQuery(sql).addCallback(
  778. lambda result: (
  779. result[0][0],
  780. result[0][1],
  781. StringIO.StringIO(result[0][2] + '\r\n' + result[0][3])
  782. )
  783. )
  784. def headRequest(self, group, index):
  785. sql = """
  786. SELECT postings.article_index, articles.message_id, articles.header
  787. FROM groups,articles LEFT OUTER JOIN postings
  788. ON postings.article_id = articles.article_id
  789. WHERE postings.article_index = %d
  790. AND postings.group_id = groups.group_id
  791. AND groups.name = '%s'
  792. """ % (index, adbapi.safe(group))
  793. return self.dbpool.runQuery(sql).addCallback(lambda result: result[0])
  794. def bodyRequest(self, group, index):
  795. sql = """
  796. SELECT postings.article_index, articles.message_id, articles.body
  797. FROM groups,articles LEFT OUTER JOIN postings
  798. ON postings.article_id = articles.article_id
  799. WHERE postings.article_index = %d
  800. AND postings.group_id = groups.group_id
  801. AND groups.name = '%s'
  802. """ % (index, adbapi.safe(group))
  803. return self.dbpool.runQuery(sql).addCallback(
  804. lambda result: result[0]
  805. ).addCallback(
  806. # result is a tuple of (index, id, body)
  807. lambda result: (result[0], result[1], StringIO.StringIO(result[2]))
  808. )
  809. ####
  810. #### XXX - make these static methods some day
  811. ####
  812. def makeGroupSQL(groups):
  813. res = ''
  814. for g in groups:
  815. res = res + """\n INSERT INTO groups (name) VALUES ('%s');\n""" % (adbapi.safe(g),)
  816. return res
  817. def makeOverviewSQL():
  818. res = ''
  819. for o in OVERVIEW_FMT:
  820. res = res + """\n INSERT INTO overview (header) VALUES ('%s');\n""" % (adbapi.safe(o),)
  821. return res