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
11 SCRIPTDIR
= os
.path
.dirname(__file__
)
15 extfile
= os
.path
.join(SCRIPTDIR
, 'video.ext')
17 extensions
= file(extfile
).read().split()
23 CONTENT_TYPE
= 'x-container/tivo-videos'
25 def video_file_filter(self
, full_path
, type=None):
26 if os
.path
.isdir(full_path
):
29 return os
.path
.splitext(full_path
)[1].lower() in extensions
31 return transcode
.supported_format(full_path
)
33 def send_file(self
, handler
, container
, name
):
34 if handler
.headers
.getheader('Range') and \
35 handler
.headers
.getheader('Range') != 'bytes=0-':
36 handler
.send_response(206)
37 handler
.send_header('Connection', 'close')
38 handler
.send_header('Content-Type', 'video/x-tivo-mpeg')
39 handler
.send_header('Transfer-Encoding', 'chunked')
41 handler
.wfile
.write("\x30\x0D\x0A")
44 tsn
= handler
.headers
.getheader('tsn', '')
46 o
= urlparse("http://fake.host" + handler
.path
)
48 handler
.send_response(200)
50 transcode
.output_video(container
['path'] + path
[len(name
) + 1:],
53 def __isdir(self
, full_path
):
54 return os
.path
.isdir(full_path
)
56 def __duration(self
, full_path
):
57 return transcode
.video_info(full_path
)[4]
59 def __est_size(self
, full_path
, tsn
= ''):
60 # Size is estimated by taking audio and video bit rate adding 2%
62 if transcode
.tivo_compatable(full_path
, tsn
):
63 # Is TiVo-compatible mpeg2
64 return int(os
.stat(full_path
).st_size
)
67 audioBPS
= config
.strtod(config
.getAudioBR(tsn
))
68 videoBPS
= config
.strtod(config
.getVideoBR(tsn
))
69 bitrate
= audioBPS
+ videoBPS
70 return int((self
.__duration
(full_path
) / 1000) *
73 def __getMetadataFromTxt(self
, full_path
):
76 default_file
= os
.path
.join(os
.path
.split(full_path
)[0], 'default.txt')
77 description_file
= full_path
+ '.txt'
79 metadata
.update(self
.__getMetadataFromFile
(default_file
))
80 metadata
.update(self
.__getMetadataFromFile
(description_file
))
84 def __getMetadataFromFile(self
, file):
87 if os
.path
.exists(file):
88 for line
in open(file):
89 if line
.strip().startswith('#'):
94 key
, value
= line
.split(':', 1)
98 if key
.startswith('v'):
100 metadata
[key
].append(value
)
102 metadata
[key
] = [value
]
104 metadata
[key
] = value
108 def __metadata(self
, full_path
, tsn
=''):
111 base_path
, title
= os
.path
.split(full_path
)
113 originalAirDate
= datetime
.fromtimestamp(os
.stat(full_path
).st_ctime
)
114 duration
= self
.__duration
(full_path
)
115 duration_delta
= timedelta(milliseconds
= duration
)
117 metadata
['title'] = '.'.join(title
.split('.')[:-1])
118 metadata
['seriesTitle'] = metadata
['title'] # default to the filename
119 metadata
['originalAirDate'] = originalAirDate
.isoformat()
120 metadata
['time'] = now
.isoformat()
121 metadata
['startTime'] = now
.isoformat()
122 metadata
['stopTime'] = (now
+ duration_delta
).isoformat()
124 metadata
.update( self
.__getMetadataFromTxt
(full_path
) )
126 metadata
['size'] = self
.__est
_size
(full_path
, tsn
)
127 metadata
['duration'] = duration
129 min = duration_delta
.seconds
/ 60
130 sec
= duration_delta
.seconds
% 60
133 metadata
['iso_duration'] = 'P' + str(duration_delta
.days
) + \
134 'DT' + str(hours
) + 'H' + str(min) + \
138 def QueryContainer(self
, handler
, query
):
139 tsn
= handler
.headers
.getheader('tsn', '')
140 subcname
= query
['Container'][0]
141 cname
= subcname
.split('/')[0]
143 if not handler
.server
.containers
.has_key(cname
) or \
144 not self
.get_local_path(handler
, query
):
145 handler
.send_response(404)
146 handler
.end_headers()
149 files
, total
, start
= self
.get_files(handler
, query
,
150 self
.video_file_filter
)
153 local_base_path
= self
.get_local_base_path(handler
, query
)
155 video
= VideoDetails()
156 video
['name'] = os
.path
.split(file)[1]
158 video
['part_path'] = file.replace(local_base_path
, '', 1)
159 video
['title'] = os
.path
.split(file)[1]
160 video
['is_dir'] = self
.__isdir
(file)
161 if not video
['is_dir']:
162 video
.update(self
.__metadata
(file, tsn
))
166 handler
.send_response(200)
167 handler
.end_headers()
168 t
= Template(file=os
.path
.join(SCRIPTDIR
,'templates', 'container.tmpl'))
176 handler
.wfile
.write(t
)
178 def TVBusQuery(self
, handler
, query
):
179 tsn
= handler
.headers
.getheader('tsn', '')
180 file = query
['File'][0]
181 path
= self
.get_local_path(handler
, query
)
182 file_path
= path
+ file
184 file_info
= VideoDetails()
185 file_info
.update(self
.__metadata
(file_path
, tsn
))
187 handler
.send_response(200)
188 handler
.end_headers()
189 t
= Template(file=os
.path
.join(SCRIPTDIR
,'templates', 'TvBus.tmpl'))
192 handler
.wfile
.write(t
)
194 class VideoDetails(DictMixin
):
196 def __init__(self
, d
=None):
202 def __getitem__(self
, key
):
203 if key
not in self
.d
:
204 self
.d
[key
] = self
.default(key
)
207 def __contains__(self
, key
):
210 def __setitem__(self
, key
, value
):
213 def __delitem__(self
):
220 return self
.d
.__iter
__()
223 return self
.d
.iteritems()
225 def default(self
, key
):
228 'episodeNumber' : '0',
229 'displayMajorNumber' : '0',
230 'displayMinorNumber' : '0',
231 'isEpisode' : 'true',
232 'colorCode' : ('COLOR', '4'),
233 'showType' : ('SERIES', '5'),
234 'tvRating' : ('NR', '7')
238 elif key
.startswith('v'):