Merge branch 'master' into subfolders-8.3
[pyTivo.git] / plugins / video / video.py
blobe3a2b9ccf11af218be7d288ed29c2c46a565cd07
1 import transcode, os, socket, re, urllib
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 state['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, state['query'],
118 self.video_file_filter)
119 if len(files) >= 1:
120 state['page'] = files[0]
121 else:
122 state['page'] = ''
123 return state['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 files, total, start = self.get_files(handler, query,
168 self.video_file_filter)
169 state['page'] = files[0]
170 return query, path
172 # The only remaining options are exiting a folder or this is a
173 # erroneous second request.
175 # 6. this an extraneous request
176 # this came within a second of a valid request; just use that
177 # request.
178 if (int(time.time()) - state['time']) <= 1:
179 debug_write(['Hack erroneous request, send a 302 error', '\n'])
180 files, total, start = self.get_files(handler, query,
181 self.video_file_filter)
182 return None, path
184 # 7. this is a request to exit a folder
185 # this request came by itself; it must be to exit a folder
186 else:
187 debug_write(['Hack over 1 second,',
188 'must be request to exit folder\n'])
189 path.pop()
190 downQuery = {}
191 downQuery['Command'] = query['Command']
192 downQuery['SortOrder'] = query['SortOrder']
193 downQuery['ItemCount'] = query['ItemCount']
194 downQuery['Filter'] = query['Filter']
195 downQuery['Container'] = ['/'.join(path)]
196 state['query'] = downQuery
197 return None, path
199 # just in case we missed something.
200 debug_write(['Hack ERROR, should not have made it here. ',
201 'Trying to recover.\n'])
202 return state['query'], path
204 def send_file(self, handler, container, name):
205 if handler.headers.getheader('Range') and \
206 handler.headers.getheader('Range') != 'bytes=0-':
207 handler.send_response(206)
208 handler.send_header('Connection', 'close')
209 handler.send_header('Content-Type', 'video/x-tivo-mpeg')
210 handler.send_header('Transfer-Encoding', 'chunked')
211 handler.end_headers()
212 handler.wfile.write("\x30\x0D\x0A")
213 return
215 tsn = handler.headers.getheader('tsn', '')
217 o = urlparse("http://fake.host" + handler.path)
218 path = unquote(o[2])
219 handler.send_response(200)
220 handler.end_headers()
221 transcode.output_video(container['path'] + path[len(name) + 1:],
222 handler.wfile, tsn)
224 def __isdir(self, full_path):
225 return os.path.isdir(full_path)
227 def __duration(self, full_path):
228 return transcode.video_info(full_path)[4]
230 def __est_size(self, full_path, tsn = ''):
231 # Size is estimated by taking audio and video bit rate adding 2%
233 if transcode.tivo_compatable(full_path, tsn):
234 # Is TiVo-compatible mpeg2
235 return int(os.stat(full_path).st_size)
236 else:
237 # Must be re-encoded
238 audioBPS = config.strtod(config.getAudioBR(tsn))
239 videoBPS = config.strtod(config.getVideoBR(tsn))
240 bitrate = audioBPS + videoBPS
241 return int((self.__duration(full_path) / 1000) *
242 (bitrate * 1.02 / 8))
244 def __getMetadataFromTxt(self, full_path):
245 metadata = {}
247 default_file = os.path.join(os.path.split(full_path)[0], 'default.txt')
248 description_file = full_path + '.txt'
250 metadata.update(self.__getMetadataFromFile(default_file))
251 metadata.update(self.__getMetadataFromFile(description_file))
253 return metadata
255 def __getMetadataFromFile(self, file):
256 metadata = {}
258 if os.path.exists(file):
259 for line in open(file):
260 if line.strip().startswith('#'):
261 continue
262 if not ':' in line:
263 continue
265 key, value = line.split(':', 1)
266 key = key.strip()
267 value = value.strip()
269 if key.startswith('v'):
270 if key in metadata:
271 metadata[key].append(value)
272 else:
273 metadata[key] = [value]
274 else:
275 metadata[key] = value
277 return metadata
279 def __metadata(self, full_path, tsn =''):
280 metadata = {}
282 base_path, title = os.path.split(full_path)
283 now = datetime.now()
284 originalAirDate = datetime.fromtimestamp(os.stat(full_path).st_ctime)
285 duration = self.__duration(full_path)
286 duration_delta = timedelta(milliseconds = duration)
288 metadata['title'] = '.'.join(title.split('.')[:-1])
289 metadata['seriesTitle'] = metadata['title'] # default to the filename
290 metadata['originalAirDate'] = originalAirDate.isoformat()
291 metadata['time'] = now.isoformat()
292 metadata['startTime'] = now.isoformat()
293 metadata['stopTime'] = (now + duration_delta).isoformat()
295 metadata.update( self.__getMetadataFromTxt(full_path) )
297 metadata['size'] = self.__est_size(full_path, tsn)
298 metadata['duration'] = duration
300 min = duration_delta.seconds / 60
301 sec = duration_delta.seconds % 60
302 hours = min / 60
303 min = min % 60
304 metadata['iso_duration'] = 'P' + str(duration_delta.days) + \
305 'DT' + str(hours) + 'H' + str(min) + \
306 'M' + str(sec) + 'S'
307 return metadata
309 def QueryContainer(self, handler, query):
310 tsn = handler.headers.getheader('tsn', '')
311 subcname = query['Container'][0]
313 # If you are running 8.3 software you want to enable hack83
314 # in the config file
316 if hack83:
317 print '=' * 73
318 query, hackPath = self.hack(handler, query, subcname)
319 hackPath = '/'.join(hackPath)
320 print 'Tivo said:', subcname, '|| Hack said:', hackPath
321 debug_write(['Hack Tivo said: ', subcname, ' || Hack said: ',
322 hackPath, '\n'])
323 subcname = hackPath
325 if not query:
326 debug_write(['Hack sending 302 redirect page', '\n'])
327 handler.send_response(302)
328 handler.send_header('Location ', 'http://' +
329 handler.headers.getheader('host') +
330 '/TiVoConnect?Command=QueryContainer&' +
331 'AnchorItem=Hack8.3&Container=' + hackPath)
332 handler.end_headers()
333 return
335 # End hack mess
337 cname = subcname.split('/')[0]
339 if not handler.server.containers.has_key(cname) or \
340 not self.get_local_path(handler, query):
341 handler.send_response(404)
342 handler.end_headers()
343 return
345 files, total, start = self.get_files(handler, query,
346 self.video_file_filter)
348 videos = []
349 local_base_path = self.get_local_base_path(handler, query)
350 for file in files:
351 video = VideoDetails()
352 video['name'] = os.path.split(file)[1]
353 video['path'] = file
354 video['part_path'] = file.replace(local_base_path, '', 1)
355 video['title'] = os.path.split(file)[1]
356 video['is_dir'] = self.__isdir(file)
357 if not video['is_dir']:
358 video.update(self.__metadata(file, tsn))
360 videos.append(video)
362 handler.send_response(200)
363 handler.end_headers()
364 t = Template(file=os.path.join(SCRIPTDIR,'templates', 'container.tmpl'))
365 t.container = cname
366 t.name = subcname
367 t.total = total
368 t.start = start
369 t.videos = videos
370 t.quote = quote
371 t.escape = escape
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 file_info.update(self.__metadata(file_path, tsn))
383 handler.send_response(200)
384 handler.end_headers()
385 t = Template(file=os.path.join(SCRIPTDIR,'templates', 'TvBus.tmpl'))
386 t.video = file_info
387 t.escape = escape
388 handler.wfile.write(t)
390 class VideoDetails(DictMixin):
392 def __init__(self, d=None):
393 if d:
394 self.d = d
395 else:
396 self.d = {}
398 def __getitem__(self, key):
399 if key not in self.d:
400 self.d[key] = self.default(key)
401 return self.d[key]
403 def __contains__(self, key):
404 return True
406 def __setitem__(self, key, value):
407 self.d[key] = value
409 def __delitem__(self):
410 del self.d[key]
412 def keys(self):
413 return self.d.keys()
415 def __iter__(self):
416 return self.d.__iter__()
418 def iteritems(self):
419 return self.d.iteritems()
421 def default(self, key):
422 defaults = {
423 'showingBits' : '0',
424 'episodeNumber' : '0',
425 'displayMajorNumber' : '0',
426 'displayMinorNumber' : '0',
427 'isEpisode' : 'true',
428 'colorCode' : ('COLOR', '4'),
429 'showType' : ('SERIES', '5'),
430 'tvRating' : ('NR', '7')
432 if key in defaults:
433 return defaults[key]
434 elif key.startswith('v'):
435 return []
436 else:
437 return ''