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
12 if os
.path
.sep
== '/':
14 unquote
= urllib
.unquote_plus
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__
)
23 debug
= config
.getDebug()
24 hack83
= config
.getHack83()
26 def debug_write(data
):
29 debug_out
.append('Video.py - ')
31 debug_out
.append(str(x
))
32 fdebug
= open('debug.txt', 'a')
33 fdebug
.write(' '.join(debug_out
))
37 debug_write(['Hack83 is enabled.\n'])
41 CONTENT_TYPE
= 'x-container/tivo-videos'
43 # Used for 8.3's broken requests
47 def video_file_filter(self
, full_path
, type=None):
48 if os
.path
.isdir(full_path
):
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'])
58 tsn
= handler
.headers
.getheader('tsn', '')
62 debug_write(['Hack this was not a TiVo request.', '\n'])
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:
69 queryAnchor
= urllib
.unquote_plus("".join(query
['AnchorItem'])).split('Container=')[-1]
70 (leftAnchor
, rightAnchor
) = queryAnchor
.rsplit('/', 1)
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'])
78 path
, state
, = self
.request_history
[tsn
]
80 #Never seen this tsn, starting new history
81 debug_write(['New TSN.', '\n'])
84 self
.request_history
[tsn
] = (path
, state
)
85 state
['query'] = query
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
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
)
115 state
['page'] = files
[0]
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
)]
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'])
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]
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
)
176 #7. this is a request to exit a folder
177 #this request came by itself it must be to exit a folder
179 debug_write(['Hack over 1 second, must be request to exit folder', '\n'])
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
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")
205 tsn
= handler
.headers
.getheader('tsn', '')
207 o
= urlparse("http://fake.host" + handler
.path
)
209 handler
.send_response(200)
210 handler
.end_headers()
211 transcode
.output_video(container
['path'] + path
[len(name
) + 1:],
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
)
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
):
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
))
245 def __getMetadataFromFile(self
, file):
248 if os
.path
.exists(file):
249 for line
in open(file):
250 if line
.strip().startswith('#'):
255 key
, value
= line
.split(':', 1)
257 value
= value
.strip()
259 if key
.startswith('v'):
261 metadata
[key
].append(value
)
263 metadata
[key
] = [value
]
265 metadata
[key
] = value
269 def __metadata(self
, full_path
, tsn
=''):
272 base_path
, title
= os
.path
.split(full_path
)
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
294 metadata
['iso_duration'] = 'P' + str(duration_delta
.days
) + \
295 'DT' + str(hours
) + 'H' + str(min) + \
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
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
)
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()
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()
327 files
, total
, start
= self
.get_files(handler
, query
,
328 self
.video_file_filter
)
331 local_base_path
= self
.get_local_base_path(handler
, query
)
333 video
= VideoDetails()
334 video
['name'] = os
.path
.split(file)[1]
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
))
344 handler
.send_response(200)
345 handler
.end_headers()
346 t
= Template(file=os
.path
.join(SCRIPTDIR
,'templates', 'container.tmpl'))
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'))
370 handler
.wfile
.write(t
)
372 class VideoDetails(DictMixin
):
374 def __init__(self
, d
=None):
380 def __getitem__(self
, key
):
381 if key
not in self
.d
:
382 self
.d
[key
] = self
.default(key
)
385 def __contains__(self
, key
):
388 def __setitem__(self
, key
, value
):
391 def __delitem__(self
):
398 return self
.d
.__iter
__()
401 return self
.d
.iteritems()
403 def default(self
, key
):
406 'episodeNumber' : '0',
407 'displayMajorNumber' : '0',
408 'displayMinorNumber' : '0',
409 'isEpisode' : 'true',
410 'colorCode' : ('COLOR', '4'),
411 'showType' : ('SERIES', '5'),
412 'tvRating' : ('NR', '7')
416 elif key
.startswith('v'):