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