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
12 SCRIPTDIR
= os
.path
.dirname(__file__
)
16 extfile
= os
.path
.join(SCRIPTDIR
, 'video.ext')
18 extensions
= file(extfile
).read().split()
22 debug
= config
.getDebug()
23 hack83
= config
.getHack83()
25 def debug_write(data
):
28 debug_out
.append('Video.py - ')
30 debug_out
.append(str(x
))
31 fdebug
= open('debug.txt', 'a')
32 fdebug
.write(' '.join(debug_out
))
36 debug_write(['Hack83 is enabled.\n'])
40 CONTENT_TYPE
= 'x-container/tivo-videos'
42 # Used for 8.3's broken requests
46 def video_file_filter(self
, full_path
, type=None):
47 if os
.path
.isdir(full_path
):
50 return os
.path
.splitext(full_path
)[1].lower() in extensions
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'])
60 tsn
= handler
.headers
.getheader('tsn', '')
64 debug_write(['Hack this was not a TiVo request.\n'])
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:
72 queryAnchor
= queryAnchor
.split('Container=')[-1]
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'])
81 path
, state
, = self
.request_history
[tsn
]
83 # Never seen this tsn, starting new history
84 debug_write(['New TSN.\n'])
87 self
.request_history
[tsn
] = (path
, state
)
88 state
['query'] = query
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
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
)
120 state
['page'] = files
[0]
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
)]
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'])
149 # 5. scrolling in a folder
150 # This could be a request to exit a folder or scroll up or down
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]
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
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
)
184 # 7. this is a request to exit a folder
185 # this request came by itself; it must be to exit a folder
187 debug_write(['Hack over 1 second,',
188 'must be request to exit folder\n'])
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
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")
215 tsn
= handler
.headers
.getheader('tsn', '')
217 o
= urlparse("http://fake.host" + handler
.path
)
219 handler
.send_response(200)
220 handler
.end_headers()
221 transcode
.output_video(container
['path'] + path
[len(name
) + 1:],
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
)
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
):
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
))
255 def __getMetadataFromFile(self
, file):
258 if os
.path
.exists(file):
259 for line
in open(file):
260 if line
.strip().startswith('#'):
265 key
, value
= line
.split(':', 1)
267 value
= value
.strip()
269 if key
.startswith('v'):
271 metadata
[key
].append(value
)
273 metadata
[key
] = [value
]
275 metadata
[key
] = value
279 def __metadata(self
, full_path
, tsn
=''):
282 base_path
, title
= os
.path
.split(full_path
)
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
304 metadata
['iso_duration'] = 'P' + str(duration_delta
.days
) + \
305 'DT' + str(hours
) + 'H' + str(min) + \
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
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: ',
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()
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()
345 files
, total
, start
= self
.get_files(handler
, query
,
346 self
.video_file_filter
)
349 local_base_path
= self
.get_local_base_path(handler
, query
)
351 video
= VideoDetails()
352 video
['name'] = os
.path
.split(file)[1]
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
))
362 handler
.send_response(200)
363 handler
.end_headers()
364 t
= Template(file=os
.path
.join(SCRIPTDIR
,'templates', 'container.tmpl'))
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'))
388 handler
.wfile
.write(t
)
390 class VideoDetails(DictMixin
):
392 def __init__(self
, d
=None):
398 def __getitem__(self
, key
):
399 if key
not in self
.d
:
400 self
.d
[key
] = self
.default(key
)
403 def __contains__(self
, key
):
406 def __setitem__(self
, key
, value
):
409 def __delitem__(self
):
416 return self
.d
.__iter
__()
419 return self
.d
.iteritems()
421 def default(self
, key
):
424 'episodeNumber' : '0',
425 'displayMajorNumber' : '0',
426 'displayMinorNumber' : '0',
427 'isEpisode' : 'true',
428 'colorCode' : ('COLOR', '4'),
429 'showType' : ('SERIES', '5'),
430 'tvRating' : ('NR', '7')
434 elif key
.startswith('v'):