Don't really need "DownQuery".
[pyTivo.git] / plugins / video / video.py
blob7bbe293f0788458b08271363c5bb1fb64aeb2996
1 import transcode, os, socket, re, urllib, zlib
2 from Cheetah.Template import Template
3 from plugin import Plugin, quote, unquote
4 from urlparse import urlparse
5 from xml.sax.saxutils import escape
6 from lrucache import LRUCache
7 from UserDict import DictMixin
8 from datetime import datetime, timedelta
9 import config
10 import time
12 SCRIPTDIR = os.path.dirname(__file__)
14 CLASS_NAME = 'Video'
16 extfile = os.path.join(SCRIPTDIR, 'video.ext')
17 try:
18 extensions = file(extfile).read().split()
19 except:
20 extensions = None
22 debug = config.getDebug()
23 hack83 = config.getHack83()
25 def debug_write(data):
26 if debug:
27 debug_out = []
28 debug_out.append('Video.py - ')
29 for x in data:
30 debug_out.append(str(x))
31 fdebug = open('debug.txt', 'a')
32 fdebug.write(' '.join(debug_out))
33 fdebug.close()
35 if hack83:
36 debug_write(['Hack83 is enabled.\n'])
38 class Video(Plugin):
40 CONTENT_TYPE = 'x-container/tivo-videos'
42 # Used for 8.3's broken requests
43 count = 0
44 request_history = {}
46 def video_file_filter(self, full_path, type=None):
47 if os.path.isdir(full_path):
48 return True
49 if extensions:
50 return os.path.splitext(full_path)[1].lower() in extensions
51 else:
52 return transcode.supported_format(full_path)
54 def hack(self, handler, query, subcname):
55 debug_write(['Hack new request ------------------------\n'])
56 debug_write(['Hack TiVo request is: \n', query, '\n'])
57 queryAnchor = ''
58 rightAnchor = ''
59 leftAnchor = ''
60 tsn = handler.headers.getheader('tsn', '')
62 # not a tivo
63 if not tsn:
64 debug_write(['Hack this was not a TiVo request.\n'])
65 return query, None
67 # this breaks up the anchor item request into seperate parts
68 if 'AnchorItem' in query and query['AnchorItem'] != ['Hack8.3']:
69 queryAnchor = urllib.unquote_plus(''.join(query['AnchorItem']))
70 if queryAnchor.find('Container=') >= 0:
71 # This is a folder
72 queryAnchor = queryAnchor.split('Container=')[-1]
73 else:
74 # This is a file
75 queryAnchor = queryAnchor.split('/', 1)[-1]
76 leftAnchor, rightAnchor = queryAnchor.rsplit('/', 1)
77 debug_write(['Hack queryAnchor: ', queryAnchor,
78 ' leftAnchor: ', leftAnchor,
79 ' rightAnchor: ', rightAnchor, '\n'])
80 try:
81 path, state = self.request_history[tsn]
82 except KeyError:
83 # Never seen this tsn, starting new history
84 debug_write(['New TSN.\n'])
85 path = []
86 state = {}
87 self.request_history[tsn] = (path, state)
88 state['query'] = query
89 state['page'] = ''
90 state['time'] = int(time.time()) + 1000
92 debug_write(['Hack our saved request is: \n', state['query'], '\n'])
94 current_folder = subcname.split('/')[-1]
96 # Begin figuring out what the request TiVo sent us means
97 # There are 7 options that can occur
99 # 1. at the root - This request is always accurate
100 if len(subcname.split('/')) == 1:
101 debug_write(['Hack we are at the root.',
102 'Saving query, Clearing state[page].\n'])
103 path[:] = [current_folder]
104 state['query'] = query
105 state['page'] = ''
106 return query, path
108 # 2. entering a new folder
109 # If there is no AnchorItem in the request then we must be
110 # entering a new folder.
111 if 'AnchorItem' not in query:
112 debug_write(['Hack we are entering a new folder.',
113 'Saving query, setting time, setting state[page].\n'])
114 path[:] = subcname.split('/')
115 state['query'] = query
116 state['time'] = int(time.time())
117 files, total, start = self.get_files(handler, query,
118 self.video_file_filter)
119 if files:
120 state['page'] = files[0]
121 else:
122 state['page'] = ''
123 return query, path
125 # 3. Request a page after pyTivo sent a 302 code
126 # we know this is the proper page
127 if ''.join(query['AnchorItem']) == 'Hack8.3':
128 debug_write(['Hack requested page from 302 code.',
129 'Returning saved query,\n'])
130 return state['query'], path
132 # 4. this is a request for a file
133 if 'ItemCount' in query and int(''.join(query['ItemCount'])) == 1:
134 debug_write(['Hack requested a file', '\n'])
135 # Everything in this request is right except the container
136 query['Container'] = ['/'.join(path)]
137 state['page'] = ''
138 return query, path
140 # All remaining requests could be a second erroneous request for
141 # each of the following we will pause to see if a correct
142 # request is coming right behind it.
144 # Sleep just in case the erroneous request came first this
145 # allows a proper request to be processed first
146 debug_write(['Hack maybe erroneous request, sleeping.\n'])
147 time.sleep(.25)
149 # 5. scrolling in a folder
150 # This could be a request to exit a folder or scroll up or down
151 # within the folder
152 # First we have to figure out if we are scrolling
153 if 'AnchorOffset' in query:
154 debug_write(['Hack Anchor offset was in query.',
155 'leftAnchor needs to match ', '/'.join(path), '\n'])
156 if leftAnchor == str('/'.join(path)):
157 debug_write(['Hack leftAnchor matched.', '\n'])
158 query['Container'] = ['/'.join(path)]
159 files, total, start = self.get_files(handler, query,
160 self.video_file_filter)
161 debug_write(['Hack saved page is= ', state['page'],
162 ' top returned file is= ', files[0], '\n'])
163 # If the first file returned equals the top of the page
164 # then we haven't scrolled pages
165 if files[0] != str(state['page']):
166 debug_write(['Hack this is scrolling within a folder.\n'])
167 state['page'] = files[0]
168 return query, path
170 # The only remaining options are exiting a folder or this is a
171 # erroneous second request.
173 # 6. this an extraneous request
174 # this came within a second of a valid request; just use that
175 # request.
176 if (int(time.time()) - state['time']) <= 1:
177 debug_write(['Hack erroneous request, send a 302 error', '\n'])
178 return None, path
180 # 7. this is a request to exit a folder
181 # this request came by itself; it must be to exit a folder
182 else:
183 debug_write(['Hack over 1 second,',
184 'must be request to exit folder\n'])
185 path.pop()
186 state['query'] = {'Command': query['Command'],
187 'SortOrder': query['SortOrder'],
188 'ItemCount': query['ItemCount'],
189 'Filter': query['Filter'],
190 'Container': ['/'.join(path)]}
191 return None, path
193 # just in case we missed something.
194 debug_write(['Hack ERROR, should not have made it here. ',
195 'Trying to recover.\n'])
196 return state['query'], path
198 def send_file(self, handler, container, name):
199 if handler.headers.getheader('Range') and \
200 handler.headers.getheader('Range') != 'bytes=0-':
201 handler.send_response(206)
202 handler.send_header('Connection', 'close')
203 handler.send_header('Content-Type', 'video/x-tivo-mpeg')
204 handler.send_header('Transfer-Encoding', 'chunked')
205 handler.end_headers()
206 handler.wfile.write("\x30\x0D\x0A")
207 return
209 tsn = handler.headers.getheader('tsn', '')
211 o = urlparse("http://fake.host" + handler.path)
212 path = unquote(o[2])
213 handler.send_response(200)
214 handler.end_headers()
215 transcode.output_video(container['path'] + path[len(name) + 1:],
216 handler.wfile, tsn)
218 def __isdir(self, full_path):
219 return os.path.isdir(full_path)
221 def __duration(self, full_path):
222 return transcode.video_info(full_path)[4]
224 def __est_size(self, full_path, tsn = ''):
225 # Size is estimated by taking audio and video bit rate adding 2%
227 if transcode.tivo_compatable(full_path, tsn):
228 # Is TiVo-compatible mpeg2
229 return int(os.stat(full_path).st_size)
230 else:
231 # Must be re-encoded
232 audioBPS = config.strtod(config.getAudioBR(tsn))
233 videoBPS = config.strtod(config.getVideoBR(tsn))
234 bitrate = audioBPS + videoBPS
235 return int((self.__duration(full_path) / 1000) *
236 (bitrate * 1.02 / 8))
238 def __getMetadataFromTxt(self, full_path):
239 metadata = {}
241 default_file = os.path.join(os.path.split(full_path)[0], 'default.txt')
242 description_file = full_path + '.txt'
244 metadata.update(self.__getMetadataFromFile(default_file))
245 metadata.update(self.__getMetadataFromFile(description_file))
247 return metadata
249 def __getMetadataFromFile(self, file):
250 metadata = {}
252 if os.path.exists(file):
253 for line in open(file):
254 if line.strip().startswith('#'):
255 continue
256 if not ':' in line:
257 continue
259 key, value = line.split(':', 1)
260 key = key.strip()
261 value = value.strip()
263 if key.startswith('v'):
264 if key in metadata:
265 metadata[key].append(value)
266 else:
267 metadata[key] = [value]
268 else:
269 metadata[key] = value
271 return metadata
273 def __metadata(self, full_path, tsn =''):
274 metadata = {}
276 base_path, title = os.path.split(full_path)
277 now = datetime.now()
278 originalAirDate = datetime.fromtimestamp(os.stat(full_path).st_ctime)
279 duration = self.__duration(full_path)
280 duration_delta = timedelta(milliseconds = duration)
282 metadata['title'] = '.'.join(title.split('.')[:-1])
283 metadata['seriesTitle'] = metadata['title'] # default to the filename
284 metadata['originalAirDate'] = originalAirDate.isoformat()
285 metadata['time'] = now.isoformat()
286 metadata['startTime'] = now.isoformat()
287 metadata['stopTime'] = (now + duration_delta).isoformat()
289 metadata.update( self.__getMetadataFromTxt(full_path) )
291 metadata['size'] = self.__est_size(full_path, tsn)
292 metadata['duration'] = duration
294 min = duration_delta.seconds / 60
295 sec = duration_delta.seconds % 60
296 hours = min / 60
297 min = min % 60
298 metadata['iso_duration'] = 'P' + str(duration_delta.days) + \
299 'DT' + str(hours) + 'H' + str(min) + \
300 'M' + str(sec) + 'S'
301 return metadata
303 def QueryContainer(self, handler, query):
304 tsn = handler.headers.getheader('tsn', '')
305 subcname = query['Container'][0]
307 # If you are running 8.3 software you want to enable hack83
308 # in the config file
310 if hack83:
311 print '=' * 73
312 query, hackPath = self.hack(handler, query, subcname)
313 hackPath = '/'.join(hackPath)
314 print 'Tivo said:', subcname, '|| Hack said:', hackPath
315 debug_write(['Hack Tivo said: ', subcname, ' || Hack said: ',
316 hackPath, '\n'])
317 subcname = hackPath
319 if not query:
320 debug_write(['Hack sending 302 redirect page', '\n'])
321 handler.send_response(302)
322 handler.send_header('Location ', 'http://' +
323 handler.headers.getheader('host') +
324 '/TiVoConnect?Command=QueryContainer&' +
325 'AnchorItem=Hack8.3&Container=' + hackPath)
326 handler.end_headers()
327 return
329 # End hack mess
331 cname = subcname.split('/')[0]
333 if not handler.server.containers.has_key(cname) or \
334 not self.get_local_path(handler, query):
335 handler.send_response(404)
336 handler.end_headers()
337 return
339 files, total, start = self.get_files(handler, query,
340 self.video_file_filter)
342 videos = []
343 local_base_path = self.get_local_base_path(handler, query)
344 for file in files:
345 video = VideoDetails()
346 video['name'] = os.path.split(file)[1]
347 video['path'] = file
348 video['part_path'] = file.replace(local_base_path, '', 1)
349 video['title'] = os.path.split(file)[1]
350 video['is_dir'] = self.__isdir(file)
351 if video['is_dir']:
352 video['small_path'] = subcname + '/' + video['name']
353 else:
354 video['valid'] = transcode.supported_format(file)
355 if video['valid']:
356 video.update(self.__metadata(file, tsn))
358 videos.append(video)
360 handler.send_response(200)
361 handler.end_headers()
362 t = Template(file=os.path.join(SCRIPTDIR,'templates', 'container.tmpl'))
363 t.container = cname
364 t.name = subcname
365 t.total = total
366 t.start = start
367 t.videos = videos
368 t.quote = quote
369 t.escape = escape
370 t.crc = zlib.crc32
371 t.guid = config.getGUID()
372 handler.wfile.write(t)
374 def TVBusQuery(self, handler, query):
375 tsn = handler.headers.getheader('tsn', '')
376 file = query['File'][0]
377 path = self.get_local_path(handler, query)
378 file_path = path + file
380 file_info = VideoDetails()
381 valid = transcode.supported_format(file_path)
382 if valid:
383 file_info.update(self.__metadata(file_path, tsn))
385 handler.send_response(200)
386 handler.end_headers()
387 t = Template(file=os.path.join(SCRIPTDIR,'templates', 'TvBus.tmpl'))
388 t.video = file_info
389 t.escape = escape
390 handler.wfile.write(t)
392 class VideoDetails(DictMixin):
394 def __init__(self, d=None):
395 if d:
396 self.d = d
397 else:
398 self.d = {}
400 def __getitem__(self, key):
401 if key not in self.d:
402 self.d[key] = self.default(key)
403 return self.d[key]
405 def __contains__(self, key):
406 return True
408 def __setitem__(self, key, value):
409 self.d[key] = value
411 def __delitem__(self):
412 del self.d[key]
414 def keys(self):
415 return self.d.keys()
417 def __iter__(self):
418 return self.d.__iter__()
420 def iteritems(self):
421 return self.d.iteritems()
423 def default(self, key):
424 defaults = {
425 'showingBits' : '0',
426 'episodeNumber' : '0',
427 'displayMajorNumber' : '0',
428 'displayMinorNumber' : '0',
429 'isEpisode' : 'true',
430 'colorCode' : ('COLOR', '4'),
431 'showType' : ('SERIES', '5'),
432 'tvRating' : ('NR', '7')
434 if key in defaults:
435 return defaults[key]
436 elif key.startswith('v'):
437 return []
438 else:
439 return ''