Add the GUID to the UniqueId -- allows accessing the same directories from
[pyTivo.git] / plugins / video / video.py
blobf798bff32639cf281c236548640d9dbf245759cb
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
9 import config
11 SCRIPTDIR = os.path.dirname(__file__)
13 CLASS_NAME = 'Video'
15 extfile = os.path.join(SCRIPTDIR, 'video.ext')
16 try:
17 extensions = file(extfile).read().split()
18 except:
19 extensions = None
21 class Video(Plugin):
23 CONTENT_TYPE = 'x-container/tivo-videos'
25 def video_file_filter(self, full_path, type=None):
26 if os.path.isdir(full_path):
27 return True
28 if extensions:
29 return os.path.splitext(full_path)[1].lower() in extensions
30 else:
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')
40 handler.end_headers()
41 handler.wfile.write("\x30\x0D\x0A")
42 return
44 tsn = handler.headers.getheader('tsn', '')
46 o = urlparse("http://fake.host" + handler.path)
47 path = unquote(o[2])
48 handler.send_response(200)
49 handler.end_headers()
50 transcode.output_video(container['path'] + path[len(name) + 1:],
51 handler.wfile, tsn)
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)
65 else:
66 # Must be re-encoded
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) *
71 (bitrate * 1.02 / 8))
73 def __getMetadataFromTxt(self, full_path):
74 metadata = {}
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))
82 return metadata
84 def __getMetadataFromFile(self, file):
85 metadata = {}
87 if os.path.exists(file):
88 for line in open(file):
89 if line.strip().startswith('#'):
90 continue
91 if not ':' in line:
92 continue
94 key, value = line.split(':', 1)
95 key = key.strip()
96 value = value.strip()
98 if key.startswith('v'):
99 if key in metadata:
100 metadata[key].append(value)
101 else:
102 metadata[key] = [value]
103 else:
104 metadata[key] = value
106 return metadata
108 def __metadata(self, full_path, tsn =''):
109 metadata = {}
111 base_path, title = os.path.split(full_path)
112 now = datetime.now()
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
131 hours = min / 60
132 min = min % 60
133 metadata['iso_duration'] = 'P' + str(duration_delta.days) + \
134 'DT' + str(hours) + 'H' + str(min) + \
135 'M' + str(sec) + 'S'
136 return metadata
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()
147 return
149 files, total, start = self.get_files(handler, query,
150 self.video_file_filter)
152 videos = []
153 local_base_path = self.get_local_base_path(handler, query)
154 for file in files:
155 video = VideoDetails()
156 video['name'] = os.path.split(file)[1]
157 video['path'] = file
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 video['small_path'] = subcname + '/' + video['name']
162 if not video['is_dir']:
163 video['valid'] = transcode.supported_format(file)
164 if video['valid']:
165 video.update(self.__metadata(file, tsn))
167 videos.append(video)
169 handler.send_response(200)
170 handler.end_headers()
171 t = Template(file=os.path.join(SCRIPTDIR,'templates', 'container.tmpl'))
172 t.container = cname
173 t.name = subcname
174 t.total = total
175 t.start = start
176 t.videos = videos
177 t.quote = quote
178 t.escape = escape
179 t.crc = zlib.crc32
180 t.guid = config.getGUID()
181 handler.wfile.write(t)
183 def TVBusQuery(self, handler, query):
184 tsn = handler.headers.getheader('tsn', '')
185 file = query['File'][0]
186 path = self.get_local_path(handler, query)
187 file_path = path + file
189 file_info = VideoDetails()
190 valid = transcode.supported_format(file_path)
191 if valid:
192 file_info.update(self.__metadata(file_path, tsn))
194 handler.send_response(200)
195 handler.end_headers()
196 t = Template(file=os.path.join(SCRIPTDIR,'templates', 'TvBus.tmpl'))
197 t.video = file_info
198 t.escape = escape
199 handler.wfile.write(t)
201 class VideoDetails(DictMixin):
203 def __init__(self, d=None):
204 if d:
205 self.d = d
206 else:
207 self.d = {}
209 def __getitem__(self, key):
210 if key not in self.d:
211 self.d[key] = self.default(key)
212 return self.d[key]
214 def __contains__(self, key):
215 return True
217 def __setitem__(self, key, value):
218 self.d[key] = value
220 def __delitem__(self):
221 del self.d[key]
223 def keys(self):
224 return self.d.keys()
226 def __iter__(self):
227 return self.d.__iter__()
229 def iteritems(self):
230 return self.d.iteritems()
232 def default(self, key):
233 defaults = {
234 'showingBits' : '0',
235 'episodeNumber' : '0',
236 'displayMajorNumber' : '0',
237 'displayMinorNumber' : '0',
238 'isEpisode' : 'true',
239 'colorCode' : ('COLOR', '4'),
240 'showType' : ('SERIES', '5'),
241 'tvRating' : ('NR', '7')
243 if key in defaults:
244 return defaults[key]
245 elif key.startswith('v'):
246 return []
247 else:
248 return ''