File: opml.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 (192 lines) | stat: -rw-r--r-- 7,190 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
187
188
189
190
191
192
# 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 os

from xml.dom import minidom
from xml.sax import saxutils
from xml.parsers import expat
from datetime import datetime
from StringIO import StringIO

from miro import util
from miro import feed
from miro import views
from miro import prefs
from miro import config
from miro import folder
from miro import dialogs
from miro import eventloop

from miro.gtcache import gettext as _
from miro.gtcache import ngettext

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

class Exporter (object):

    def __init__(self):
        self.io = StringIO()
        self.currentFolder = None

    @eventloop.asIdle
    def exportSubscriptionsTo(self, pathname):
        now = datetime.now()
        
        self.io.write(u'<?xml version="1.0" encoding="utf-8" ?>\n')
        self.io.write(u'<!-- OPML generated by Miro v%s on %s -->\n' % (config.get(prefs.APP_VERSION), now.ctime()))
        self.io.write(u'<opml version="2.0">\n')
        self.io.write(u'\t<head>\n')
        self.io.write(u'\t\t<title>%s</title>\n' % os.path.basename(pathname))
        self.io.write(u'\t\t<dateCreated>%s</dateCreated>\n' % now.ctime())
        self.io.write(u'\t\t<docs>http://www.opml.org/spec2</docs>\n')
        self.io.write(u'\t</head>\n')
        self.io.write(u'\t<body>\n')
    
        tabOrder = util.getSingletonDDBObject(views.channelTabOrder)
        for tab in tabOrder.getAllTabs():
            if tab.isChannelFolder():
                self._openFolderEntry(tab.obj)
            elif tab.isFeed():
                self._writeFeedEntry(tab.obj)
    
        if self.currentFolder is not None:
            self._closeFolderEntry()
    
        self.io.write(u'\t</body>\n')
        self.io.write(u'</opml>\n')
    
        f = open(pathname, "w")
        f.write(self.io.getvalue().encode('utf-8'))
        f.close()

    def _openFolderEntry(self, folder):
        if self.currentFolder is not None:
            self._closeFolderEntry()
        self.currentFolder = folder
        self.io.write(u'\t\t<outline text=%s>\n' % saxutils.quoteattr(folder.getTitle()))

    def _closeFolderEntry(self):
        self.io.write(u'\t\t</outline>\n')

    def _writeFeedEntry(self, thefeed):
        if (self.currentFolder is not None) and (thefeed.getFolder() is None):
            self._closeFolderEntry()
            self.currentFolder = None
        if self.currentFolder is None:
            spacer = u'\t\t'
        else:
            spacer = u'\t\t\t'

        # FIXME - RSSFeedImpl items should be of type "rss", but
        # it's not clear what type other things should be.  We
        # mark them as "mirofeed"--this should get changed if there
        # are issues.
        if isinstance(thefeed.getActualFeed(), feed.RSSFeedImpl):
            feedtype = u'type="rss"'
        else:
            feedtype = u'type="mirofeed"'

        self.io.write(u'%s<outline %s text=%s xmlUrl=%s />\n' % (spacer, feedtype, saxutils.quoteattr(thefeed.getTitle()), saxutils.quoteattr(thefeed.getURL())))

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

class Importer (object):

    def __init__(self):
        self.currentFolder = None
        self.ignoredFeeds = 0
        self.importedFeeds = 0

    @eventloop.asIdle
    def importSubscriptionsFrom(self, pathname, showSummary = True):
        f = open(pathname, "r")
        content = f.read()
        f.close()
        
        try:
            dom = minidom.parseString(content)
            root = dom.documentElement
            body = root.getElementsByTagName("body").pop()
            self._walkOutline(body)
            dom.unlink()
            if showSummary:
                self.showImportSummary()
        except expat.ExpatError:
            self.showXMLError()

    def showXMLError(self):
        title = _(u"OPML Import failed")
        message = _(u"The selected OPML file appears to be invalid. Import was interrupted.")
        dialog = dialogs.MessageBoxDialog(title, message)
        dialog.run()

    def showImportSummary(self):
        title = _(u"OPML Import summary")
        message = ngettext(u"Successfully imported %d feed.", u"Successfully imported %d feeds.", self.importedFeeds) % self.importedFeeds
        if self.ignoredFeeds > 0:
            message += "\n"
            message += ngettext(u"Skipped %d feed already present.", u"Skipped %d feeds already present.", self.ignoredFeeds) % self.ignoredFeeds
        dialog = dialogs.MessageBoxDialog(title, message)
        dialog.run()
        
    def _walkOutline(self, node):
        try:
            children = node.childNodes
            for child in children:
                if hasattr(child, 'getAttribute'):
                    if child.hasAttribute("xmlUrl"):
                        self._handleFeedEntry(child)
                    else:
                        self._handlerFolderEntry(child)
            self.currentFolder = None
        except Exception, e:
            print e
            pass
            
    def _handleFeedEntry(self, entry):
        url = entry.getAttribute("xmlUrl")
        f = feed.getFeedByURL(url)
        if f is None:
            f = feed.Feed(url, False)
            title = entry.getAttribute("text")
            if title is not None and title != '':
                f.setTitle(title)
            if self.currentFolder is not None:
                f.setFolder(self.currentFolder)
                f.blink()
            self.importedFeeds += 1
        else:
            self.ignoredFeeds += 1
    
    def _handlerFolderEntry(self, entry):
        title = entry.getAttribute("text")
        self.currentFolder = folder.ChannelFolder(title)
        self._walkOutline(entry)

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