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