1 import time
, os
, BaseHTTPServer
, SocketServer
, socket
, re
2 from urllib
import unquote_plus
, quote
, unquote
3 from urlparse
import urlparse
4 from cgi
import parse_qs
5 from Cheetah
.Template
import Template
6 from plugin
import GetPlugin
8 from xml
.sax
.saxutils
import escape
10 SCRIPTDIR
= os
.path
.dirname(__file__
)
12 class TivoHTTPServer(SocketServer
.ThreadingMixIn
, BaseHTTPServer
.HTTPServer
):
15 def __init__(self
, server_address
, RequestHandlerClass
):
16 BaseHTTPServer
.HTTPServer
.__init
__(self
, server_address
,
18 self
.daemon_threads
= True
20 def add_container(self
, name
, settings
):
21 if self
.containers
.has_key(name
) or name
== 'TiVoConnect':
22 raise "Container Name in use"
23 settings
['content_type'] = GetPlugin(settings
['type']).CONTENT_TYPE
24 self
.containers
[name
] = settings
26 class TivoHTTPHandler(BaseHTTPServer
.BaseHTTPRequestHandler
):
28 def address_string(self
):
29 host
, port
= self
.client_address
[:2]
34 basepath
= unquote_plus(self
.path
).split('/')[1]
37 for name
, container
in self
.server
.containers
.items():
39 plugin
= GetPlugin(container
['type'])
40 plugin
.send_file(self
, container
, name
)
43 ## Not a file not a TiVo command fuck them
44 if not self
.path
.startswith('/TiVoConnect'):
48 o
= urlparse("http://fake.host" + self
.path
)
49 query
= parse_qs(o
[4])
52 if query
.has_key('Command') and len(query
['Command']) >= 1:
54 command
= query
['Command'][0]
56 # If we are looking at the root container
57 if command
== "QueryContainer" and \
58 (not query
.has_key('Container') or query
['Container'][0] == '/'):
62 if query
.has_key('Container'):
63 # Dispatch to the container plugin
64 for name
, container
in self
.server
.containers
.items():
65 if query
['Container'][0].startswith(name
):
66 plugin
= GetPlugin(container
['type'])
67 if hasattr(plugin
,command
):
68 method
= getattr(plugin
, command
)
71 self
.unsupported(query
)
74 self
.unsupported(query
)
76 def root_container(self
):
77 tsn
= self
.headers
.getheader('TiVo_TCD_ID', '')
78 tsnshares
= config
.getShares(tsn
)
80 for section
, settings
in tsnshares
:
81 settings
['content_type'] = GetPlugin(settings
['type']).CONTENT_TYPE
82 tsncontainers
[section
] = settings
83 t
= Template(file=os
.path
.join(SCRIPTDIR
, 'templates',
84 'root_container.tmpl'))
85 t
.containers
= tsncontainers
86 t
.hostname
= socket
.gethostname()
88 self
.send_response(200)
93 self
.send_response(200)
94 self
.send_header('Content-type', 'text/html')
96 t
= Template(file=os
.path
.join(SCRIPTDIR
, 'templates',
101 def unsupported(self
, query
):
102 self
.send_response(404)
103 self
.send_header('Content-type', 'text/html')
105 t
= Template(file=os
.path
.join(SCRIPTDIR
, 'templates',
110 if __name__
== '__main__':
112 httpd
= TivoHTTPServer(('', 9032), TivoHTTPHandler
)
113 httpd
.add_container('test', 'x-container/tivo-videos',
114 r
'C:\Documents and Settings\Armooo\Desktop\pyTivo\test')
115 httpd
.serve_forever()