]> kaliko git repositories - sid.git/blob - sid/feeds.py
feeds: use proper http caching
[sid.git] / sid / feeds.py
1 # -*- coding: utf-8 -*-
2
3 # Copyright (C) 2011, 2014 kaliko <kaliko@azylum.org>
4
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, version 3 only.
8
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 # GNU General Public License for more details.
13
14 # You should have received a copy of the GNU General Public License
15 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
17 import datetime
18 import threading
19 import time
20 import traceback
21
22 from feedparser import parse as feed_parse
23
24 from .plugin import Plugin, botcmd
25
26
27 html_escape_table = {
28         "&": "&amp;",
29         '"': "&quot;",
30         "'": "&apos;",
31         ">": "&gt;",
32         "<": "&lt;",
33         }
34
35
36 def html_escape(text):
37     """Produce entities within text."""
38     return ''.join(html_escape_table.get(c, c) for c in text)
39
40
41 def strtm_to_dtm(struc_time):
42     return datetime.datetime(*struc_time[:6])
43
44
45 class FeedMonitor(threading.Thread):
46     def __init__(self, plugin):
47         threading.Thread.__init__(self)
48         self.feeds_list = plugin.FEEDS
49         self.tempo = plugin.TEMPO
50         self.plugin = plugin
51         self.last_check = datetime.datetime.utcnow()
52         self.seen = dict()
53         self.thread_killed = False
54
55     def _update_cache(self, feed, parsed):
56         self.seen[feed].update({'ids': {p.id for p in parsed.entries} or {}})
57         # Common HTTP caching
58         if parsed.get('etag', False):
59             self.seen[feed].update({'cache': {'etag': parsed.etag}})
60         if parsed.get('modified', False):
61             self.seen[feed].update({'cache': {'modified': parsed.modified}})
62
63     def new_posts(self, feed):
64         """Send new posts in feed"""
65         self.plugin.log.debug('feed:     : "%s"', feed)
66         if self.seen.get(feed) and self.seen.get(feed).get('cache'):
67             parsed_feed = feed_parse(feed, **self.seen[feed]['cache'])
68         else:
69             if self.seen.get(feed):
70                 self.plugin.log.debug('No cache headers set (etag/modified)')
71             parsed_feed = feed_parse(feed)
72         # Cannot resolve address
73         if 'status' not in parsed_feed:
74             self.plugin.log.error('Error from "%s": %s.',
75                                   feed, parsed_feed.bozo_exception.__repr__())
76             return
77         # http caching
78         if parsed_feed.status == 304:
79             self.plugin.log.debug('Got 304 not modified')
80             return
81         # unusual return http code
82         if parsed_feed.status != 200:
83             self.plugin.log.warning(
84                 'Got code %(status)d from "%(href)s" (please update).',
85                 parsed_feed)
86             return
87         if not self.seen.setdefault(feed):
88             # Fills with post id when first started (prevent from posting all
89             # entries at startup)
90             self.seen[feed] = {'cache': None}
91             self._update_cache(feed, parsed_feed)
92             return
93         title = '"%s":' % parsed_feed.feed.get('title', 'n/a')
94         xtitle = '<strong>%s</strong>:' % html_escape(
95             parsed_feed.feed.get('title', 'n/a'))
96         text = [title]
97         xhtml = [xtitle]
98
99         # Detecting new post
100         entries = {p.id for p in parsed_feed.entries}
101         seen_ids = self.seen.get(feed).get('ids')
102         new_entries = [p for p in parsed_feed.entries
103                        if p.id in entries - seen_ids]
104         for post in new_entries:
105             self.plugin.log.info(post.title)
106             body = '%(title)s %(link)s' % post
107             text.append(body)
108             xpost = {'title': html_escape(post.get('title', 'n/a'))}
109             xpost['link'] = html_escape(post.get('link',))
110             xbody = '<a href="{link}">{title}</a>'.format(**xpost)
111             xhtml.append(xbody)
112         # Updating self.seen, entries and cache headers
113         self._update_cache(feed, parsed_feed)
114         if len(text) > 1:
115             self.plugin.send(self.plugin.bot.room,
116                     {'mhtml': '<br />'.join(xhtml), 'mbody': '\n'.join(text)},
117                     mtype='groupchat')
118
119     def run(self):
120         while not self.thread_killed:
121             self.plugin.log.debug('feeds check')
122             for feed in self.feeds_list:
123                 try:
124                     self.new_posts(feed)
125                 except Exception as err:
126                     self.plugin.log.error('feeds thread crashed: %s', err)
127                     self.plugin.log.error(''.join(traceback.format_exc()))
128                     self.thread_killed = True
129             self.last_check = datetime.datetime.utcnow()
130             for _ in list(range(self.tempo)):
131                 time.sleep(1)
132                 if self.thread_killed:
133                     return
134
135
136 class Feeds(Plugin):
137     TEMPO = 60
138     FEEDS = [
139         'https://www.debian.org/security/dsa',
140         'https://www.debian.org/News/news',
141         # Some packages
142         'https://tracker.debian.org/pkg/prosody/rss',
143         'https://tracker.debian.org/pkg/ejabberd/rss',
144         # Misc
145         'https://planet.debian.org/atom.xml',
146         ]
147
148     def __init__(self, bot):
149         Plugin.__init__(self, bot)
150         self.last_check = None
151         self.th_mon = FeedMonitor(self)
152         self.th_mon.start()
153
154     def shutdown(self):
155         self.th_mon.thread_killed = True
156
157     @botcmd
158     def feeds(self, rcv, args):
159         """feeds monitors debian project related feeds.
160         !feeds : registred feeds list
161         !feeds last : last check time"""
162         if 'last' in args:
163             self.reply(rcv, 'Last feeds check: %s' % self.th_mon.last_check)
164             return
165         html = ['<a href="{0}">{1}</a>'.format(html_escape(u),
166                                                html_escape(u[7:])
167                                               ) for u in Feeds.FEEDS]
168         msg = {'mbody': 'Feeds:\n' + '\n'.join(Feeds.FEEDS),
169                'mhtml': 'Feeds:<br />' + '<br />'.join(html)}
170         self.reply(rcv, msg)