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