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
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
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
)
120 state
['page'] = files
[0]
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 state
['page'] = files
[0]
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
176 if (int(time
.time()) - state
['time']) <= 1:
177 debug_write(['Hack erroneous request, send a 302 error', '\n'])
180 # 7. this is a request to exit a folder
181 # this request came by itself; it must be to exit a folder
183 debug_write(['Hack over 1 second,',
184 'must be request to exit folder\n'])
186 state
['query'] = {'Command': query
['Command'],
187 'SortOrder': query
['SortOrder'],
188 'ItemCount': query
['ItemCount'],
189 'Filter': query
['Filter'],
190 'Container': ['/'.join(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")
209 tsn
= handler
.headers
.getheader('tsn', '')
211 o
= urlparse("http://fake.host" + handler
.path
)
213 handler
.send_response(200)
214 handler
.end_headers()
215 transcode
.output_video(container
['path'] + path
[len(name
) + 1:],
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
)
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
):
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
))
249 def __getMetadataFromFile(self
, file):
252 if os
.path
.exists(file):
253 for line
in open(file):
254 if line
.strip().startswith('#'):
259 key
, value
= line
.split(':', 1)
261 value
= value
.strip()
263 if key
.startswith('v'):
265 metadata
[key
].append(value
)
267 metadata
[key
] = [value
]
269 metadata
[key
] = value
273 def __metadata(self
, full_path
, tsn
=''):
276 base_path
, title
= os
.path
.split(full_path
)
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
298 metadata
['iso_duration'] = 'P' + str(duration_delta
.days
) + \
299 'DT' + str(hours
) + 'H' + str(min) + \
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
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: ',
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()
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()
339 files
, total
, start
= self
.get_files(handler
, query
,
340 self
.video_file_filter
)
343 local_base_path
= self
.get_local_base_path(handler
, query
)
345 video
= VideoDetails()
346 video
['name'] = os
.path
.split(file)[1]
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)
352 video
['small_path'] = subcname
+ '/' + video
['name']
354 video
['valid'] = transcode
.supported_format(file)
356 video
.update(self
.__metadata
(file, tsn
))
360 handler
.send_response(200)
361 handler
.end_headers()
362 t
= Template(file=os
.path
.join(SCRIPTDIR
,'templates', 'container.tmpl'))
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
)
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'))
390 handler
.wfile
.write(t
)
392 class VideoDetails(DictMixin
):
394 def __init__(self
, d
=None):
400 def __getitem__(self
, key
):
401 if key
not in self
.d
:
402 self
.d
[key
] = self
.default(key
)
405 def __contains__(self
, key
):
408 def __setitem__(self
, key
, value
):
411 def __delitem__(self
):
418 return self
.d
.__iter
__()
421 return self
.d
.iteritems()
423 def default(self
, key
):
426 'episodeNumber' : '0',
427 'displayMajorNumber' : '0',
428 'displayMinorNumber' : '0',
429 'isEpisode' : 'true',
430 'colorCode' : ('COLOR', '4'),
431 'showType' : ('SERIES', '5'),
432 'tvRating' : ('NR', '7')
436 elif key
.startswith('v'):