changed /web
[enigma2-plugins.git] / webinterface / src / plugin.py
1 from Plugins.Plugin import PluginDescriptor
2
3 from twisted.internet import reactor
4 from twisted.web2 import server, channel, static, resource, stream, http_headers, responsecode, http
5 from twisted.python import util
6 import webif
7 import os
8
9 sessions = [ ]
10
11 # set DEBUG to True, if twisted should write logoutput to a file.
12 DEBUG = False 
13 DEBUGFILE= "/tmp/twisted.log"
14
15 # Passwordprotection Test
16 # set it only to True, if you have a patched wrapper.py
17 # see http://twistedmatrix.com/trac/ticket/2041
18 # in /usr/lib/python2.4/site-packages/twisted/web2/auth/wrapper.py
19 # The solution is to change this line
20 #       
21 #       return self.authenticate(req), seg[1:]
22 # into this
23 #       return self.authenticate(req), seg
24 PASSWORDPROTECTION = False
25 PASSWORDPROTECTION_pwd = "root"
26 PASSWORDPROTECTION_mode = "sha"; 
27 # twisted supports more than sha ('md5','md5-sess','sha')
28 # but only sha works for me, but IE 
29 # sha, Firefox=ok, Opera=ok, wget=ok, ie=not ok
30 # md5-sess, firefox=not ok, opera=not ok,wget=ok, ie=not ok
31 # md5 same as md5-sess 
32
33 def startWebserver():
34         class ScreenPage(resource.Resource):
35                 def __init__(self, path):
36                         self.path = path
37                         
38                 def render(self, req):
39                         global sessions
40                         if sessions == [ ]:
41                                 return http.Response(responsecode.OK, stream="please wait until enigma has booted")
42
43                         class myProducerStream(stream.ProducerStream):
44                                 closed_callback = None
45
46                                 def close(self):
47                                         if self.closed_callback:
48                                                 self.closed_callback()
49                                         stream.ProducerStream.close(self)
50
51                         if os.path.isfile(self.path):
52                                 s=myProducerStream()
53                                 webif.renderPage(s, self.path, req, sessions[0])  # login?
54                                 return http.Response(responsecode.OK,stream=s)
55                         else:
56                                 return http.Response(responsecode.NOT_FOUND)
57                         
58                 def locateChild(self, request, segments):
59                         path = self.path+'/'+'/'.join(segments)
60                         if path[-1:] == "/":
61                                 path += "index.html"
62                         return ScreenPage(path), ()
63                 
64         class Toplevel(resource.Resource):
65                 addSlash = True
66
67                 def render(self, req):
68                         fp = open(util.sibpath(__file__, "web-data")+"/index.html")
69                         s = fp.read()
70                         fp.close()
71                         return http.Response(responsecode.OK, {'Content-type': http_headers.MimeType('text', 'html')},stream=s)
72
73                 child_web = ScreenPage(util.sibpath(__file__, "web")) # "/web/*"
74                 child_webdata = static.File(util.sibpath(__file__, "web-data")) # FIXME: web-data appears as webdata
75                 child_hdd = static.File("/hdd")
76                 
77         if PASSWORDPROTECTION is False:
78                 site = server.Site(Toplevel())
79         else:
80                 from twisted.cred.portal import Portal
81                 from twisted.cred import checkers
82                 from twisted.web2.auth import digest, basic, wrapper
83                 from zope.interface import Interface, implements
84                 from twisted.cred import portal
85                 class IHTTPUser(Interface):
86                         pass
87
88                 class HTTPUser(object):
89                         implements(IHTTPUser)
90
91                 class HTTPAuthRealm(object):
92                         implements(portal.IRealm)
93                         def requestAvatar(self, avatarId, mind, *interfaces):
94                                 if IHTTPUser in interfaces:
95                                         return IHTTPUser, HTTPUser()
96                                 raise NotImplementedError("Only IHTTPUser interface is supported")
97
98                 portal = Portal(HTTPAuthRealm())
99                 checker = checkers.InMemoryUsernamePasswordDatabaseDontUse(root=PASSWORDPROTECTION_pwd)
100                 portal.registerChecker(checker)
101                 root = wrapper.HTTPAuthResource(Toplevel(),
102                                         (basic.BasicCredentialFactory('DM7025'),digest.DigestCredentialFactory(PASSWORDPROTECTION_mode,'DM7025')),
103                                         portal, (IHTTPUser,))
104                 site = server.Site(root)
105         reactor.listenTCP(80, channel.HTTPFactory(site))
106
107 # start classes for PASSWORDPROTECTION
108 # end  classes for PASSWORDPROTECTION
109
110 def autostart(reason, **kwargs):
111         if "session" in kwargs:
112                 global sessions
113                 sessions.append(kwargs["session"])
114                 return
115
116         if reason == 0:
117                 try:
118                         """
119                          in normal console output, twisted will print only the first Traceback.
120                          is this a bug in twisted or a conflict with enigma2?
121                          with this option enabled, twisted will print all TB to the logfile
122                          use tail -f <file> to view this log
123                         """
124                         if DEBUG:
125                                 from twisted.python.log import startLogging
126                                 print "start twisted logfile, writing to %s" % DEBUGFILE 
127                                 startLogging(open(DEBUGFILE,'w'))
128                         
129                         startWebserver()
130                 except ImportError:
131                         print "twisted not available, not starting web services"
132
133 def Plugins(**kwargs):
134         return PluginDescriptor(where = [PluginDescriptor.WHERE_SESSIONSTART, PluginDescriptor.WHERE_AUTOSTART], fnc = autostart)