Advertisement
SharkyEXE

Untitled

Aug 5th, 2018
469
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.60 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. # System Time Plugin for E2
  3. # Coded by Dima73 (c) 2012
  4. #
  5. # Version: 1.0-rc2 (14.02.2013 12:00)
  6. # Support: Dima73@inbox.lv
  7. #
  8.  
  9. import enigma
  10. from enigma import *
  11. from Plugins.Plugin import PluginDescriptor
  12. from Tools.Directories import resolveFilename, fileExists, SCOPE_CONFIG, SCOPE_PLUGINS, SCOPE_LANGUAGE
  13. from Components.config import config, ConfigSubsection, ConfigSelection, getConfigListEntry, ConfigYesNo
  14. from Components.ConfigList import ConfigListScreen
  15. from Screens.Screen import Screen
  16. from Screens.InputBox import InputBox
  17. from Components.Input import Input
  18. from Components.GUIComponent import *
  19. from Components.Sources.StaticText import StaticText
  20. from Components.ActionMap import ActionMap, NumberActionMap
  21. from Screens.MessageBox import MessageBox
  22. from Components.Pixmap import Pixmap
  23. from Screens.Console import Console
  24. from Components.Label import Label
  25. from Screens.Standby import TryQuitMainloop
  26. from Components.Language import language
  27. from os import environ
  28. import os
  29. from time import *
  30. import time
  31. import datetime
  32. import gettext
  33.  
  34. lang = language.getLanguage()
  35. environ["LANGUAGE"] = lang[:2]
  36. gettext.bindtextdomain("enigma2", resolveFilename(SCOPE_LANGUAGE))
  37. gettext.textdomain("enigma2")
  38. gettext.bindtextdomain("SystemTime", "%s%s" % (resolveFilename(SCOPE_PLUGINS), "SystemPlugins/SystemTime/locale/"))
  39.  
  40. def _(txt):
  41. t = gettext.dgettext("SystemTime", txt)
  42. if t == txt:
  43. t = gettext.gettext(txt)
  44. return t
  45.  
  46. PLUGIN_VERSION = _(" ver. 1.0")
  47.  
  48. config.plugins.SystemTime = ConfigSubsection()
  49. config.plugins.SystemTime.choiceSystemTime = ConfigSelection([("0", _("Transponder Time")),("1", _("Internet Time"))], default="0")
  50. config.plugins.SystemTime.useNTPminutes = ConfigSelection(default = "30", choices = [("5", _("5 min")),("15", _("15 min")),("30", _("30 min")), ("60", _("1 hour")), ("120", _("2 hours")),("240", _("4 hours")), ("720", _("12 hours"))])
  51. config.plugins.SystemTime.syncNTPcoldstart = ConfigYesNo(default = False)
  52. config.plugins.SystemTime.syncNTPtime = ConfigSelection(choices = [("1", _("Press OK"))], default = "1")
  53. config.plugins.SystemTime.syncDVBtime = ConfigSelection(choices = [("1", _("Press OK"))], default = "1")
  54. config.plugins.SystemTime.syncManually = ConfigSelection(choices = [("1", _("Press OK"))], default = "1")
  55.  
  56. from NTPSyncPoller import NTPSyncPoller
  57. ntpsyncpoller = None
  58.  
  59. class SystemTimeSetupScreen(Screen, ConfigListScreen):
  60. global PLUGIN_VERSION
  61. skin = """
  62. <screen position="center,center" size="800,250" title="Setup System Time" >
  63. <ePixmap position="0,30" zPosition="1" size="200,2" pixmap="/usr/lib/enigma2/python/Plugins/SystemPlugins/SystemTime/images/red.png" alphatest="blend" />
  64. <widget name="key_red" position="0,0" zPosition="2" size="200,30" font="Regular; 17" halign="center" valign="center" backgroundColor="background" foregroundColor="white" transparent="1" />
  65. <ePixmap position="200,30" zPosition="1" size="200,2" pixmap="/usr/lib/enigma2/python/Plugins/SystemPlugins/SystemTime/images/green.png" alphatest="blend" />
  66. <widget name="key_green" position="200,0" zPosition="2" size="200,30" font="Regular; 17" halign="center" valign="center" backgroundColor="background" foregroundColor="white" transparent="1" />
  67. <ePixmap position="400,30" zPosition="1" size="200,2" pixmap="/usr/lib/enigma2/python/Plugins/SystemPlugins/SystemTime/images/yellow.png" alphatest="blend" />
  68. <widget name="key_yellow" position="400,0" zPosition="2" size="200,30" font="Regular; 17" halign="center" valign="center" backgroundColor="background" foregroundColor="white" transparent="1" />
  69. <ePixmap position="600,30" zPosition="1" size="200,2" pixmap="/usr/lib/enigma2/python/Plugins/SystemPlugins/SystemTime/images/blue.png" alphatest="blend" />
  70. <widget name="key_blue" position="600,0" zPosition="2" size="200,30" font="Regular; 17" halign="center" valign="center" backgroundColor="background" foregroundColor="white" transparent="1" />
  71. <widget name="config" position="25,50" size="740,155" scrollbarMode="showOnDemand"/>
  72. <ePixmap pixmap="skin_default/div-h.png" position="0,210" zPosition="1" size="800,2" />
  73. <widget source="global.CurrentTime" render="Label" position="250,218" size="430, 21" font="Regular; 20" halign="left" foregroundColor="white" backgroundColor="background" transparent="1">
  74. <convert type="ClockToText">Date</convert>
  75. </widget>
  76. <ePixmap alphatest="on" pixmap="skin_default/icons/clock.png" position="690,215" size="14,14" zPosition="1" />
  77. <widget font="Regular;19" halign="left" position="710,218" render="Label" size="55,20" source="global.CurrentTime" transparent="1" valign="center" zPosition="1">
  78. <convert type="ClockToText">Default</convert>
  79. </widget>
  80. <widget font="Regular;15" halign="left" position="762,215" render="Label" size="27,17" source="global.CurrentTime" transparent="1" valign="center" zPosition="1">
  81. <convert type="ClockToText">Format::%S</convert>
  82. </widget>
  83. </screen>"""
  84. def __init__(self, session, servicelist = None, args = None):
  85. self.servicelist = servicelist
  86. self.skin = SystemTimeSetupScreen.skin
  87. self.setup_title = _("Setup System Time") + PLUGIN_VERSION
  88. Screen.__init__(self, session)
  89.  
  90. self["key_red"] = Label(_("Cancel"))
  91. self["key_green"] = Label(_("Save"))
  92. self["key_yellow"] = Label(_("Restart GUI"))
  93. self["key_blue"] = Label(" ")
  94.  
  95. self["actions"] = ActionMap(["SetupActions", "ColorActions"],
  96. {
  97. "ok": self.keyGo,
  98. "save": self.keyGreen,
  99. "cancel": self.cancel,
  100. "red": self.keyRed,
  101. "yellow":self.keyYellow,
  102. "blue": self.keyBlue,
  103. }, -2)
  104.  
  105. ConfigListScreen.__init__(self, [])
  106. self.initConfig()
  107. self.createSetup()
  108. self.onClose.append(self.__closed)
  109. self.onLayoutFinish.append(self.__layoutFinished)
  110. self["config"].onSelectionChanged.append(self.configPosition)
  111.  
  112. def __closed(self):
  113. pass
  114.  
  115. def __layoutFinished(self):
  116. self.setTitle(self.setup_title)
  117.  
  118. def initConfig(self):
  119. def getPrevValues(section):
  120. res = { }
  121. for (key,val) in section.content.items.items():
  122. if isinstance(val, ConfigSubsection):
  123. res[key] = getPrevValues(val)
  124. else:
  125. res[key] = val.value
  126. return res
  127.  
  128. self.ST = config.plugins.SystemTime
  129. self.prev_values = getPrevValues(self.ST)
  130. self.cfg_choiceSystemTime = getConfigListEntry(_("Sync time using"), config.plugins.SystemTime.choiceSystemTime)
  131. self.cfg_useNTPminutes = getConfigListEntry(_("Sync NTP every (minutes)"), config.plugins.SystemTime.useNTPminutes)
  132. self.cfg_syncNTPcoldstart = getConfigListEntry(_("Sync NTP cold start"), config.plugins.SystemTime.syncNTPcoldstart)
  133. self.cfg_syncNTPtime = getConfigListEntry(_("Sync now internet"), config.plugins.SystemTime.syncNTPtime)
  134. self.cfg_syncDVBtime = getConfigListEntry(_("Sync now current transponder"), config.plugins.SystemTime.syncDVBtime)
  135. self.cfg_syncManually = getConfigListEntry(_("Set system time manually"), config.plugins.SystemTime.syncManually)
  136.  
  137. def createSetup(self):
  138. list = [ self.cfg_choiceSystemTime ]
  139. if self.ST.choiceSystemTime.value == "1":
  140. list.append(self.cfg_useNTPminutes)
  141. list.append(self.cfg_syncDVBtime)
  142. list.append(self.cfg_syncNTPcoldstart)
  143. list.append(self.cfg_syncNTPtime)
  144. list.append(self.cfg_syncManually)
  145. self["config"].list = list
  146. self["config"].l.setList(list)
  147.  
  148. def newConfig(self):
  149. cur = self["config"].getCurrent()
  150. if cur in (self.cfg_choiceSystemTime, self.cfg_useNTPminutes):
  151. self.createSetup()
  152.  
  153. def keyGo(self):
  154. ConfigListScreen.keyOK(self)
  155. sel = self["config"].getCurrent()[1]
  156. if sel == self.ST.syncNTPtime:
  157. if os.path.exists("/usr/bin/ntpdate"):
  158. cmd = '/usr/bin/ntpdate -v -u pool.ntp.org && echo "\n"'
  159. self.session.open(MyConsole, _("Time sync with NTP..."), [cmd])
  160. else:
  161. self.session.open(MessageBox,_("'ntpdate' not installed !"), MessageBox.TYPE_ERROR, timeout = 3 )
  162. if sel == self.ST.syncDVBtime:
  163. if os.path.exists("/usr/bin/dvbdate"):
  164. cmd = '/usr/bin/dvbdate -p -s -f && echo "\n"'
  165. self.session.open(MyConsole, _("Time sync with DVB..."), [cmd])
  166. else:
  167. self.session.open(MessageBox,_("'dvbdate' not installed !"), MessageBox.TYPE_ERROR, timeout = 3 )
  168. if sel == self.ST.syncManually:
  169. ChangeTimeWizzard(self.session)
  170.  
  171. def configPosition(self):
  172. self["key_blue"].setText("")
  173. idx = self["config"].getCurrent()[1]
  174. if idx == self.ST.syncDVBtime:
  175. self["key_blue"].setText(_("Choice transponder"))
  176.  
  177. def keyRed(self):
  178. def setPrevValues(section, values):
  179. for (key,val) in section.content.items.items():
  180. value = values.get(key, None)
  181. if value is not None:
  182. if isinstance(val, ConfigSubsection):
  183. setPrevValues(val, value)
  184. else:
  185. val.value = value
  186. setPrevValues(self.ST, self.prev_values)
  187. self.ST.save()
  188.  
  189. def addNTPcoldstart(self):
  190. if os.path.exists("/usr/bin/ntpdate"):
  191. if not fileExists("/etc/rcS.d/S42ntpdate.sh"):
  192. os.system("echo -e '#!/bin/sh\n\n[ -x /usr/bin/ntpdate ] && /usr/bin/ntpdate -b -s -u pool.ntp.org\n\nexit 0' >> /etc/rcS.d/S42ntpdate.sh")
  193. if fileExists("/etc/rcS.d/S42ntpdate.sh"):
  194. os.chmod("/etc/rcS.d/S42ntpdate.sh", 0755)
  195. else:
  196. self.session.open(MessageBox,_("'ntpdate' not installed !"), MessageBox.TYPE_ERROR, timeout = 3 )
  197.  
  198. def removeNTPcoldstart(self):
  199. if fileExists("/etc/rcS.d/S42ntpdate.sh"):
  200. os.system("rm -rf /etc/rcS.d/S42ntpdate.sh")
  201.  
  202. def keyGreen(self):
  203. if self.ST.syncNTPcoldstart.value:
  204. self.addNTPcoldstart()
  205. if not self.ST.syncNTPcoldstart.value:
  206. self.removeNTPcoldstart()
  207. if self.ST.choiceSystemTime.value == "0":
  208. enigma.eDVBLocalTimeHandler.getInstance().setUseDVBTime(True)
  209. config.misc.useTransponderTime.setValue(True)
  210. config.misc.useTransponderTime.save()
  211. if self.ST.choiceSystemTime.value == "1":
  212. enigma.eDVBLocalTimeHandler.getInstance().setUseDVBTime(False)
  213. config.misc.useTransponderTime.setValue(False)
  214. config.misc.useTransponderTime.save()
  215. self.ST.save()
  216. self.session.openWithCallback(self.restartGuiNow, MessageBox, _("Restart the GUI now?"), MessageBox.TYPE_YESNO, default = False)
  217.  
  218. def restartGuiNow(self, answer):
  219. if answer is True:
  220. self.session.open(TryQuitMainloop, 3)
  221. else:
  222. self.close()
  223.  
  224. def cancel(self):
  225. self.keyRed()
  226. self.close()
  227.  
  228. def keyYellow(self):
  229. self.session.openWithCallback(self.restartGui, MessageBox, _("Restart the GUI now?"), MessageBox.TYPE_YESNO)
  230.  
  231. def restartGui(self, answer):
  232. if answer is True:
  233. self.session.open(TryQuitMainloop, 3)
  234.  
  235. def keyBlue(self):
  236. if self["key_blue"].getText() == _("Choice transponder"):
  237. if self.servicelist is None:
  238. for (dlg,flag) in self.session.dialog_stack:
  239. if dlg.__class__.__name__ == "InfoBar":
  240. self.servicelist = dlg.servicelist
  241. break
  242. if not self.servicelist is None:
  243. self.session.execDialog(self.servicelist)
  244.  
  245. def keyLeft(self):
  246. ConfigListScreen.keyLeft(self)
  247. self.newConfig()
  248.  
  249. def keyRight(self):
  250. ConfigListScreen.keyRight(self)
  251. self.newConfig()
  252.  
  253. class MyConsole(Console):
  254. skin = """<screen position="center,center" size="500,240" title="Command execution..." >
  255. <widget name="text" position="10,10" size="485,230" font="Regular;20" />
  256. </screen>"""
  257. def __init__(self, session, title = "My Console...", cmdlist = None):
  258. Console.__init__(self, session, title, cmdlist)
  259.  
  260. class ChangeTimeWizzard(Screen):
  261. def __init__(self, session):
  262. self.session = session
  263. jetzt = time.time()
  264. timezone = datetime.datetime.utcnow()
  265. delta = (jetzt - time.mktime(timezone.timetuple()))
  266. self.oldtime = strftime("%Y:%m:%d %H:%M",localtime())
  267. self.session.openWithCallback(self.askForNewTime,InputBox, title=_("Please Enter new System time and press OK !"), text="%s" % (self.oldtime), maxSize=16, type=Input.NUMBER)
  268.  
  269. def askForNewTime(self,newclock):
  270. try:
  271. length=len(newclock)
  272. except:
  273. length=0
  274. if newclock is None:
  275. self.skipChangeTime(_("no new time"))
  276. elif (length == 16) is False:
  277. self.skipChangeTime(_("new time string too short"))
  278. elif (newclock.count(" ") < 1) is True:
  279. self.skipChangeTime(_("invalid format"))
  280. elif (newclock.count(":") < 3) is True:
  281. self.skipChangeTime(_("invalid format"))
  282. else:
  283. full=[]
  284. full=newclock.split(" ",1)
  285. newdate=full[0]
  286. newtime=full[1]
  287. parts=[]
  288. parts=newdate.split(":",2)
  289. newyear=parts[0]
  290. newmonth=parts[1]
  291. newday=parts[2]
  292. parts=newtime.split(":",1)
  293. newhour=parts[0]
  294. newmin=parts[1]
  295. maxmonth = 31
  296. if (int(newmonth) == 4) or (int(newmonth) == 6) or (int(newmonth) == 9) or (int(newmonth) == 11) is True:
  297. maxmonth=30
  298. elif (int(newmonth) == 2) is True:
  299. if ((4*int(int(newyear)/4)) == int(newyear)) is True:
  300. maxmonth=28
  301. else:
  302. maxmonth=27
  303. if (int(newyear) < 2007) or (int(newyear) > 2027) or (len(newyear) < 4) is True:
  304. self.skipChangeTime(_("invalid year %s") %newyear)
  305. elif (int(newmonth) < 0) or (int(newmonth) >12) or (len(newmonth) < 2) is True:
  306. self.skipChangeTime(_("invalid month %s") %newmonth)
  307. elif (int(newday) < 1) or (int(newday) > maxmonth) or (len(newday) < 2) is True:
  308. self.skipChangeTime(_("invalid day %s") %newday)
  309. elif (int(newhour) < 0) or (int(newhour) > 23) or (len(newhour) < 2) is True:
  310. self.skipChangeTime(_("invalid hour %s") %newhour)
  311. elif (int(newmin) < 0) or (int(newmin) > 59) or (len(newmin) < 2) is True:
  312. self.skipChangeTime(_("invalid minute %s") %newmin)
  313. else:
  314. self.newtime = "%s%s%s%s%s" %(newmonth,newday,newhour,newmin,newyear)
  315. self.session.openWithCallback(self.DoChangeTimeRestart,MessageBox,_("Apply the new System time?"), MessageBox.TYPE_YESNO)
  316.  
  317. def DoChangeTimeRestart(self,answer):
  318. if answer is None:
  319. self.skipChangeTime(_("answer is None"))
  320. if answer is False:
  321. self.skipChangeTime(_("you were not confirming"))
  322. else:
  323. os.system("date %s" % (self.newtime))
  324.  
  325. def skipChangeTime(self,reason):
  326. self.session.open(MessageBox,(_("Change system time was canceled, because %s") % reason), MessageBox.TYPE_WARNING)
  327.  
  328. def startup(session=None, **kwargs):
  329. global ntpsyncpoller
  330. ntpsyncpoller = NTPSyncPoller()
  331. ntpsyncpoller.start()
  332.  
  333. def main(menuid, **kwargs):
  334. if menuid == "system":
  335. return [(_("System Time"), OpenSetup, "system_time_setup", None)]
  336. else:
  337. return []
  338.  
  339. def OpenSetup(session, **kwargs):
  340. servicelist = kwargs.get('servicelist', None)
  341. session.open(SystemTimeSetupScreen, servicelist)
  342.  
  343. def Plugins(**kwargs):
  344. return [PluginDescriptor(name = "System Time", description = _("System time your box"), where = PluginDescriptor.WHERE_MENU, fnc = main),
  345. PluginDescriptor(name = "System Time", description = "", where = PluginDescriptor.WHERE_SESSIONSTART, fnc = startup)]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement