1 import transcode
, os
, socket
, re
2 from Cheetah
.Template
import Template
3 from plugin
import Plugin
4 from urllib
import unquote_plus
, quote
, unquote
5 from urlparse
import urlparse
6 from xml
.sax
.saxutils
import escape
7 from lrucache
import LRUCache
8 from UserDict
import DictMixin
9 from datetime
import datetime
, timedelta
12 SCRIPTDIR
= os
.path
.dirname(__file__
)
18 CONTENT_TYPE
= 'x-container/tivo-videos'
20 def send_file(self
, handler
, container
, name
):
22 #No longer a 'cheep' hack :p
23 if handler
.headers
.getheader('Range') and not handler
.headers
.getheader('Range') == 'bytes=0-':
24 handler
.send_response(206)
25 handler
.send_header('Connection', 'close')
26 handler
.send_header('Content-Type', 'video/x-tivo-mpeg')
27 handler
.send_header('Transfer-Encoding', 'chunked')
28 handler
.send_header('Server', 'TiVo Server/1.4.257.475')
30 handler
.wfile
.write("\x30\x0D\x0A")
33 tsn
= handler
.headers
.getheader('tsn', '')
35 o
= urlparse("http://fake.host" + handler
.path
)
36 path
= unquote_plus(o
[2])
37 handler
.send_response(200)
39 transcode
.output_video(container
['path'] + path
[len(name
)+1:], handler
.wfile
, tsn
)
42 def __isdir(self
, full_path
):
43 return os
.path
.isdir(full_path
)
45 def __duration(self
, full_path
):
46 return transcode
.video_info(full_path
)[4]
48 def __est_size(self
, full_path
):
49 #Size is estimated by taking audio and video bit rate adding 2%
51 if transcode
.tivo_compatable(full_path
): # Is TiVo compatible mpeg2
52 return int(os
.stat(full_path
).st_size
)
53 else: # Must be re-encoded
54 audioBPS
= strtod(config
.getAudioBR())
55 videoBPS
= strtod(config
.getVideoBR())
56 bitrate
= audioBPS
+ videoBPS
57 return int((self
.__duration
(full_path
)/1000)*(bitrate
* 1.02 / 8))
59 def __getMetadateFromTxt(self
, full_path
):
62 description_file
= full_path
+ '.txt'
63 if os
.path
.exists(description_file
):
64 for line
in open(description_file
):
65 if line
.strip().startswith('#'):
70 key
, value
= line
.split(':', 1)
74 if key
.startswith('v'):
76 metadata
[key
].append(value
)
78 metadata
[key
] = [value
]
84 def __metadata(self
, full_path
):
88 base_path
, title
= os
.path
.split(full_path
)
90 originalAirDate
= datetime
.fromtimestamp(os
.stat(full_path
).st_ctime
)
91 duration
= self
.__duration
(full_path
)
92 duration_delta
= timedelta(milliseconds
= duration
)
94 metadata
['title'] = '.'.join(title
.split('.')[:-1])
95 metadata
['seriesTitle'] = os
.path
.split(base_path
)[1]
96 metadata
['originalAirDate'] = originalAirDate
.isoformat()
97 metadata
['time'] = now
.isoformat()
98 metadata
['startTime'] = now
.isoformat()
99 metadata
['stopTime'] = (now
+ duration_delta
).isoformat()
101 metadata
.update( self
.__getMetadateFromTxt
(full_path
) )
103 metadata
['size'] = self
.__est
_size
(full_path
)
104 metadata
['duration'] = duration
106 min = duration_delta
.seconds
/ 60
107 sec
= duration_delta
.seconds
% 60
110 metadata
['iso_durarion'] = 'P' + str(duration_delta
.days
) + 'DT' + str(hours
) + 'H' + str(min) + 'M' + str(sec
) + 'S'
114 def QueryContainer(self
, handler
, query
):
116 subcname
= query
['Container'][0]
117 cname
= subcname
.split('/')[0]
119 if not handler
.server
.containers
.has_key(cname
) or not self
.get_local_path(handler
, query
):
120 handler
.send_response(404)
121 handler
.end_headers()
124 def video_file_filter(file):
125 path
= self
.get_local_path(handler
, query
)
126 full_path
= os
.path
.join(path
, file)
127 if os
.path
.isdir(full_path
):
129 return transcode
.suported_format(full_path
)
131 files
, total
, start
= self
.get_files(handler
, query
, video_file_filter
)
135 path
= self
.get_local_path(handler
, query
)
136 full_path
= os
.path
.join(path
, file)
138 video
= VideoDetails()
140 video
['title'] = file
141 video
['is_dir'] = self
.__isdir
(full_path
)
142 if not video
['is_dir']:
143 video
['title'] = '.'.join(file.split('.')[:-1])
144 video
.update(self
.__metadata
(full_path
))
148 handler
.send_response(200)
149 handler
.end_headers()
150 t
= Template(file=os
.path
.join(SCRIPTDIR
,'templates', 'container.tmpl'))
157 handler
.wfile
.write(t
)
159 def TVBusQuery(self
, handler
, query
):
161 file = query
['File'][0]
162 path
= self
.get_local_path(handler
, query
)
163 file_path
= os
.path
.join(path
, file)
166 file_info
= VideoDetails()
167 file_info
.update(self
.__metadata
(file_path
))
171 handler
.send_response(200)
172 handler
.end_headers()
173 t
= Template(file=os
.path
.join(SCRIPTDIR
,'templates', 'TvBus.tmpl'))
175 handler
.wfile
.write(t
)
177 class VideoDetails(DictMixin
):
179 def __init__(self
, d
= None):
185 def __getitem__(self
, key
):
186 if key
not in self
.d
:
187 self
.d
[key
] = self
.default(key
)
190 def __contains__(self
, key
):
193 def __setitem__(self
, key
, value
):
196 def __delitem__(self
):
203 return self
.d
.__iter
__()
206 return self
.d
.iteritems()
208 def default(self
, key
):
211 'episodeNumber' : '0',
212 'displayMajorNumber' : '0',
213 'displayMinorNumber' : '0',
214 'isEpisode' : 'true',
215 'colorCode' : ('COLOR', '4'),
216 'showType' : ('SERIES', '5'),
217 'tvRating' : ('NR', '7'),
221 elif key
.startswith('v'):
222 return [key
+ '1', key
+ '2']
227 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
228 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
229 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
231 prefixes
= {"y":-24,"z":-21,"a":-18,"f":-15,"p":-12,"n":-9,"u":-6,"m":-3,"c":-2,"d":-1,"h":2,"k":3,"K":3,"M":6,"G":9,"T":12,"P":15,"E":18,"Z":21,"Y":24}
232 p
= re
.compile(r
'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
235 raise SyntaxError('Invalid bit value syntax')
236 (coef
, prefix
, power
, byte
) = m
.groups()
240 exponent
= float(prefixes
[prefix
])
243 value
= float(coef
) * pow(2.0, exponent
/0.3)
246 value
= float(coef
) * pow(10.0, exponent
)
247 if byte
== "B": # B==Byte, b=bit