fix Depends (twisted-web)
[enigma2-plugins.git] / emailclient / src / protocol.py
1 from twisted.internet import reactor
2 from twisted.internet import protocol
3 from twisted.internet import ssl
4 from twisted.internet import defer
5 from twisted.mail import imap4
6
7 #from twisted.python import log
8 #log.startLogging(open("/tmp/twisted.log","w"))
9
10 class SimpleIMAP4Client(imap4.IMAP4Client):
11     greetDeferred = None
12     def __init__(self,e2session, contextFac = None):
13         self.e2session = e2session
14         imap4.IMAP4Client.__init__(self,contextFactory = contextFac)
15         
16     def serverGreeting(self, caps):
17         print "serverGreeting",caps
18         self.serverCapabilities = caps
19         if self.greetDeferred is not None:
20             d, self.greetDeferred = self.greetDeferred, None
21             d.callback(self)
22
23 class SimpleIMAP4ClientFactory(protocol.ClientFactory):
24     
25     protocol = SimpleIMAP4Client
26
27     def __init__(self, e2session, username, onConn,factory):
28         self.ctx = factory
29         self.e2session = e2session
30         self.username = username
31         self.onConn = onConn
32
33     def buildProtocol(self, addr):
34         print "building protocol",addr
35         p = self.protocol(self.e2session,contextFac = self.ctx)
36         p.factory = self
37         p.greetDeferred = self.onConn
38         auth = imap4.CramMD5ClientAuthenticator(self.username)
39         p.registerAuthenticator(auth)
40         return p
41     
42     def clientConnectionFailed(self, connector, reason):
43         d, self.onConn = self.onConn, None
44         d.errback(reason)
45
46 def createFactory( e2session,username,hostname, port):
47     print "creating factory for ",username,hostname,port
48     onConn = defer.Deferred(
49         ).addCallback(e2session.onConnect
50         ).addErrback(e2session.onConnectFailed
51         )
52
53     f2 = ssl.ClientContextFactory()
54     factory = SimpleIMAP4ClientFactory(e2session,username, onConn,f2)
55     if port == 993:
56         reactor.connectSSL( hostname, port,factory,f2)
57     else:
58         reactor.connectTCP( hostname, port,factory)
59
60     print "factory started"