289fc65839b6ea9593fe9d406f2f5f047655d338
[rss2email.git] / rss2email / post_process / redirect.py
1 # Copyright (C) 2013 Francois Boulogne <fboulogne at april dot org>
2 #
3 # This file is part of rss2email.
4 #
5 # rss2email is free software: you can redistribute it and/or modify it under
6 # the terms of the GNU General Public License as published by the Free Software
7 # Foundation, either version 2 of the License, or (at your option) version 3 of
8 # the License.
9 #
10 # rss2email is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License along with
15 # rss2email.  If not, see <http://www.gnu.org/licenses/>.
16
17 """Remove redirects on the post URL.
18
19 Several websites use redirects (e.g. feedburner) for various reasons like
20 statistics. You may want to avoid this for privacy or for durability.
21
22 This hook finds and uses the real url behind redirects.
23 """
24
25 import urllib
26 import re
27 import rss2email
28
29 def process(feed, parsed, entry, guid, message):
30     # decode message
31     encoding = message.get_charsets()[0]
32     content = str(message.get_payload(decode=True), encoding)
33
34     links = []
35
36     # Get the link
37     link = entry['link']
38     if link:
39         links.append(link)
40
41     for enclosure in entry['enclosures']:
42         links.append(enclosure['href'])
43
44     if not links:
45         return message
46
47     # Remove the redirect and modify the content
48     timeout = rss2email.config.CONFIG['DEFAULT'].getint('feed-timeout')
49     proxy = rss2email.config.CONFIG['DEFAULT']['proxy']
50     for link in links:
51         try:
52             request = urllib.request.Request(link)
53             request.add_header('User-agent', rss2email.feed._USER_AGENT)
54             direct_link = urllib.request.urlopen(request).geturl()
55         except:
56             continue
57         content = re.sub(re.escape(link), direct_link, content, re.MULTILINE)
58
59     # clear CTE and set message. It can be important to clear the CTE
60     # before setting the payload, since the payload is only re-encoded
61     # if CTE is not already set.
62     del message['Content-Transfer-Encoding']
63     message.set_payload(content, charset=encoding)
64
65     return message