from Screens.Screen import Screen
from Screens.MessageBox import MessageBox
from Screens.ChoiceBox import ChoiceBox
from Screens.Standby import TryQuitMainloop
from Components.ActionMap import ActionMap
from Components.Sources.StaticText import StaticText
from Components.Sources.Progress import Progress
from Components.Sources.Boolean import Boolean
from Components.Label import Label
from Components.FileList import FileList
from Components.Task import Task, Job, JobManager
from Tools.Directories import fileExists
from Tools.HardwareInfo import HardwareInfo
from os import system
from enigma import eConsoleAppContainer
import re
class writeNAND(Task):
def __init__(self,job,param,box):
Task.__init__(self,job, ("Writing image file to NAND Flash"))
self.setTool("/usr/lib/enigma2/python/Plugins/SystemPlugins/NFIFlash/mywritenand")
if box == "dm7025":
self.end = 256
elif box[:5] == "dm800":
self.end = 512
if box == "dm8000":
self.setTool("/usr/lib/enigma2/python/Plugins/SystemPlugins/NFIFlash/dm8000_writenand")
self.args += param
self.weighting = 1
def processOutput(self, data):
print "[writeNand] " + data
if data == "." or data.endswith(" ."):
self.progress += 1
elif data.find("*** done!") > 0:
print "data.found done"
self.setProgress(self.end)
else:
self.output_line = data
class NFISummary(Screen):
skin = """
"""
def __init__(self, session, parent):
Screen.__init__(self, session, parent)
self["title"] = StaticText(_("Image flash utility"))
self["content"] = StaticText(_("Please select .NFI flash image file from medium"))
self["job_progressbar"] = Progress()
self["job_progresslabel"] = StaticText("")
def setText(self, text):
self["content"].setText(text)
class NFIFlash(Screen):
skin = """
"""
def __init__(self, session, cancelable = True, close_on_finish = False):
self.skin = NFIFlash.skin
Screen.__init__(self, session)
self["job_progressbar"] = Progress()
self["job_progresslabel"] = StaticText("")
self["finished"] = Boolean()
self["infolabel"] = StaticText("")
self["statusbar"] = StaticText(_("Please select .NFI flash image file from medium"))
self["listlabel"] = StaticText(_("select .NFI flash file")+":")
self["key_green"] = StaticText()
self["key_yellow"] = StaticText()
self["key_blue"] = StaticText()
self["actions"] = ActionMap(["OkCancelActions", "ColorActions", "DirectionActions"],
{
"green": self.ok,
"yellow": self.reboot,
"blue": self.runWizard,
"ok": self.ok,
"left": self.left,
"right": self.right,
"up": self.up,
"down": self.down
}, -1)
currDir = "/media/usb/"
self.filelist = FileList(currDir, matchingPattern = "^.*\.(nfi|NFI)")
self["filelist"] = self.filelist
self.nfifile = ""
self.md5sum = ""
self.job = None
self.box = HardwareInfo().get_device_name()
self.configuration_restorable = None
self.wizard_mode = False
from enigma import eTimer
self.delayTimer = eTimer()
self.delayTimer.callback.append(self.runWizard)
self.delayTimer.start(50,1)
def check_for_wizard(self):
if self["filelist"].getCurrentDirectory() is not None and fileExists(self["filelist"].getCurrentDirectory()+"wizard.nfo"):
self["key_blue"].text = _("USB stick wizard")
return True
else:
self["key_blue"].text = ""
return False
def runWizard(self):
if not self.check_for_wizard():
self.wizard_mode = False
return
wizardcontent = open(self["filelist"].getCurrentDirectory()+"/wizard.nfo", "r").readlines()
nfifile = None
for line in wizardcontent:
line = line.strip()
if line.startswith("image: "):
nfifile = self["filelist"].getCurrentDirectory()+line[7:]
if line.startswith("configuration: "):
backupfile = self["filelist"].getCurrentDirectory()+line[15:]
if fileExists(backupfile):
print "wizard configuration:", backupfile
self.configuration_restorable = backupfile
else:
self.configuration_restorable = None
if nfifile and fileExists(nfifile):
self.wizard_mode = True
print "wizard image:", nfifile
self.check_for_NFO(nfifile)
self.queryFlash()
def closeCB(self):
if ( self.job is None or self.job.status is not self.job.IN_PROGRESS ) and not self.no_autostart:
self.close()
#else:
#if self.cancelable:
#self.cancel()
def up(self):
self["filelist"].up()
self.check_for_NFO()
def down(self):
self["filelist"].down()
self.check_for_NFO()
def right(self):
self["filelist"].pageDown()
self.check_for_NFO()
def left(self):
self["filelist"].pageUp()
self.check_for_NFO()
def check_for_NFO(self, nfifile=None):
self.session.summary.setText(self["filelist"].getFilename())
if nfifile is None:
self.session.summary.setText(self["filelist"].getFilename())
if self["filelist"].getFilename() is None:
return
if self["filelist"].getCurrentDirectory() is not None:
self.nfifile = self["filelist"].getCurrentDirectory()+self["filelist"].getFilename()
else:
self.nfifile = nfifile
if self.nfifile.upper().endswith(".NFI"):
self["key_green"].text = _("Flash")
nfofilename = self.nfifile[0:-3]+"nfo"
if fileExists(nfofilename):
nfocontent = open(nfofilename, "r").read()
self["infolabel"].text = nfocontent
pos = nfocontent.find("MD5:")
if pos > 0:
self.md5sum = nfocontent[pos+5:pos+5+32] + " " + self.nfifile
else:
self.md5sum = ""
else:
self["infolabel"].text = _("No details for this image file") + (self["filelist"].getFilename() or "")
self.md5sum = ""
else:
self["infolabel"].text = ""
self["key_green"].text = ""
def ok(self):
if self.job is None or self.job.status is not self.job.IN_PROGRESS:
if self["filelist"].canDescent(): # isDir
self["filelist"].descent()
self.session.summary.setText(self["filelist"].getFilename())
self.check_for_NFO()
self.check_for_wizard()
else:
self.queryFlash()
def queryFlash(self):
fd = open(self.nfifile, 'r')
print fd
sign = fd.read(11)
print sign
if sign.find("NFI1" + self.box + "\0") == 0:
if self.md5sum != "":
self["statusbar"].text = ("Please wait for md5 signature verification...")
self.session.summary.setText(("Please wait for md5 signature verification..."))
self.container = eConsoleAppContainer()
self.container.setCWD(self["filelist"].getCurrentDirectory())
self.container.appClosed.append(self.md5finished)
self.container.dataSent.append(self.md5ready)
self.container.execute("md5sum -cw -")
self.container.write(self.md5sum)
else:
self.session.openWithCallback(self.queryCB, MessageBox, _("This .NFI file does not have a md5sum signature and is not guaranteed to work. Do you really want to burn this image to flash memory?"), MessageBox.TYPE_YESNO)
else:
self.session.open(MessageBox, (_("This .NFI file does not contain a valid %s image!") % (self.box.upper())), MessageBox.TYPE_ERROR)
def md5ready(self, retval):
self.container.sendEOF()
def md5finished(self, retval):
if retval==0:
if self.wizard_mode:
self.session.openWithCallback(self.queryCB, MessageBox, _("Shall the USB stick wizard proceed and program the image file %s into flash memory?" % self.nfifile.rsplit('/',1)[-1]), MessageBox.TYPE_YESNO)
else:
self.session.openWithCallback(self.queryCB, MessageBox, _("This .NFI file has a valid md5 signature. Continue programming this image to flash memory?"), MessageBox.TYPE_YESNO)
else:
self.session.openWithCallback(self.queryCB, MessageBox, _("The md5sum validation failed, the file may be corrupted! Are you sure that you want to burn this image to flash memory? You are doing this at your own risk!"), MessageBox.TYPE_YESNO)
def queryCB(self, answer):
if answer == True:
self.createJob()
else:
self["statusbar"].text = _("Please select .NFI flash image file from medium")
self.wizard_mode = False
def createJob(self):
self.job = Job("Image flashing job")
param = [self.nfifile]
writeNAND(self.job,param,self.box)
#writeNAND2(self.job,param)
#writeNAND3(self.job,param)
self.job.state_changed.append(self.update_job)
self.job.end = 540
self.cwd = self["filelist"].getCurrentDirectory()
self["job_progressbar"].range = self.job.end
self.startJob()
def startJob(self):
self["key_blue"].text = ""
self["key_yellow"].text = ""
self["key_green"].text = ""
#self["progress0"].show()
#self["progress1"].show()
self.job.start(self.jobcb)
def update_job(self):
j = self.job
#print "[job state_changed]"
if j.status == j.IN_PROGRESS:
self.session.summary["job_progressbar"].value = j.progress
self.session.summary["job_progressbar"].range = j.end
self.session.summary["job_progresslabel"].text = "%.2f%%" % (100*j.progress/float(j.end))
self["job_progressbar"].range = j.end
self["job_progressbar"].value = j.progress
#print "[update_job] j.progress=%f, j.getProgress()=%f, j.end=%d, text=%f" % (j.progress, j.getProgress(), j.end, (100*j.progress/float(j.end)))
self["job_progresslabel"].text = "%.2f%%" % (100*j.progress/float(j.end))
self.session.summary.setText(j.tasks[j.current_task].name)
self["statusbar"].text = (j.tasks[j.current_task].name)
elif j.status == j.FINISHED:
self["statusbar"].text = _("Writing NFI image file to flash completed")
self.session.summary.setText(_("NFI image flashing completed. Press Yellow to Reboot!"))
if self.wizard_mode:
self.restoreConfiguration()
self["key_yellow"].text = _("Reboot")
elif j.status == j.FAILED:
self["statusbar"].text = j.tasks[j.current_task].name + " " + _("failed")
self.session.open(MessageBox, (_("Flashing failed") + ":\n" + j.tasks[j.current_task].name + ":\n" + j.tasks[j.current_task].output_line), MessageBox.TYPE_ERROR)
def jobcb(self, jobref, fasel, blubber):
print "[jobcb] %s %s %s" % (jobref, fasel, blubber)
self["key_green"].text = _("Flash")
def reboot(self, ret=None):
if self.job.status == self.job.FINISHED:
self["statusbar"].text = ("rebooting...")
TryQuitMainloop(self.session,2)
def restoreConfiguration(self):
if self.configuration_restorable:
from Screens.Console import Console
cmdlist = [ "mount /dev/mtdblock/3 /mnt/realroot -t jffs2", "tar -xzvf " + self.configuration_restorable + " -C /mnt/realroot/" ]
self.session.open(Console, title = "Restore running", cmdlist = cmdlist, finishedCallback = self.restore_finished, closeOnSuccess = True)
def restore_finished(self):
self.session.openWithCallback(self.reboot, MessageBox, _("USB stick wizard finished. Your dreambox will now restart with your new image!"), MessageBox.TYPE_INFO)
def createSummary(self):
return NFISummary