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__
)
17 CONTENT_TYPE
= 'x-container/tivo-videos'
19 def video_file_filter(self
, full_path
, type=None):
20 if os
.path
.isdir(full_path
):
22 return transcode
.supported_format(full_path
)
24 def send_file(self
, handler
, container
, name
):
25 if handler
.headers
.getheader('Range') and \
26 handler
.headers
.getheader('Range') != 'bytes=0-':
27 handler
.send_response(206)
28 handler
.send_header('Connection', 'close')
29 handler
.send_header('Content-Type', 'video/x-tivo-mpeg')
30 handler
.send_header('Transfer-Encoding', 'chunked')
32 handler
.wfile
.write("\x30\x0D\x0A")
35 tsn
= handler
.headers
.getheader('tsn', '')
37 o
= urlparse("http://fake.host" + handler
.path
)
39 handler
.send_response(200)
41 transcode
.output_video(container
['path'] + path
[len(name
) + 1:],
44 def __isdir(self
, full_path
):
45 return os
.path
.isdir(full_path
)
47 def __duration(self
, full_path
):
48 return transcode
.video_info(full_path
)[4]
50 def __est_size(self
, full_path
, tsn
= ''):
51 # Size is estimated by taking audio and video bit rate adding 2%
53 if transcode
.tivo_compatable(full_path
, tsn
):
54 # Is TiVo-compatible mpeg2
55 return int(os
.stat(full_path
).st_size
)
58 audioBPS
= config
.strtod(config
.getAudioBR(tsn
))
59 videoBPS
= config
.strtod(config
.getVideoBR(tsn
))
60 bitrate
= audioBPS
+ videoBPS
61 return int((self
.__duration
(full_path
) / 1000) *
64 def __getMetadataFromTxt(self
, full_path
):
67 default_file
= os
.path
.join(os
.path
.split(full_path
)[0], 'default.txt')
68 description_file
= full_path
+ '.txt'
70 metadata
.update(self
.__getMetadataFromFile
(default_file
))
71 metadata
.update(self
.__getMetadataFromFile
(description_file
))
75 def __getMetadataFromFile(self
, file):
78 if os
.path
.exists(file):
79 for line
in open(file):
80 if line
.strip().startswith('#'):
85 key
, value
= line
.split(':', 1)
89 if key
.startswith('v'):
91 metadata
[key
].append(value
)
93 metadata
[key
] = [value
]
99 def __metadata(self
, full_path
, tsn
=''):
102 base_path
, title
= os
.path
.split(full_path
)
104 originalAirDate
= datetime
.fromtimestamp(os
.stat(full_path
).st_ctime
)
105 duration
= self
.__duration
(full_path
)
106 duration_delta
= timedelta(milliseconds
= duration
)
108 metadata
['title'] = '.'.join(title
.split('.')[:-1])
109 metadata
['seriesTitle'] = metadata
['title'] # default to the filename
110 metadata
['originalAirDate'] = originalAirDate
.isoformat()
111 metadata
['time'] = now
.isoformat()
112 metadata
['startTime'] = now
.isoformat()
113 metadata
['stopTime'] = (now
+ duration_delta
).isoformat()
115 metadata
.update( self
.__getMetadataFromTxt
(full_path
) )
117 metadata
['size'] = self
.__est
_size
(full_path
, tsn
)
118 metadata
['duration'] = duration
120 min = duration_delta
.seconds
/ 60
121 sec
= duration_delta
.seconds
% 60
124 metadata
['iso_duration'] = 'P' + str(duration_delta
.days
) + \
125 'DT' + str(hours
) + 'H' + str(min) + \
129 def QueryContainer(self
, handler
, query
):
130 tsn
= handler
.headers
.getheader('tsn', '')
131 subcname
= query
['Container'][0]
132 cname
= subcname
.split('/')[0]
134 if not handler
.server
.containers
.has_key(cname
) or \
135 not self
.get_local_path(handler
, query
):
136 handler
.send_response(404)
137 handler
.end_headers()
140 files
, total
, start
= self
.get_files(handler
, query
,
141 self
.video_file_filter
)
144 local_base_path
= self
.get_local_base_path(handler
, query
)
146 video
= VideoDetails()
147 video
['name'] = os
.path
.split(file)[1]
149 video
['part_path'] = file.replace(local_base_path
, '', 1)
150 video
['title'] = os
.path
.split(file)[1]
151 video
['is_dir'] = self
.__isdir
(file)
152 if not video
['is_dir']:
153 video
.update(self
.__metadata
(file, tsn
))
157 handler
.send_response(200)
158 handler
.end_headers()
159 t
= Template(file=os
.path
.join(SCRIPTDIR
,'templates', 'container.tmpl'))
167 handler
.wfile
.write(t
)
169 def TVBusQuery(self
, handler
, query
):
170 tsn
= handler
.headers
.getheader('tsn', '')
171 file = query
['File'][0]
172 path
= self
.get_local_path(handler
, query
)
173 file_path
= path
+ file
175 file_info
= VideoDetails()
176 file_info
.update(self
.__metadata
(file_path
, tsn
))
178 handler
.send_response(200)
179 handler
.end_headers()
180 t
= Template(file=os
.path
.join(SCRIPTDIR
,'templates', 'TvBus.tmpl'))
183 handler
.wfile
.write(t
)
185 class VideoDetails(DictMixin
):
187 def __init__(self
, d
=None):
193 def __getitem__(self
, key
):
194 if key
not in self
.d
:
195 self
.d
[key
] = self
.default(key
)
198 def __contains__(self
, key
):
201 def __setitem__(self
, key
, value
):
204 def __delitem__(self
):
211 return self
.d
.__iter
__()
214 return self
.d
.iteritems()
216 def default(self
, key
):
219 'episodeNumber' : '0',
220 'displayMajorNumber' : '0',
221 'displayMinorNumber' : '0',
222 'isEpisode' : 'true',
223 'colorCode' : ('COLOR', '4'),
224 'showType' : ('SERIES', '5'),
225 'tvRating' : ('NR', '7')
229 elif key
.startswith('v'):