1 # -*- coding: utf-8 -*-
2 # SPDX-FileCopyrightText: 2011, 2014, 2020 kaliko <kaliko@azylum.org>
3 # SPDX-License-Identifier: GPL-3.0-or-later
10 from urllib.error import URLError
11 from urllib.parse import urlparse
13 from feedparser import parse as feed_parse
15 from .plugin import Plugin, botcmd
27 def html_escape(text):
28 """Produce entities within text."""
29 return ''.join(html_escape_table.get(c, c) for c in text)
32 def strtm_to_dtm(struc_time):
33 return datetime.datetime(*struc_time[:6])
36 class FeedMonitor(threading.Thread):
37 def __init__(self, plugin):
38 threading.Thread.__init__(self)
39 self.feeds_list = plugin.FEEDS
40 self.tempo = plugin.TEMPO
42 self.last_check = datetime.datetime.utcnow()
44 self.thread_killed = False
46 def _update_cache(self, feed, parsed):
47 self.seen[feed].update({'ids': {p.id for p in parsed.entries} or {}})
49 if parsed.get('etag', False):
50 self.seen[feed].update({'cache': {'etag': parsed.etag}})
51 if parsed.get('modified', False):
52 self.seen[feed].update({'cache': {'modified': parsed.modified}})
54 def new_posts(self, feed):
55 """Send new posts in feed"""
56 self.plugin.log.debug('feed: : "%s"', feed)
57 if self.seen.get(feed) and self.seen.get(feed).get('cache'):
58 parsed_feed = feed_parse(feed, **self.seen[feed]['cache'])
60 if self.seen.get(feed):
61 self.plugin.log.debug('No cache headers set (etag/modified)')
62 parsed_feed = feed_parse(feed)
63 # Cannot resolve address
64 if 'status' not in parsed_feed:
65 self.plugin.log.error('Error from "%s": %s.',
66 feed, parsed_feed.bozo_exception.__repr__())
69 if parsed_feed.status == 304:
70 self.plugin.log.debug('Got 304 not modified')
72 # unusual return http code
73 if parsed_feed.status != 200:
74 self.plugin.log.warning(
75 'Got code %(status)d from "%(href)s" (please update).',
78 if not self.seen.setdefault(feed):
79 # Fills with post id when first started (prevent from posting all
81 self.seen[feed] = {'cache': None}
82 self._update_cache(feed, parsed_feed)
84 title = '"%s":' % parsed_feed.feed.get('title', 'n/a')
85 xtitle = '<strong>%s</strong>:' % html_escape(
86 parsed_feed.feed.get('title', 'n/a'))
91 entries = {p.id for p in parsed_feed.entries}
92 seen_ids = self.seen.get(feed).get('ids')
93 new_entries = [p for p in parsed_feed.entries
94 if p.id in entries - seen_ids]
95 for post in new_entries:
96 self.plugin.log.info(post.title)
97 body = '%(title)s %(link)s' % post
99 xpost = {'title': html_escape(post.get('title', 'n/a'))}
100 xpost['link'] = html_escape(post.get('link',))
101 xbody = '<a href="{link}">{title}</a>'.format(**xpost)
103 # Updating self.seen, entries and cache headers
104 self._update_cache(feed, parsed_feed)
106 self.plugin.send(self.plugin.bot.room,
107 {'mhtml': '<br />'.join(xhtml), 'mbody': '\n'.join(text)},
111 while not self.thread_killed:
112 self.plugin.log.debug('feeds check')
113 for feed in self.feeds_list:
116 except ConnectionError as err: # Non fatal exception
117 self.plugin.log.error('connection error on %s: %s', feed, err)
118 except URLError as err: # Non fatal exception
119 self.plugin.log.error('error for "%s": %s', feed, err.reason)
120 except Exception as err: # Unknown execption, killing thread anyway
121 self.plugin.log.error('feeds thread crashed: %s', err)
122 self.plugin.log.error(''.join(traceback.format_exc()))
123 self.thread_killed = True
124 self.last_check = datetime.datetime.utcnow()
125 for _ in list(range(self.tempo)):
127 if self.thread_killed:
134 Feeds plugin depends on external module: **feedparser**
137 #: Time between feeds check
139 #: Default feeds to monitor
141 'https://www.debian.org/security/dsa',
142 'https://www.debian.org/News/news',
144 'https://tracker.debian.org/pkg/prosody/rss',
145 'https://tracker.debian.org/pkg/ejabberd/rss',
147 'https://planet.debian.org/atom.xml',
150 def __init__(self, bot):
151 Plugin.__init__(self, bot)
152 self.last_check = None
153 self.th_mon = FeedMonitor(self)
157 self.th_mon.thread_killed = True
160 def feeds(self, rcv, args):
161 """Monitors debian project related feeds.
163 * ``!feeds`` : registred feeds list
164 * ``!feeds last`` : last check time"""
166 date = '{:%Y-%m-%d %H:%M} (utc)'.format(self.th_mon.last_check)
167 self.reply(rcv, f'Last feeds check: {date}')
169 html = ['<a href="{0}">{1}</a>'.format(
171 html_escape('{1}{2}'.format(*urlparse(u)))
172 ) for u in Feeds.FEEDS]
173 msg = {'mbody': 'Feeds:\n' + '\n'.join(Feeds.FEEDS),
174 'mhtml': 'Feeds:<br />' + '<br />'.join(html)}