]> kaliko git repositories - sid.git/blob - sid/feeds.py
feeds: catch ConnectionError to avoid killing thread
[sid.git] / sid / feeds.py
1 # -*- coding: utf-8 -*-
2
3 # Copyright (C) 2011, 2014, 2020 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 urllib.error import URLError
23
24 from feedparser import parse as feed_parse
25
26 from .plugin import Plugin, botcmd
27
28
29 html_escape_table = {
30         "&": "&amp;",
31         '"': "&quot;",
32         "'": "&apos;",
33         ">": "&gt;",
34         "<": "&lt;",
35         }
36
37
38 def html_escape(text):
39     """Produce entities within text."""
40     return ''.join(html_escape_table.get(c, c) for c in text)
41
42
43 def strtm_to_dtm(struc_time):
44     return datetime.datetime(*struc_time[:6])
45
46
47 class FeedMonitor(threading.Thread):
48     def __init__(self, plugin):
49         threading.Thread.__init__(self)
50         self.feeds_list = plugin.FEEDS
51         self.tempo = plugin.TEMPO
52         self.plugin = plugin
53         self.last_check = datetime.datetime.utcnow()
54         self.seen = dict()
55         self.thread_killed = False
56
57     def _update_cache(self, feed, parsed):
58         self.seen[feed].update({'ids': {p.id for p in parsed.entries} or {}})
59         # Common HTTP caching
60         if parsed.get('etag', False):
61             self.seen[feed].update({'cache': {'etag': parsed.etag}})
62         if parsed.get('modified', False):
63             self.seen[feed].update({'cache': {'modified': parsed.modified}})
64
65     def new_posts(self, feed):
66         """Send new posts in feed"""
67         self.plugin.log.debug('feed:     : "%s"', feed)
68         if self.seen.get(feed) and self.seen.get(feed).get('cache'):
69             parsed_feed = feed_parse(feed, **self.seen[feed]['cache'])
70         else:
71             if self.seen.get(feed):
72                 self.plugin.log.debug('No cache headers set (etag/modified)')
73             parsed_feed = feed_parse(feed)
74         # Cannot resolve address
75         if 'status' not in parsed_feed:
76             self.plugin.log.error('Error from "%s": %s.',
77                                   feed, parsed_feed.bozo_exception.__repr__())
78             return
79         # http caching
80         if parsed_feed.status == 304:
81             self.plugin.log.debug('Got 304 not modified')
82             return
83         # unusual return http code
84         if parsed_feed.status != 200:
85             self.plugin.log.warning(
86                 'Got code %(status)d from "%(href)s" (please update).',
87                 parsed_feed)
88             return
89         if not self.seen.setdefault(feed):
90             # Fills with post id when first started (prevent from posting all
91             # entries at startup)
92             self.seen[feed] = {'cache': None}
93             self._update_cache(feed, parsed_feed)
94             return
95         title = '"%s":' % parsed_feed.feed.get('title', 'n/a')
96         xtitle = '<strong>%s</strong>:' % html_escape(
97             parsed_feed.feed.get('title', 'n/a'))
98         text = [title]
99         xhtml = [xtitle]
100
101         # Detecting new post
102         entries = {p.id for p in parsed_feed.entries}
103         seen_ids = self.seen.get(feed).get('ids')
104         new_entries = [p for p in parsed_feed.entries
105                        if p.id in entries - seen_ids]
106         for post in new_entries:
107             self.plugin.log.info(post.title)
108             body = '%(title)s %(link)s' % post
109             text.append(body)
110             xpost = {'title': html_escape(post.get('title', 'n/a'))}
111             xpost['link'] = html_escape(post.get('link',))
112             xbody = '<a href="{link}">{title}</a>'.format(**xpost)
113             xhtml.append(xbody)
114         # Updating self.seen, entries and cache headers
115         self._update_cache(feed, parsed_feed)
116         if len(text) > 1:
117             self.plugin.send(self.plugin.bot.room,
118                     {'mhtml': '<br />'.join(xhtml), 'mbody': '\n'.join(text)},
119                     mtype='groupchat')
120
121     def run(self):
122         while not self.thread_killed:
123             self.plugin.log.debug('feeds check')
124             for feed in self.feeds_list:
125                 try:
126                     self.new_posts(feed)
127                 except ConnectionError as err:  # Non fatal exception
128                     self.plugin.log.error(f'connection error on {feed}: {err}')
129                 except URLError as err:  # Non fatal exception
130                     self.plugin.log.error(f'error for {feed}: {err.reason}')
131                 except Exception as err:  # Unknown execption, killing thread anyway
132                     self.plugin.log.error('feeds thread crashed: %s', err)
133                     self.plugin.log.error(''.join(traceback.format_exc()))
134                     self.thread_killed = True
135             self.last_check = datetime.datetime.utcnow()
136             for _ in list(range(self.tempo)):
137                 time.sleep(1)
138                 if self.thread_killed:
139                     return
140
141
142 class Feeds(Plugin):
143     """
144     .. note::
145       Feeds plugin depends on external module: **feedparser**
146     """
147
148     #: Time between feeds check
149     TEMPO = 60
150     #: Default feeds to monitor
151     FEEDS = [
152         'https://www.debian.org/security/dsa',
153         'https://www.debian.org/News/news',
154         # Some packages
155         'https://tracker.debian.org/pkg/prosody/rss',
156         'https://tracker.debian.org/pkg/ejabberd/rss',
157         # Misc
158         'https://planet.debian.org/atom.xml',
159         ]
160
161     def __init__(self, bot):
162         Plugin.__init__(self, bot)
163         self.last_check = None
164         self.th_mon = FeedMonitor(self)
165         self.th_mon.start()
166
167     def shutdown(self):
168         self.th_mon.thread_killed = True
169
170     @botcmd
171     def feeds(self, rcv, args):
172         """Monitors debian project related feeds.
173
174         * ``!feeds``      : registred feeds list
175         * ``!feeds last`` : last check time"""
176         if 'last' in args:
177             self.reply(rcv, 'Last feeds check: %s' % self.th_mon.last_check)
178             return
179         html = ['<a href="{0}">{1}</a>'.format(html_escape(u),
180                                                html_escape(u[7:])
181                                               ) for u in Feeds.FEEDS]
182         msg = {'mbody': 'Feeds:\n' + '\n'.join(Feeds.FEEDS),
183                'mhtml': 'Feeds:<br />' + '<br />'.join(html)}
184         self.reply(rcv, msg)