1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2011, 2014 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 feedparser import parse as feed_parse
24 from .plugin import Plugin, botcmd
36 def html_escape(text):
37 """Produce entities within text."""
38 return ''.join(html_escape_table.get(c, c) for c in text)
41 def strtm_to_dtm(struc_time):
42 return datetime.datetime(*struc_time[:6])
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
51 self.last_check = datetime.datetime.utcnow()
53 self.thread_killed = False
55 def _update_cache(self, feed, parsed):
56 self.seen[feed].update({'ids': {p.id for p in parsed.entries} or {}})
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}})
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'])
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__())
78 if parsed_feed.status == 304:
79 self.plugin.log.debug('Got 304 not modified')
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).',
87 if not self.seen.setdefault(feed):
88 # Fills with post id when first started (prevent from posting all
90 self.seen[feed] = {'cache': None}
91 self._update_cache(feed, parsed_feed)
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'))
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
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)
112 # Updating self.seen, entries and cache headers
113 self._update_cache(feed, parsed_feed)
115 self.plugin.send(self.plugin.bot.room,
116 {'mhtml': '<br />'.join(xhtml), 'mbody': '\n'.join(text)},
120 while not self.thread_killed:
121 self.plugin.log.debug('feeds check')
122 for feed in self.feeds_list:
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)):
132 if self.thread_killed:
139 'https://www.debian.org/security/dsa',
140 'https://www.debian.org/News/news',
142 'https://tracker.debian.org/pkg/prosody/rss',
143 'https://tracker.debian.org/pkg/ejabberd/rss',
145 'https://planet.debian.org/atom.xml',
148 def __init__(self, bot):
149 Plugin.__init__(self, bot)
150 self.last_check = None
151 self.th_mon = FeedMonitor(self)
155 self.th_mon.thread_killed = True
158 def feeds(self, rcv, args):
159 """feeds monitors debian project related feeds.
160 !feeds : registred feeds list
161 !feeds last : last check time"""
163 self.reply(rcv, 'Last feeds check: %s' % self.th_mon.last_check)
165 html = ['<a href="{0}">{1}</a>'.format(html_escape(u),
167 ) for u in Feeds.FEEDS]
168 msg = {'mbody': 'Feeds:\n' + '\n'.join(Feeds.FEEDS),
169 'mhtml': 'Feeds:<br />' + '<br />'.join(html)}