-
Notifications
You must be signed in to change notification settings - Fork 0
/
pyvr.py
281 lines (225 loc) · 6.37 KB
/
pyvr.py
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
#!/usr/bin/env python
# Copyright 2008 John-Mark Gurney <jmg@funktaht.com>
'''PVR Interface'''
__version__ = '$Change: 1109 $'
# $Id: //depot/python/pymeds/main/shoutcast.py#13 $
from DIDLLite import Container, Item, VideoItem, Resource
from FSStorage import registerklassfun
import os.path
import time
from twisted.internet import reactor
from twisted.python import log
import twisted.web
import urlparse
def getPage(url, contextFactory=None, *args, **kwargs):
"""Download a web page as a string.
Download a page. Return the HTTPClientFactory, which will
callback with a page (as a string) or errback with a
description of the error.
See HTTPClientFactory to see what extra args can be passed.
"""
from twisted.web.client import _parse, HTTPClientFactory
scheme, host, port, path = _parse(url)
factory = HTTPClientFactory(url, *args, **kwargs)
if scheme == 'https':
from twisted.internet import ssl
if contextFactory is None:
contextFactory = ssl.ClientContextFactory()
reactor.connectSSL(host, port, factory, contextFactory)
else:
reactor.connectTCP(host, port, factory)
return factory
class PYVRShow(VideoItem):
def __init__(self, *args, **kwargs):
baseurl = kwargs['url']
self.info = kwargs['info']
del kwargs['info'], kwargs['url']
VideoItem.__init__(self, *args, **kwargs)
url = self.info['link']
sc = urlparse.urlparse(url)[0]
if not sc:
# need to combine w/ base url
url = urlparse.urljoin(baseurl, url)
self.res = Resource(url,
'http-get:*:%s:*' % self.info['mimetype'])
self.res.duration = self.info['duration']
def doUpdate(self):
pass
import xml.sax
import xml.sax.handler
from xml.sax.saxutils import unescape
class RecordingXML(xml.sax.handler.ContentHandler):
dataels = ('title', 'subtitle', 'duration', 'mimetype', 'link',
'delete', )
def __init__(self):
self.shows = {}
self.data = None
def characters(self, chars):
if self.data is not None:
self.data.append(chars)
def startElement(self, name, attrs):
if name in self.dataels:
self.data = []
self.curel = name
elif name == 'record':
self.currec = {}
def endElement(self, name):
if name in self.dataels:
data = unescape(''.join(self.data))
self.currec[self.curel] = data
elif name == 'record':
rec = self.currec
try:
self.shows[rec['title']].append(rec)
except KeyError:
self.shows[rec['title']] = [ rec ]
self.data = None
def recxmltoobj(page):
obj = RecordingXML()
xml.sax.parseString(page, obj)
return obj.shows
class PYVRShows(Container):
def __init__(self, *args, **kwargs):
self.pyvr = kwargs['pyvr']
del kwargs['pyvr']
self.show = kwargs['show']
del kwargs['show']
Container.__init__(self, *args, **kwargs)
self.pathObjmap = {}
self.shows = {}
self.lastmodified = None
def checkUpdate(self):
self.pyvr.checkUpdate()
if self.pyvr.lastmodified != self.lastmodified:
self.doUpdate()
@staticmethod
def getunique(eps, ep):
i = 1
while True:
title = '%s Copy %d' % (ep['subtitle'], i)
if not eps.has_key(title):
return title
i += 1
@staticmethod
def eplisttodict(eps):
ret = {}
for pos, i in enumerate(eps):
title = i['subtitle']
if ret.has_key(title):
print 'WARNING: dup:', `i`, `ret[title]`
title = PYVRShows.getunique(ret, i)
i['pos'] = pos
ret[title] = i
return ret
def doUpdate(self):
nl = self.eplisttodict(self.pyvr.shows[self.show])
doupdate = False
for i in self.pathObjmap.keys():
if i not in nl:
# delete
doupdate = True
self.cd.delItem(self.pathObjmap[i])
del self.pathObjmap[i]
for i in nl:
if i in self.pathObjmap and self.shows[i] == nl[i]:
continue
doupdate = True
if i in self.pathObjmap:
# changed
self.cd.delItem(self.pathObjmap[i])
self.pathObjmap[i] = self.cd.addItem(self.id,
PYVRShow, i, url=self.pyvr.url, info=nl[i])
self.shows = nl
# sort our children
#self.sort(lambda x, y: cmp(x.title, y.title))
self.sort(lambda x, y: cmp(x.info['pos'], y.info['pos']))
if doupdate:
Container.doUpdate(self)
self.lastmodified = self.pyvr.lastmodified
class PYVR(Container):
def __init__(self, *args, **kwargs):
self.url = kwargs['url']
del kwargs['url']
Container.__init__(self, *args, **kwargs)
self.pathObjmap = {}
self.pend = None
self.lastmodified = None
self.newobjs = None
self.objs = {}
self.lastcheck = 0
def checkUpdate(self):
if self.pend is not None:
raise self.pend
if time.time() - self.lastcheck < 10:
return
# Check to see if any changes have been made
self.runCheck()
raise self.pend
def runCheck(self):
print 'runCheck'
self.page = getPage(self.url, method='HEAD')
self.page.deferred.addErrback(self.errCheck).addCallback(
self.doCheck)
self.pend = self.page.deferred
def errCheck(self, x):
print 'errCheck:', `x`
self.runCheck()
def doCheck(self, x):
print 'doCheck:', self.page.status
if self.page.status != '200':
print 'foo'
return reactor.callLater(.01, self.runCheck)
self.lastcheck = time.time()
slm = self.page.response_headers['last-modified']
if slm == self.lastmodified:
# Page the same, don't do anything
self.pend = None
return
self.page = getPage(self.url)
self.page.deferred.addCallback(self.parsePage)
self.pend = self.page.deferred
return self.pend
def parsePage(self, page):
slm = self.page.response_headers['last-modified']
self.lastmodified = slm
del self.page
self.pend = None
self.newobjs = recxmltoobj(page)
self.doUpdate()
def doUpdate(self):
if self.newobjs is None:
import traceback
traceback.print_stack(file=log.logfile)
return
nl = self.newobjs
doupdate = False
for i in self.pathObjmap.keys():
if i not in nl:
# delete
doupdate = True
self.cd.delItem(self.pathObjmap[i])
del self.pathObjmap[i]
# This data is referenced when adding new shows
self.shows = nl
for i in nl:
if i in self.pathObjmap:
continue
doupdate = True
try:
self.pathObjmap[i] = self.cd.addItem(self.id,
PYVRShows, i, show=i, pyvr=self)
except:
import traceback
traceback.print_exc(file=log.logfile)
raise
self.newobjs = None
# sort our children
self.sort(lambda x, y: cmp(x.title, y.title))
if doupdate:
Container.doUpdate(self)
def detectpyvrfile(path, fobj):
bn = os.path.basename(path)
if bn == 'PYVR':
return PYVR, { 'url': fobj.readline().strip() }
return None, None
registerklassfun(detectpyvrfile)