7ff793542eb05da9478af48421f28152823dedf5
1 import os
, socket
, re
, sys
, ConfigParser
, config
, time
2 import urllib2
, cookielib
, thread
, buildhelp
3 from xml
.dom
import minidom
4 from ConfigParser
import NoOptionError
5 from Cheetah
.Template
import Template
6 from plugin
import Plugin
7 from urllib
import unquote_plus
, quote
, unquote
8 from urlparse
import urlparse
9 from xml
.sax
.saxutils
import escape
10 from lrucache
import LRUCache
13 SCRIPTDIR
= os
.path
.dirname(__file__
)
17 p
= os
.path
.dirname(__file__
)
18 p
= p
.split(os
.path
.sep
)
21 p
= os
.path
.sep
.join(p
)
22 config_file_path
= os
.path
.join(p
, 'pyTivo.conf')
24 status
= {} #Global variable to control download threads
25 tivo_cache
= {} #Cache of TiVo NPL
28 CONTENT_TYPE
= 'text/html'
30 def Reset(self
, handler
, query
):
32 handler
.server
.reset()
33 if 'last_page' in query
:
34 last_page
= query
['last_page'][0]
38 subcname
= query
['Container'][0]
39 cname
= subcname
.split('/')[0]
40 handler
.send_response(200)
42 t
= Template(file=os
.path
.join(SCRIPTDIR
,'templates', 'redirect.tmpl'))
45 t
.url
= '/TiVoConnect?Command='+ last_page
+'&Container=' + cname
46 t
.text
= '<h3>The pyTivo Server has been soft reset.</h3> <br>pyTivo has reloaded the pyTivo.conf'+\
47 'file and all changed should now be in effect. <br> The'+ \
48 '<a href="/TiVoConnect?Command='+ last_page
+'&Container='+ cname
+'"> previous</a> page will reload in 3 seconds.'
49 handler
.wfile
.write(t
)
50 debug
.debug_write(__name__
, debug
.fn_attr(), ['The pyTivo Server has been soft reset.'])
51 debug
.print_conf(__name__
, debug
.fn_attr())
53 def Admin(self
, handler
, query
):
54 #Read config file new each time in case there was any outside edits
55 config
= ConfigParser
.ConfigParser()
56 config
.read(config_file_path
)
59 for section
in config
.sections():
60 if not(section
.startswith('_tivo_') or section
.startswith('Server')):
61 if not(config
.has_option(section
,'type')):
62 shares_data
.append((section
, dict(config
.items(section
, raw
=True))))
63 elif config
.get(section
,'type').lower() != 'admin':
64 shares_data
.append((section
, dict(config
.items(section
, raw
=True))))
66 subcname
= query
['Container'][0]
67 cname
= subcname
.split('/')[0]
68 handler
.send_response(200)
70 t
= Template(file=os
.path
.join(SCRIPTDIR
,'templates', 'settings.tmpl'))
72 t
.server_data
= dict(config
.items('Server', raw
=True))
73 t
.server_known
= buildhelp
.getknown('server')
74 t
.shares_data
= shares_data
75 t
.shares_known
= buildhelp
.getknown('shares')
76 t
.tivos_data
= [ (section
, dict(config
.items(section
, raw
=True))) for section
in config
.sections() \
77 if section
.startswith('_tivo_')]
78 t
.tivos_known
= buildhelp
.getknown('tivos')
79 t
.help_list
= buildhelp
.gethelp()
80 handler
.wfile
.write(t
)
82 def UpdateSettings(self
, handler
, query
):
83 config
= ConfigParser
.ConfigParser()
84 config
.read(config_file_path
)
86 if key
.startswith('Server.'):
87 section
, option
= key
.split('.')
88 if option
== "new__setting":
89 new_setting
= query
[key
][0]
91 if option
== "new__value":
92 new_value
= query
[key
][0]
94 if query
[key
][0] == " ":
95 config
.remove_option(section
, option
)
97 config
.set(section
, option
, query
[key
][0])
98 if not(new_setting
== ' ' and new_value
== ' '):
99 config
.set('Server', new_setting
, new_value
)
101 sections
= query
['Section_Map'][0].split(']')
102 sections
.pop() #last item is junk
103 for section
in sections
:
104 ID
, name
= section
.split('|')
105 if query
[ID
][0] == "Delete_Me":
106 config
.remove_section(name
)
108 if query
[ID
][0] != name
:
109 config
.remove_section(name
)
110 config
.add_section(query
[ID
][0])
112 if key
.startswith(ID
+ '.'):
113 junk
, option
= key
.split('.')
114 if option
== "new__setting":
115 new_setting
= query
[key
][0]
117 if option
== "new__value":
118 new_value
= query
[key
][0]
120 if query
[key
][0] == " ":
121 config
.remove_option(query
[ID
][0], option
)
123 config
.set(query
[ID
][0], option
, query
[key
][0])
124 if not(new_setting
== ' ' and new_value
== ' '):
125 config
.set(query
[ID
][0], new_setting
, new_value
)
126 if query
['new_Section'][0] != " ":
127 config
.add_section(query
['new_Section'][0])
128 f
= open(config_file_path
, "w")
132 subcname
= query
['Container'][0]
133 cname
= subcname
.split('/')[0]
134 handler
.send_response(200)
135 handler
.end_headers()
136 t
= Template(file=os
.path
.join(SCRIPTDIR
,'templates', 'redirect.tmpl'))
139 t
.url
= '/TiVoConnect?Command=Admin&Container=' + cname
140 t
.text
= '<h3>Your Settings have been saved.</h3> <br>You settings have been saved to the pyTivo.conf file.'+\
141 'However you will need to do a <b>Soft Reset</b> before these changes will take effect.'+\
142 '<br> The <a href="/TiVoConnect?Command=Admin&Container='+ cname
+'"> Admin</a> page will reload in 10 seconds.'
143 handler
.wfile
.write(t
)
145 def NPL(self
, handler
, query
):
146 shows_per_page
= 50 #Change this to alter the number of shows returned per page
147 subcname
= query
['Container'][0]
148 cname
= subcname
.split('/')[0]
152 for name
, data
in config
.getShares():
154 if 'tivo_mak' in data
:
155 tivo_mak
= data
['tivo_mak']
158 if 'togo_path' in data
:
159 togo_path
= data
['togo_path']
164 tivoIP
= query
['TiVo'][0]
165 theurl
= 'https://'+ tivoIP
+'/TiVoConnect?Command=QueryContainer&ItemCount='+ str(shows_per_page
) +'&Container=/NowPlaying'
166 if 'Folder' in query
:
167 folder
+= str(query
['Folder'][0])
168 theurl
+= '/' + folder
169 if 'AnchorItem' in query
:
170 AnchorItem
+= str(query
['AnchorItem'][0])
171 theurl
+= '&AnchorItem=' + quote(AnchorItem
)
172 if 'AnchorOffset' in query
:
173 AnchorOffset
+= str(query
['AnchorOffset'][0])
174 theurl
+= '&AnchorOffset=' + AnchorOffset
176 password
= tivo_mak
#TiVo MAK
178 r
=urllib2
.Request(theurl
)
179 auth_handler
= urllib2
.HTTPDigestAuthHandler()
180 auth_handler
.add_password('TiVo DVR', tivoIP
, 'tivo', password
)
181 opener
= urllib2
.build_opener(auth_handler
)
182 urllib2
.install_opener(opener
)
184 if theurl
in tivo_cache
: #check to see if we have accessed this page before
185 if tivo_cache
[theurl
]['thepage'] == '' or (time
.time() - tivo_cache
[theurl
]['thepage_time']) >= 60: #if page is empty or old then retreive it
187 handle
= urllib2
.urlopen(r
)
189 handler
.send_response(200)
190 handler
.end_headers()
191 t
= Template(file=os
.path
.join(SCRIPTDIR
,'templates', 'redirect.tmpl'))
194 t
.url
= '/TiVoConnect?Command=NPL&Container=' + cname
195 t
.text
= '<h3>Unable to Connect to TiVo.</h3> <br>pyTivo was unable to connect to the TiVo at ' + tivoIP
+\
196 '<br>This most likely caused by an incorrect Media Access Key. Please return to the ToGo page and double check your Media Access Key.' +\
197 '<br> The <a href="/TiVoConnect?Command=NPL&Container='+ cname
+ '"> ToGo</a> page will reload in 20 seconds.'
198 handler
.wfile
.write(t
)
200 tivo_cache
[theurl
]['thepage'] = handle
.read()
201 tivo_cache
[theurl
]['thepage_time'] = time
.time()
204 handle
= urllib2
.urlopen(r
)
206 handler
.send_response(200)
207 handler
.end_headers()
208 t
= Template(file=os
.path
.join(SCRIPTDIR
,'templates', 'redirect.tmpl'))
211 t
.url
= '/TiVoConnect?Command=NPL&Container=' + cname
212 t
.text
= '<h3>Unable to Connect to TiVo.</h3> <br>pyTivo was unable to connect to the TiVo at ' + tivoIP
+\
213 '<br>This most likely caused by an incorrect Media Access Key. Please return to the ToGo page and double check your Media Access Key.' +\
214 '<br> The <a href="/TiVoConnect?Command=NPL&Container='+ cname
+ '"> ToGo</a> page will reload in 20 seconds.'
215 handler
.wfile
.write(t
)
217 tivo_cache
[theurl
] = {}
218 tivo_cache
[theurl
]['thepage'] = handle
.read()
219 tivo_cache
[theurl
]['thepage_time'] = time
.time()
221 xmldoc
= minidom
.parseString(tivo_cache
[theurl
]['thepage'])
222 items
= xmldoc
.getElementsByTagName('Item')
223 TotalItems
= xmldoc
.getElementsByTagName('Details')[0].getElementsByTagName('TotalItems')[0].firstChild
.data
224 ItemStart
= xmldoc
.getElementsByTagName('ItemStart')[0].firstChild
.data
225 ItemCount
= xmldoc
.getElementsByTagName('ItemCount')[0].firstChild
.data
226 FirstAnchor
= items
[0].getElementsByTagName("Links")[0].getElementsByTagName("Content")[0].getElementsByTagName("Url")[0].firstChild
.data
231 entry
['Title'] = item
.getElementsByTagName("Title")[0].firstChild
.data
232 entry
['ContentType'] = item
.getElementsByTagName("ContentType")[0].firstChild
.data
233 if (len(item
.getElementsByTagName("UniqueId")) >= 1):
234 entry
['UniqueId'] = item
.getElementsByTagName("UniqueId")[0].firstChild
.data
235 if entry
['ContentType'] == 'x-tivo-container/folder':
236 entry
['TotalItems'] = item
.getElementsByTagName("TotalItems")[0].firstChild
.data
237 entry
['LastChangeDate'] = item
.getElementsByTagName("LastChangeDate")[0].firstChild
.data
238 entry
['LastChangeDate'] = time
.strftime("%b %d, %Y", time
.localtime(int(entry
['LastChangeDate'], 16)))
240 link
= item
.getElementsByTagName("Links")[0]
241 if (len(link
.getElementsByTagName("CustomIcon")) >= 1):
242 entry
['Icon'] = link
.getElementsByTagName("CustomIcon")[0].getElementsByTagName("Url")[0].firstChild
.data
243 if (len(link
.getElementsByTagName("Content")) >= 1):
244 entry
['Url'] = link
.getElementsByTagName("Content")[0].getElementsByTagName("Url")[0].firstChild
.data
245 parse_url
= urlparse(entry
['Url'])
246 entry
['Url'] = quote('http://' + parse_url
[1].split(':')[0] + parse_url
[2] + "?" + parse_url
[4])
247 keys
= ['SourceSize', 'Duration', 'CaptureDate', 'EpisodeTitle', 'Description', 'SourceChannel', 'SourceStation']
250 entry
[key
] = item
.getElementsByTagName(key
)[0].firstChild
.data
253 entry
['SourceSize'] = "%.3f GB" % float(float(entry
['SourceSize'])/(1024*1024*1024))
254 entry
['Duration'] = str(int(entry
['Duration'])/(60*60*1000)).zfill(2) + ':' \
255 + str((int(entry
['Duration'])%(60*60*1000))/(60*1000)).zfill(2) + ':' \
256 + str((int(entry
['Duration'])/1000)%60).zfill(2)
257 entry
['CaptureDate'] = time
.strftime("%b %d, %Y", time
.localtime(int(entry
['CaptureDate'], 16)))
268 subcname
= query
['Container'][0]
269 cname
= subcname
.split('/')[0]
270 handler
.send_response(200)
271 handler
.send_header('Content-Type', 'text/html; charset=UTF-8')
272 handler
.end_headers()
273 t
= Template(file=os
.path
.join(SCRIPTDIR
,'templates', 'npl.tmpl'))
276 t
.tivo_mak
= tivo_mak
277 t
.togo_path
= togo_path
278 t
.tivos
= handler
.tivos
284 t
.TotalItems
= int(TotalItems
)
285 t
.ItemStart
= int(ItemStart
)
286 t
.ItemCount
= int(ItemCount
)
287 t
.FirstAnchor
= quote(FirstAnchor
)
288 t
.shows_per_page
= shows_per_page
289 t
.redirect
= quote(unquote_plus(handler
.path
).split('/')[1])
290 handler
.wfile
.write(unicode(t
).encode('utf-8'))
292 def get_tivo_file(self
, url
, mak
, tivoIP
, outfile
):
294 cj
= cookielib
.LWPCookieJar()
296 r
=urllib2
.Request(url
)
297 auth_handler
= urllib2
.HTTPDigestAuthHandler()
298 auth_handler
.add_password('TiVo DVR', tivoIP
, 'tivo', mak
)
299 opener
= urllib2
.build_opener(urllib2
.HTTPCookieProcessor(cj
), auth_handler
)
300 urllib2
.install_opener(opener
)
303 handle
= urllib2
.urlopen(r
)
305 #If we get "Too many transfers error" try a second time. For some reason
306 #urllib2 does not properly close connections when a transfer is canceled.
309 handle
= urllib2
.urlopen(r
)
311 status
[url
]['running'] = False
312 status
[url
]['error'] = e
.code
315 status
[url
]['running'] = False
316 status
[url
]['error'] = e
.code
319 f
= open(outfile
, 'wb')
321 start_time
= time
.time()
322 output
= handle
.read(1024)
323 while status
[url
]['running'] and output
!= '':
326 if ((time
.time() - start_time
) >= 5):
327 status
[url
]['rate'] = int(kilobytes
/(time
.time() - start_time
))
329 start_time
= time
.time()
330 output
= handle
.read(1024)
331 status
[url
]['running'] = False
336 def ToGo(self
, handler
, query
):
337 subcname
= query
['Container'][0]
338 cname
= subcname
.split('/')[0]
339 for name
, data
in config
.getShares():
341 if 'tivo_mak' in data
:
342 tivo_mak
= data
['tivo_mak']
345 if 'togo_path' in data
:
346 togo_path
= data
['togo_path']
349 if tivo_mak
!= "" and togo_path
!= "":
350 parse_url
= urlparse(str(query
['Url'][0]))
351 theurl
= 'http://' + parse_url
[1].split(':')[0] + parse_url
[2] + "?" + parse_url
[4]
352 password
= tivo_mak
#TiVo MAK
353 tivoIP
= query
['TiVo'][0]
354 name
= unquote(parse_url
[2])[10:300].split('.')
355 name
.insert(-1," - " + unquote(parse_url
[4]).split("id=")[1] + ".")
356 outfile
= os
.path
.join(togo_path
, "".join(name
))
358 status
[theurl
] = {'running':True, 'error':'', 'rate':'', 'finished':False}
360 thread
.start_new_thread(Admin
.get_tivo_file
, (self
, theurl
, password
, tivoIP
, outfile
))
362 handler
.send_response(200)
363 handler
.end_headers()
364 t
= Template(file=os
.path
.join(SCRIPTDIR
,'templates', 'redirect.tmpl'))
367 t
.url
= '/'+ query
['Redirect'][0]
368 t
.text
= '<h3>Transfer Initiated.</h3> <br>You selected transfer has been initiated.'+\
369 '<br> The <a href="/'+ query
['Redirect'][0] +'"> ToGo</a> page will reload in 3 seconds.'
370 handler
.wfile
.write(t
)
372 handler
.send_response(200)
373 handler
.end_headers()
374 t
= Template(file=os
.path
.join(SCRIPTDIR
,'templates', 'redirect.tmpl'))
377 t
.url
= '/'+ query
['Redirect'][0]
378 t
.text
= '<h3>Missing Data.</h3> <br>You must set both "tivo_mak" and "togo_path" before using this function.'+\
379 '<br> The <a href="/'+ query
['Redirect'][0] +'"> ToGo</a> page will reload in 10 seconds.'
380 handler
.wfile
.write(t
)
382 def ToGoStop(self
, handler
, query
):
383 parse_url
= urlparse(str(query
['Url'][0]))
384 theurl
= 'http://' + parse_url
[1].split(':')[0] + parse_url
[2] + "?" + parse_url
[4]
386 status
[theurl
]['running'] = False
388 subcname
= query
['Container'][0]
389 cname
= subcname
.split('/')[0]
390 handler
.send_response(200)
391 handler
.end_headers()
392 t
= Template(file=os
.path
.join(SCRIPTDIR
,'templates', 'redirect.tmpl'))
395 t
.url
= '/'+ query
['Redirect'][0]
396 t
.text
= '<h3>Transfer Stopped.</h3> <br>Your transfer has been stopped.'+\
397 '<br> The <a href="/'+ query
['Redirect'][0] +'"> ToGo</a> page will reload in 3 seconds.'
398 handler
.wfile
.write(t
)
401 def SaveNPL(self
, handler
, query
):
402 config
= ConfigParser
.ConfigParser()
403 config
.read(config_file_path
)
404 if 'tivo_mak' in query
:
405 config
.set(query
['Container'][0], 'tivo_mak', query
['tivo_mak'][0])
406 if 'togo_path' in query
:
407 config
.set(query
['Container'][0], 'togo_path', query
['togo_path'][0])
408 f
= open(config_file_path
, "w")
412 subcname
= query
['Container'][0]
413 cname
= subcname
.split('/')[0]
414 handler
.send_response(200)
415 handler
.end_headers()
416 t
= Template(file=os
.path
.join(SCRIPTDIR
,'templates', 'redirect.tmpl'))
419 t
.url
= '/TiVoConnect?last_page=NPL&Command=Reset&Container=' + cname
420 t
.text
= '<h3>Your Settings have been saved.</h3> <br>You settings have been saved to the pyTivo.conf file.'+\
421 'pyTivo will now do a <b>Soft Reset</b> to allow these changes to take effect.'+\
422 '<br> The <a href="/TiVoConnect?last_page=NPL&Command=Reset&Container='+ cname
+'"> Reset</a> will occur in 2 seconds.'
423 handler
.wfile
.write(t
)