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