File: subscription.py

package info (click to toggle)
miro 1.2.3-2
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 60,356 kB
  • ctags: 15,099
  • sloc: cpp: 58,491; python: 40,363; ansic: 796; xml: 265; sh: 197; makefile: 167
file content (186 lines) | stat: -rw-r--r-- 6,394 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# Miro - an RSS based video player application
# Copyright (C) 2005-2008 Participatory Culture Foundation
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
#
# In addition, as a special exception, the copyright holders give
# permission to link the code of portions of this program with the OpenSSL
# library.
#
# You must obey the GNU General Public License in all respects for all of
# the code used other than OpenSSL. If you modify file(s) with this
# exception, you may extend this exception to your version of the file(s),
# but you are not obligated to do so. If you do not wish to do so, delete
# this exception statement from your version. If you delete this exception
# statement from all source files in the program, then also delete it here.

import cgi
import re
from miro import util
import urllib2
import urlparse
import xml.dom.minidom

"""
This place's waiting for a little bit of documentation
"""

# =========================================================================

reflexiveAutoDiscoveryOpener = urllib2.urlopen

def parseFile(path):
    try:
        subscriptionFile = open(path, "r")
        content = subscriptionFile.read()
        subscriptionFile.close()
        return parseContent(content)
    except:
        pass

def parseContent(content):
    try:
        dom = xml.dom.minidom.parseString(content)
        root = dom.documentElement
        if root.nodeName == "rss":
            urls = _getSubscriptionsFromRSSChannel(root)
        elif root.nodeName == "feed":
            urls = _getSubscriptionsFromAtomFeed(root)
        elif root.nodeName == "opml":
            urls = _getSubscriptionsFromOPMLOutline(root)
        else:
            urls = None
        dom.unlink()
        return urls
    except:
        import traceback
        if util.chatter:
            print "WARNING: Error parsing OPML content..."
            traceback.print_exc()
        return None

def get_urls_from_query(query):
    urls = []
    for key, value in cgi.parse_qs(query).items():
        if re.match(r'url\d+$', key):
            urls.append(value[0])
    return urls

def findSubscribeLinks(url):
    """Given a URL, test if it's trying to subscribe the user using
    subscribe.getdemocracy.com.  Returns the list of parsed URLs.
    """
    try:
        scheme, host, path, params, query, frag = urlparse.urlparse(url)
    except:
        return 'none', []
    if host not in ('subscribe.getdemocracy.com', 'subscribe.getmiro.com'):
        return 'none', []
    if path in ('/', '/opml.php'):
        return 'feed', get_urls_from_query(query)
    elif path in ('/download.php','/download','/download/'):
        return 'download', get_urls_from_query(query)
    elif path in ('/channelguide.php', '/channelguide', '/channelguide/'):
        return 'guide', get_urls_from_query(query)
    else:
        return 'feed', [urllib2.unquote(path[1:])]

# =========================================================================

def _getSubscriptionsFromRSSChannel(root):
    try:
        channel = root.getElementsByTagName("channel").pop()
        urls = _getSubscriptionsFromAtomLinkConstruct(channel)
        if urls is not None:
            return urls
        else:
            link = channel.getElementsByTagName("link").pop()
            href = link.firstChild.data
            return _getSubscriptionsFromReflexiveAutoDiscovery(href, "application/rss+xml")
    except:
        pass

def _getSubscriptionsFromAtomFeed(root):
    try:
        urls = _getSubscriptionsFromAtomLinkConstruct(root)
        if urls is not None:
            return urls
        else:
            link = _getAtomLink(root)
            rel = link.getAttribute("rel")
            if rel == "alternate":
                href = link.getAttribute("href")
                return _getSubscriptionsFromReflexiveAutoDiscovery(href, "application/atom+xml")
    except:
        pass

def _getSubscriptionsFromAtomLinkConstruct(node):
    try:
        link = _getAtomLink(node)
        if link.getAttribute("rel") in ("self", "start"):
            href = link.getAttribute("href")
            return [href]
    except:
        pass

def _getSubscriptionsFromReflexiveAutoDiscovery(url, ltype):
    try:
        urls = list()
        html = reflexiveAutoDiscoveryOpener(url).read()
        for match in re.findall("<link[^>]+>", html):
            altMatch = re.search("rel=\"alternate\"", match)
            typeMatch = re.search("type=\"%s\"" % re.escape(ltype), match)
            hrefMatch = re.search("href=\"([^\"]*)\"", match)
            if None not in (altMatch, typeMatch, hrefMatch):
                href = hrefMatch.group(1)
                urls.append(href)
    except:
        urls = None
    else:
        if len(urls) == 0:
            urls = None
    return urls

def _getAtomLink(node):
    return node.getElementsByTagNameNS("http://www.w3.org/2005/Atom", "link").pop()

# =========================================================================

def _getSubscriptionsFromOPMLOutline(root):
    try:
        urls = list()
        body = root.getElementsByTagName("body").pop()
        _searchOPMLNodeRecursively(body, urls)
    except:
        urls = None
    else:
        if len(urls) == 0:
            urls = None
    return urls

def _searchOPMLNodeRecursively(node, urls):
    try:
        children = node.childNodes
        for child in children:
            if hasattr(child, 'getAttribute'):
                if child.hasAttribute("xmlUrl"):
                    url = child.getAttribute("xmlUrl")
                    urls.append(url)
                else:
                    _searchOPMLNodeRecursively(child, urls)
    except:
        pass

# =========================================================================