9 from urllib
import quote
, unquote
10 from xml
.dom
import minidom
11 from xml
.sax
.saxutils
import escape
13 from Cheetah
.Template
import Template
17 from plugin
import EncodeUnicode
, Plugin
19 logger
= logging
.getLogger('pyTivo.togo')
20 tag_data
= metadata
.tag_data
22 SCRIPTDIR
= os
.path
.dirname(__file__
)
26 # Some error/status message templates
28 MISSING
= """<h3>Missing Data</h3> <p>You must set both "tivo_mak" and
29 "togo_path" before using this function.</p>"""
31 TRANS_QUEUE
= """<h3>Queued for Transfer</h3> <p>%s</p> <p>queued for
32 transfer to:</p> <p>%s</p>"""
34 TRANS_STOP
= """<h3>Transfer Stopped</h3> <p>Your transfer of:</p>
35 <p>%s</p> <p>has been stopped.</p>"""
37 UNQUEUE
= """<h3>Removed from Queue</h3> <p>%s</p> <p>has been removed
38 from the queue.</p>"""
40 UNABLE
= """<h3>Unable to Connect to TiVo</h3> <p>pyTivo was unable to
41 connect to the TiVo at %s.</p> <p>This is most likely caused by an
42 incorrect Media Access Key. Please return to the Settings page and
43 double check your <b>tivo_mak</b> setting.</p>"""
45 # Preload the templates
46 tnname
= os
.path
.join(SCRIPTDIR
, 'templates', 'npl.tmpl')
47 NPL_TEMPLATE
= file(tnname
, 'rb').read()
49 status
= {} # Global variable to control download threads
50 tivo_cache
= {} # Cache of TiVo NPL
51 queue
= {} # Recordings to download -- list per TiVo
52 basic_meta
= {} # Data from NPL, parsed, indexed by progam URL
54 def null_cookie(name
, value
):
55 return cookielib
.Cookie(0, name
, value
, None, False, '', False,
56 False, '', False, False, None, False, None, None, None)
58 auth_handler
= urllib2
.HTTPDigestAuthHandler()
59 cj
= cookielib
.CookieJar()
60 cj
.set_cookie(null_cookie('sid', 'ADEADDA7EDEBAC1E'))
61 tivo_opener
= urllib2
.build_opener(urllib2
.HTTPCookieProcessor(cj
),
65 CONTENT_TYPE
= 'text/html'
67 def tivo_open(self
, url
):
68 # Loop just in case we get a server busy message
71 # Open the URL using our authentication/cookie opener
72 return tivo_opener
.open(url
)
74 # Do a retry if the TiVo responds that the server is busy
75 except urllib2
.HTTPError
, e
:
80 # Throw the error otherwise
83 def NPL(self
, handler
, query
):
93 shows_per_page
= 50 # Change this to alter the number of shows returned
96 has_tivodecode
= bool(config
.get_bin('tivodecode'))
99 tivoIP
= query
['TiVo'][0]
100 tsn
= config
.tivos_by_ip(tivoIP
)
101 tivo_name
= config
.tivo_names
[tsn
]
102 tivo_mak
= config
.get_tsn('tivo_mak', tsn
)
103 theurl
= ('https://' + tivoIP
+
104 '/TiVoConnect?Command=QueryContainer&ItemCount=' +
105 str(shows_per_page
) + '&Container=/NowPlaying')
106 if 'Folder' in query
:
107 folder
+= query
['Folder'][0]
108 theurl
+= '/' + folder
109 if 'AnchorItem' in query
:
110 theurl
+= '&AnchorItem=' + quote(query
['AnchorItem'][0])
111 if 'AnchorOffset' in query
:
112 theurl
+= '&AnchorOffset=' + query
['AnchorOffset'][0]
114 if (theurl
not in tivo_cache
or
115 (time
.time() - tivo_cache
[theurl
]['thepage_time']) >= 60):
116 # if page is not cached or old then retreive it
117 auth_handler
.add_password('TiVo DVR', tivoIP
, 'tivo', tivo_mak
)
119 page
= self
.tivo_open(theurl
)
121 handler
.redir(UNABLE
% tivoIP
, 10)
123 tivo_cache
[theurl
] = {'thepage': minidom
.parse(page
),
124 'thepage_time': time
.time()}
127 xmldoc
= tivo_cache
[theurl
]['thepage']
128 items
= xmldoc
.getElementsByTagName('Item')
129 TotalItems
= tag_data(xmldoc
, 'TiVoContainer/Details/TotalItems')
130 ItemStart
= tag_data(xmldoc
, 'TiVoContainer/ItemStart')
131 ItemCount
= tag_data(xmldoc
, 'TiVoContainer/ItemCount')
132 title
= tag_data(xmldoc
, 'TiVoContainer/Details/Title')
134 FirstAnchor
= tag_data(items
[0], 'Links/Content/Url')
139 entry
['ContentType'] = tag_data(item
, 'Details/ContentType')
140 for tag
in ('CopyProtected', 'UniqueId'):
141 value
= tag_data(item
, 'Details/' + tag
)
144 if entry
['ContentType'] == 'x-tivo-container/folder':
145 entry
['Title'] = tag_data(item
, 'Details/Title')
146 entry
['TotalItems'] = tag_data(item
, 'Details/TotalItems')
147 lc
= tag_data(item
, 'Details/LastCaptureDate')
149 lc
= tag_data(item
, 'Details/LastChangeDate')
150 entry
['LastChangeDate'] = time
.strftime('%b %d, %Y',
151 time
.localtime(int(lc
, 16)))
153 keys
= {'Icon': 'Links/CustomIcon/Url',
154 'Url': 'Links/Content/Url',
155 'SourceSize': 'Details/SourceSize',
156 'Duration': 'Details/Duration',
157 'CaptureDate': 'Details/CaptureDate'}
159 value
= tag_data(item
, keys
[key
])
163 rawsize
= entry
['SourceSize']
164 entry
['SourceSize'] = metadata
.human_size(rawsize
)
166 dur
= getint(entry
['Duration']) / 1000
167 entry
['Duration'] = ( '%d:%02d:%02d' %
168 (dur
/ 3600, (dur
% 3600) / 60, dur
% 60) )
170 entry
['CaptureDate'] = time
.strftime('%b %d, %Y',
171 time
.localtime(int(entry
['CaptureDate'], 16)))
174 if url
in basic_meta
:
175 entry
.update(basic_meta
[url
])
177 basic_data
= metadata
.from_container(item
)
178 entry
.update(basic_data
)
179 basic_meta
[url
] = basic_data
190 t
= Template(NPL_TEMPLATE
, filter=EncodeUnicode
)
196 t
.queue
= queue
[tivoIP
]
197 t
.has_tivodecode
= has_tivodecode
200 t
.container
= handler
.cname
203 t
.TotalItems
= getint(TotalItems
)
204 t
.ItemStart
= getint(ItemStart
)
205 t
.ItemCount
= getint(ItemCount
)
206 t
.FirstAnchor
= quote(FirstAnchor
)
207 t
.shows_per_page
= shows_per_page
209 handler
.send_html(str(t
), refresh
='300')
211 def get_tivo_file(self
, tivoIP
, url
, mak
, togo_path
):
213 status
[url
].update({'running': True, 'queued': False})
215 parse_url
= urlparse
.urlparse(url
)
217 name
= unquote(parse_url
[2])[10:].split('.')
218 id = unquote(parse_url
[4]).split('id=')[1]
219 name
.insert(-1, ' - ' + id + '.')
220 if status
[url
]['decode']:
222 outfile
= os
.path
.join(togo_path
, ''.join(name
))
224 if status
[url
]['save']:
225 meta
= basic_meta
[url
]
226 details_url
= 'https://%s/TiVoVideoDetails?id=%s' % (tivoIP
, id)
228 handle
= self
.tivo_open(details_url
)
229 meta
.update(metadata
.from_details(handle
))
233 metafile
= open(outfile
+ '.txt', 'w')
234 metadata
.dump(metafile
, meta
)
237 auth_handler
.add_password('TiVo DVR', url
, 'tivo', mak
)
239 handle
= self
.tivo_open(url
)
240 except urllib2
.HTTPError
, e
:
241 status
[url
]['running'] = False
242 status
[url
]['error'] = e
.code
245 except urllib2
.URLError
, e
:
246 status
[url
]['running'] = False
247 status
[url
]['error'] = e
.reason
248 logger
.error(e
.reason
)
251 tivo_name
= config
.tivo_names
[config
.tivos_by_ip(tivoIP
)]
253 logger
.info('[%s] Start getting "%s" from %s' %
254 (time
.strftime('%d/%b/%Y %H:%M:%S'), outfile
, tivo_name
))
256 if status
[url
]['decode']:
257 tivodecode_path
= config
.get_bin('tivodecode')
258 tcmd
= [tivodecode_path
, '-m', mak
, '-o', outfile
, '-']
259 tivodecode
= subprocess
.Popen(tcmd
, stdin
=subprocess
.PIPE
,
260 bufsize
=(512 * 1024))
263 f
= open(outfile
, 'wb')
265 start_time
= time
.time()
266 last_interval
= start_time
269 while status
[url
]['running']:
270 output
= handle
.read(1024000)
273 length
+= len(output
)
276 elapsed
= now
- last_interval
278 status
[url
]['rate'] = '%.2f Mb/s' % (length
* 8.0 /
279 (elapsed
* 1024 * 1024))
280 status
[url
]['size'] += length
283 if status
[url
]['running']:
284 status
[url
]['finished'] = True
285 except Exception, msg
:
286 status
[url
]['running'] = False
290 status
[url
]['size'] += length
291 if status
[url
]['running']:
292 mega_elapsed
= (now
- start_time
) * 1024 * 1024
295 size
= status
[url
]['size']
296 rate
= size
* 8.0 / mega_elapsed
297 logger
.info('[%s] Done getting "%s" from %s, %d bytes, %.2f Mb/s' %
298 (time
.strftime('%d/%b/%Y %H:%M:%S'), outfile
,
299 tivo_name
, size
, rate
))
300 status
[url
]['running'] = False
303 if status
[url
]['save']:
304 os
.remove(outfile
+ '.txt')
305 logger
.info('[%s] Transfer of "%s" from %s aborted' %
306 (time
.strftime('%d/%b/%Y %H:%M:%S'), outfile
,
310 def process_queue(self
, tivoIP
, mak
, togo_path
):
313 url
= queue
[tivoIP
][0]
314 self
.get_tivo_file(tivoIP
, url
, mak
, togo_path
)
318 def ToGo(self
, handler
, query
):
319 togo_path
= config
.get_server('togo_path')
320 for name
, data
in config
.getShares():
321 if togo_path
== name
:
322 togo_path
= data
.get('path')
324 tivoIP
= query
['TiVo'][0]
325 tsn
= config
.tivos_by_ip(tivoIP
)
326 tivo_mak
= config
.get_tsn('tivo_mak', tsn
)
327 urls
= query
.get('Url', [])
328 decode
= 'decode' in query
329 save
= 'save' in query
331 status
[theurl
] = {'running': False, 'error': '', 'rate': '',
332 'queued': True, 'size': 0, 'finished': False,
333 'decode': decode
, 'save': save
}
335 queue
[tivoIP
].append(theurl
)
337 queue
[tivoIP
] = [theurl
]
338 thread
.start_new_thread(ToGo
.process_queue
,
339 (self
, tivoIP
, tivo_mak
, togo_path
))
340 logger
.info('[%s] Queued "%s" for transfer to %s' %
341 (time
.strftime('%d/%b/%Y %H:%M:%S'),
342 unquote(theurl
), togo_path
))
343 urlstring
= '<br>'.join([unquote(x
) for x
in urls
])
344 message
= TRANS_QUEUE
% (urlstring
, togo_path
)
347 handler
.redir(message
, 5)
349 def ToGoStop(self
, handler
, query
):
350 theurl
= query
['Url'][0]
351 status
[theurl
]['running'] = False
352 handler
.redir(TRANS_STOP
% unquote(theurl
))
354 def Unqueue(self
, handler
, query
):
355 theurl
= query
['Url'][0]
356 tivoIP
= query
['TiVo'][0]
358 queue
[tivoIP
].remove(theurl
)
359 logger
.info('[%s] Removed "%s" from queue' %
360 (time
.strftime('%d/%b/%Y %H:%M:%S'),
362 handler
.redir(UNQUEUE
% unquote(theurl
))