remove not needed dependency with twisted-web2
[enigma2-plugins.git] / dyndns / src / plugin.py
1 from Plugins.Plugin import PluginDescriptor
2 from Screens.Screen import Screen
3 from Components.Label import Label
4 from Components.ActionMap import ActionMap
5 from enigma import eTimer
6 from Components.ConfigList import ConfigListScreen
7 from Components.config import config, getConfigListEntry, ConfigText, ConfigSelection, ConfigSubsection, ConfigYesNo
8 from urllib2 import Request, urlopen
9 from base64 import encodestring
10 global sessions
11 from twisted.internet import reactor
12
13 sessions = []
14
15 config.plugins.DynDNS = ConfigSubsection()
16 config.plugins.DynDNS.enable = ConfigYesNo(default = False)
17 config.plugins.DynDNS.interval = ConfigSelection(default = "10", choices = [("5", _("5 min.")),("10", _("10 min.")),("15", _("15 min.")),("30", _("30 min.")),("60", _("60 min."))])
18 config.plugins.DynDNS.hostname = ConfigText(default = "", fixed_size = False)
19 config.plugins.DynDNS.user = ConfigText(default = "", fixed_size = False)
20 config.plugins.DynDNS.password = ConfigText(default = "", fixed_size = False)
21
22 class DynDNSScreenMain(ConfigListScreen,Screen):
23     skin = """
24         <screen position="100,100" size="550,400" title="DynDNS Setup" >
25         <widget name="config" position="0,0" size="550,300" scrollbarMode="showOnDemand" />
26         <widget name="buttonred" position="10,360" size="100,40" backgroundColor="red" valign="center" halign="center" zPosition="2"  foregroundColor="white" font="Regular;18"/> 
27         <widget name="buttongreen" position="120,360" size="100,40" backgroundColor="green" valign="center" halign="center" zPosition="2"  foregroundColor="white" font="Regular;18"/> 
28         </screen>"""
29     def __init__(self, session, args = 0):
30         self.session = session
31         Screen.__init__(self, session)
32         self.list = []
33         self.list.append(getConfigListEntry(_("activate DynDNS"), config.plugins.DynDNS.enable))
34         self.list.append(getConfigListEntry(_("Interval to check IP-Adress"), config.plugins.DynDNS.interval))
35         self.list.append(getConfigListEntry(_("Hostname"), config.plugins.DynDNS.hostname))
36         self.list.append(getConfigListEntry(_("Username"), config.plugins.DynDNS.user))
37         self.list.append(getConfigListEntry(_("Password"), config.plugins.DynDNS.password))
38         ConfigListScreen.__init__(self, self.list)
39         self["buttonred"] = Label(_("cancel"))
40         self["buttongreen"] = Label(_("ok"))
41         self["setupActions"] = ActionMap(["SetupActions"],
42         {
43             "green": self.save,
44             "red": self.cancel,
45             "save": self.save,
46             "cancel": self.cancel,
47             "ok": self.save,
48         }, -2)
49
50     def save(self):
51         print "[DynDNS] saving config"
52         for x in self["config"].list:
53             x[1].save()
54         self.close(True)
55
56     def cancel(self):
57         for x in self["config"].list:
58             x[1].cancel()
59         self.close(False)
60
61 class DynDNSService:
62         enabled = False
63         sessions = []
64         lastip = ""
65         def __init__(self):
66                 self.timer = eTimer()
67                 self.timer.timeout.get().append(self.checkCurrentIP)
68                 
69         def enable(self):
70                 if config.plugins.DynDNS.enable.value:
71                         self.enabled = True
72                         reactor.callLater(1, self.checkCurrentIP)
73
74         def disable(self):
75                 if self.enabled:
76                         self.timer.stop()
77                         self.enabled = False
78                 
79         def addSession(self,session):
80                 self.sessions.append(session)
81         
82         def checkCurrentIP(self):
83                 print "[DynDNS] checking IP"
84                 try:
85                         html = self.getURL("http://checkip.dyndns.org")
86                         str = html.split("<body>")[1]
87                         str = str.split("</body>")[0]
88                         str = str.split(":")[1]
89                         str = str.lstrip().rstrip()
90                         
91                         if self.lastip is not str:
92                                 self.lastip=str
93                                 reactor.callLater(1, self.onIPchanged)
94                         self.timer.start(int(config.plugins.DynDNS.interval.value)*60000)
95                 except Exception,e:
96                         print "[DynDNS]",e
97                         str = "coundnotgetip"
98                         
99         def onIPchanged(self):
100                 print "[DynDNS] IP change, setting new one",self.lastip
101                 try:
102                         url = "http://members.dyndns.org/nic/update?system=dyndns&hostname=%s&myip=%s&wildcard=ON&offline=NO"%(config.plugins.DynDNS.hostname.value,self.lastip)
103                         if self.getURL(url).find("good") is not -1:
104                                 print "[DynDNS] ip changed"
105                 except Exception,e:
106                         print "[DynDNS] ip was not changed",e
107                         
108         def getURL(self,url):
109                 request =  Request(url)
110                 base64string = encodestring('%s:%s' % (config.plugins.DynDNS.user.value,config.plugins.DynDNS.password.value))[:-1]
111                 request.add_header("Authorization", "Basic %s" % base64string)
112                 htmlFile = urlopen(request)
113                 htmlData = htmlFile.read()
114                 htmlFile.close()
115                 return htmlData
116
117 def onPluginStart(session, **kwargs):
118         session.openWithCallback(onPluginStartCB,DynDNSScreenMain)
119
120 def onPluginStartCB(changed):
121         print "[DynDNS] config changed=",changed
122         global dyndnsservice
123         if changed:
124                 dyndnsservice.disable()
125                 dyndnsservice.enable()
126                 
127 global dyndnsservice
128 dyndnsservice = DynDNSService()
129
130 def onSessionStart(reason, **kwargs):
131         global dyndnsservice
132         if config.plugins.DynDNS.enable.value is not False:
133                 if "session" in kwargs:
134                         dyndnsservice.addSession(kwargs["session"])
135                 if reason == 0:
136                         dyndnsservice.enable()
137                 elif reason == 1:
138                         dyndnsservice.disable()
139                         
140 def Plugins(path,**kwargs):
141         return [PluginDescriptor(where = [PluginDescriptor.WHERE_SESSIONSTART, PluginDescriptor.WHERE_AUTOSTART], fnc = onSessionStart),
142                     PluginDescriptor(name=_("DynDNS"), description=_("use www.DynDNS.org on your Box"),where = [PluginDescriptor.WHERE_PLUGINMENU], fnc = onPluginStart, icon="icon.png")]
143