]> kaliko git repositories - sid.git/blob - sid/feeds.py
cf77ae023aebf22a0ca7e7ebe20e2fe7a7b628af
[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.bot = plugin.bot
51         self.last_check = datetime.datetime.utcnow()
52         self.seen = dict()
53         self.thread_killed = False
54
55     def send(self, message):
56         """simple wrapper around bot send_message method"""
57         self.bot.send_message(mto=self.bot.room,
58                               mbody=message[1],
59                               mhtml=message[0],
60                               mtype='groupchat')
61
62     def new_posts(self, feed):
63         """Send new posts in feed"""
64         parsed_feed = feed_parse(feed)
65
66         # Cannot resolve address
67         if 'status' not in parsed_feed:
68             self.bot.log.error('Error from "%s": %s.' %
69                     (feed, parsed_feed.bozo_exception.__repr__()))
70             return
71
72         # unusual return http code
73         if parsed_feed.status != 200:
74             self.bot.log.error(
75                 'Got code %(status)d from "%(href)s" (please update).' %
76                     parsed_feed)
77             return
78
79         feed_updated = parsed_feed.feed.get('updated_parsed', None)
80
81         # Avoid looping over all posts if possible
82         if feed_updated and strtm_to_dtm(feed_updated) < self.last_check:
83             self.bot.log.debug('updated   : %s' % strtm_to_dtm(feed_updated))
84             self.bot.log.debug('last check: %s' % self.last_check)
85             return
86
87         title = '"%s":' % parsed_feed.feed.get('title', 'n/a')
88         xtitle = '<strong>%s</strong>:' % html_escape(
89             parsed_feed.feed.get('title', 'n/a'))
90         text = [title]
91         xhtml = [xtitle]
92         feed_id = parsed_feed.feed.get('id', feed)
93         if not self.seen.setdefault(feed_id):
94             # Fills with post id when first started (prevent from posting all
95             # entries at startup)
96             self.seen[feed_id] = {p.id for p in parsed_feed.entries}
97             #return
98
99         # Detecting new post
100         entries = {p.id for p in parsed_feed.entries}
101         new_entries = [p for p in parsed_feed.entries
102                        if p.id in entries - self.seen.get(feed_id)]
103         for post in new_entries:
104             self.bot.log.info(post.title)
105
106             body = '%(title)s %(link)s' % post
107             text.append(body)
108
109             xpost = dict(**post)
110             xpost['title'] = html_escape(xpost.get('title', 'n/a'))
111             xbody = '<a href="%(link)s">%(title)s</a>' % xpost
112             xhtml.append(xbody)
113         # Updating self.seen
114         self.seen[feed_id] = entries
115         if len(text) > 1:
116             self.bot.log.debug('<br />'.join(xhtml))
117             self.send(('<br />'.join(xhtml), '\n'.join(text)))
118
119     def run(self):
120         while not self.thread_killed:
121             self.bot.log.debug('feeds check')
122             for feed in self.feeds_list:
123                 try:
124                     self.new_posts(feed)
125                 except Exception as err:
126                     self.bot.log.error('feeds thread crashed: %s' % err)
127                     self.bot.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)):
131                 time.sleep(1)
132                 if self.thread_killed:
133                     return
134
135
136 class Feeds(Plugin):
137     TEMPO = 60
138     FEEDS = [
139         # not working <http://bugs.debian.org/612274>
140         # 'http://www.debian.org/security/dsa',
141
142         # not working <http://bugs.debian.org/612274>
143         # 'http://www.debian.org/News/news',
144
145         # DPN in french
146        'http://www.debian.org/News/weekly/dwn.fr.rdf',
147
148         # Misc
149        'http://rss.gmane.org/topics/excerpts/gmane.linux.debian.devel.announce',
150        'http://rss.gmane.org/gmane.linux.debian.user.security.announce',
151        'http://planet-fr.debian.net/users/rss20.xml',
152        'http://planet.debian.org/atom.xml',
153        'http://rss.gmane.org/gmane.linux.debian.devel.general',
154         ]
155
156     def __init__(self, bot):
157         Plugin.__init__(self, bot)
158         self.last_check = None
159         self.th_mon = FeedMonitor(self)
160         self.th_mon.start()
161
162     def shutdown(self):
163         self.th_mon.thread_killed = True
164
165     @botcmd
166     def feeds(self, message, args):
167         """feeds monitors debian project related feeds.
168         !feeds : registred feeds list
169         !feeds last : last check time"""
170         if 'last' in args:
171             return 'Last feeds check: %s' % self.th_mon.last_check
172         return '\n'.join(Feeds.FEEDS)