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