1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2011, 2014, 2020 kaliko <kaliko@azylum.org>
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.
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.
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/>.
22 from urllib.error import URLError
23 from urllib.parse import urlparse
25 from feedparser import parse as feed_parse
27 from .plugin import Plugin, botcmd
39 def html_escape(text):
40 """Produce entities within text."""
41 return ''.join(html_escape_table.get(c, c) for c in text)
44 def strtm_to_dtm(struc_time):
45 return datetime.datetime(*struc_time[:6])
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
54 self.last_check = datetime.datetime.utcnow()
56 self.thread_killed = False
58 def _update_cache(self, feed, parsed):
59 self.seen[feed].update({'ids': {p.id for p in parsed.entries} or {}})
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}})
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'])
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__())
81 if parsed_feed.status == 304:
82 self.plugin.log.debug('Got 304 not modified')
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).',
90 if not self.seen.setdefault(feed):
91 # Fills with post id when first started (prevent from posting all
93 self.seen[feed] = {'cache': None}
94 self._update_cache(feed, parsed_feed)
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'))
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
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)
115 # Updating self.seen, entries and cache headers
116 self._update_cache(feed, parsed_feed)
118 self.plugin.send(self.plugin.bot.room,
119 {'mhtml': '<br />'.join(xhtml), 'mbody': '\n'.join(text)},
123 while not self.thread_killed:
124 self.plugin.log.debug('feeds check')
125 for feed in self.feeds_list:
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)):
139 if self.thread_killed:
146 Feeds plugin depends on external module: **feedparser**
149 #: Time between feeds check
151 #: Default feeds to monitor
153 'https://www.debian.org/security/dsa',
154 'https://www.debian.org/News/news',
156 'https://tracker.debian.org/pkg/prosody/rss',
157 'https://tracker.debian.org/pkg/ejabberd/rss',
159 'https://planet.debian.org/atom.xml',
162 def __init__(self, bot):
163 Plugin.__init__(self, bot)
164 self.last_check = None
165 self.th_mon = FeedMonitor(self)
169 self.th_mon.thread_killed = True
172 def feeds(self, rcv, args):
173 """Monitors debian project related feeds.
175 * ``!feeds`` : registred feeds list
176 * ``!feeds last`` : last check time"""
178 date = '{:%Y-%m-%d %H:%M} (utc)'.format(self.th_mon.last_check)
179 self.reply(rcv, f'Last feeds check: {date}')
181 html = ['<a href="{0}">{1}</a>'.format(
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)}