/
Flash_online.py
678 lines (614 loc) · 26.1 KB
/
Flash_online.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
from Plugins.SystemPlugins.Hotplug.plugin import hotplugNotifier
from Components.Button import Button
from Components.Label import Label
from Components.ActionMap import ActionMap
from Components.MenuList import MenuList
from Components.FileList import FileList
from Components.Task import Task, Job, job_manager, Condition
from Components.Sources.StaticText import StaticText
from Components.SystemInfo import SystemInfo
from Components import Harddisk
from Screens.Console import Console
from Screens.MessageBox import MessageBox
from Screens.ChoiceBox import ChoiceBox
from Screens.Screen import Screen
from Screens.Console import Console
from Screens.HelpMenu import HelpableScreen
from Screens.TaskView import JobView
from Tools.Downloader import downloadWithProgress
from enigma import fbClass
import urllib2
import os
import shutil
import math
from boxbranding import getBoxType, getImageDistro, getMachineName, getMachineBrand, getImageVersion, getMachineKernelFile, getMachineRootFile, getMachineBuild
distro = getImageDistro()
ImageVersion = getImageVersion()
ROOTFSBIN = getMachineRootFile()
KERNELBIN = getMachineKernelFile()
#############################################################################################################
# Create a List of imagetypes
# 0 = Name Of Image, 1 = link to file
images = []
global imagesCounter
imagesCounter = 0
#images.append(["Team", "http://teamimages.hdfreaks.cc"])
#images.append(["Latest", "http://images.hdfreaks.cc"])
#images.append(["V5.5", "http://v55.hdfreaks.cc"])
#images.append(["V6.0", "http://beta6.hdfreaks.cc"])
images.append(["V5.5", "http://teamimages.hdfreaks.cc"])
images.append(["V6.2", "http://v55.hdfreaks.cc"])
images.append(["V6.1", "http://v62.hdfreaks.cc"])
images.append(["Team", "http://v60.hdfreaks.cc"])
imagePath = '/media/hdd/images'
flashPath = '/media/hdd/images/flash'
flashTmp = '/media/hdd/images/tmp'
ofgwritePath = '/usr/bin/ofgwrite'
#############################################################################################################
def Freespace(dev):
statdev = os.statvfs(dev)
space = (statdev.f_bavail * statdev.f_frsize) / 1024
print "[Flash Online] Free space on %s = %i kilobytes" %(dev, space)
return space
class FlashOnline(Screen):
skin = """
<screen position="center,center" size="560,400" title="Flash On the Fly">
<ePixmap position="0,360" zPosition="1" size="140,40" pixmap="skin_default/buttons/red.png" transparent="1" alphatest="on" />
<ePixmap position="140,360" zPosition="1" size="140,40" pixmap="skin_default/buttons/green.png" transparent="1" alphatest="on" />
<ePixmap position="280,360" zPosition="1" size="140,40" pixmap="skin_default/buttons/yellow.png" transparent="1" alphatest="on" />
<ePixmap position="420,360" zPosition="1" size="140,40" pixmap="skin_default/buttons/blue.png" transparent="1" alphatest="on" />
<widget name="key_red" position="0,360" zPosition="2" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" shadowColor="black" shadowOffset="-1,-1" />
<widget name="key_green" position="140,360" zPosition="2" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" shadowColor="black" shadowOffset="-1,-1" />
<widget name="key_yellow" position="280,360" zPosition="2" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" shadowColor="black" shadowOffset="-1,-1" />
<widget name="key_blue" position="420,360" zPosition="2" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" shadowColor="black" shadowOffset="-1,-1" />
<widget name="info-online" position="10,80" zPosition="1" size="450,100" font="Regular;20" halign="left" valign="top" transparent="1" />
<widget name="info-local" position="10,150" zPosition="1" size="450,200" font="Regular;20" halign="left" valign="top" transparent="1" />
</screen>"""
def __init__(self, session):
Screen.__init__(self, session)
self.session = session
self.selection = 0
if getMachineBuild() in ("hd51","vs1500","h7","ceryon7252"):
self.devrootfs = "/dev/mmcblk0p3"
elif getMachineBuild() in ("gb7252"):
self.devrootfs = "/dev/mmcblk0p4"
else:
self.devrootfs = "/dev/mmcblk1p3"
self.multi = 1
self.list = self.list_files("/boot")
Screen.setTitle(self, _("Flash On the Fly"))
if SystemInfo["HaveMultiBoot"]:
self["key_blue"] = Button(_("Multiboot Select"))
else:
self["key_blue"] = Button(_(" "))
self["key_green"] = Button(_("Online"))
self["key_red"] = Button(_("Exit"))
self["key_yellow"] = Button(_("Local"))
self["info-local"] = Label(_("Local = Flash a image from local path /hdd/images"))
self["info-online"] = Label(_("Online = Download a image and flash it"))
self["actions"] = ActionMap(["OkCancelActions", "ColorActions"],
{
"blue": self.blue,
"yellow": self.yellow,
"green": self.green,
"red": self.quit,
"cancel": self.quit,
}, -2)
if SystemInfo["HaveMultiBoot"]:
if getMachineBuild() in ("gb7252"):
self.multi = self.read_startup("/boot/" + self.list[self.selection]).split(".",1)[1].split(":",1)[0]
self.multi = self.multi[-1:]
else:
self.multi = self.read_startup("/boot/" + self.list[self.selection]).split(".",1)[1].split(" ",1)[0]
self.multi = self.multi[-1:]
print "[Flash Online] MULTI:",self.multi
def check_hdd(self):
if not os.path.exists("/media/hdd"):
self.session.open(MessageBox, _("No /hdd found !!\nPlease make sure you have a HDD mounted.\n\nExit plugin."), type = MessageBox.TYPE_ERROR)
return False
if Freespace('/media/hdd') < 300000:
self.session.open(MessageBox, _("Not enough free space on /hdd !!\nYou need at least 300Mb free space.\n\nExit plugin."), type = MessageBox.TYPE_ERROR)
return False
if not os.path.exists(ofgwritePath):
self.session.open(MessageBox, _('ofgwrite not found !!\nPlease make sure you have ofgwrite installed in /usr/bin/ofgwrite.\n\nExit plugin.'), type = MessageBox.TYPE_ERROR)
return False
if not os.path.exists(imagePath):
try:
os.mkdir(imagePath)
except:
pass
if os.path.exists(flashPath):
try:
os.system('rm -rf ' + flashPath)
except:
pass
try:
os.mkdir(flashPath)
except:
pass
return True
def quit(self):
self.close()
def yellow(self):
if self.check_hdd():
self.session.open(doFlashImage, online = False, list=self.list[self.selection], multi=self.multi, devrootfs=self.devrootfs)
else:
self.close()
def green(self):
if self.check_hdd():
self.session.open(doFlashImage, online = True, list=self.list[self.selection], multi=self.multi, devrootfs=self.devrootfs)
else:
self.close()
def blue(self):
if SystemInfo["HaveMultiBoot"]:
self.selection = self.selection + 1
if self.selection == len(self.list):
self.selection = 0
self["key_blue"].setText(_(self.list[self.selection]))
if getMachineBuild() in ("gb7252"):
self.multi = self.read_startup("/boot/" + self.list[self.selection]).split(".",1)[1].split(":",1)[0]
self.multi = self.multi[-1:]
else:
self.multi = self.read_startup("/boot/" + self.list[self.selection]).split(".",1)[1].split("",1)[0]
self.multi = self.multi[-1:]
print "[Flash Online] MULTI:",self.multi
if getMachineBuild() in ("hd51","vs1500","h7","ceryon7252"):
cmdline = self.read_startup("/boot/" + self.list[self.selection]).split("=",3)[3].split(" ",1)[0]
else:
cmdline = self.read_startup("/boot/" + self.list[self.selection]).split("=",1)[1].split(" ",1)[0]
self.devrootfs = cmdline
print "[Flash Online] MULTI rootfs ", self.devrootfs
def read_startup(self, FILE):
file = FILE
with open(file, 'r') as myfile:
data=myfile.read().replace('\n', '')
myfile.close()
return data
def list_files(self, PATH):
files = []
if SystemInfo["HaveMultiBoot"]:
path = PATH
if getMachineBuild() in ("hd51","vs1500","h7","ceryon7252"):
for name in os.listdir(path):
if name != 'bootname' and os.path.isfile(os.path.join(path, name)):
try:
cmdline = self.read_startup("/boot/" + name).split("=",3)[3].split(" ",1)[0]
except IndexError:
continue
cmdline_startup = self.read_startup("/boot/STARTUP").split("=",3)[3].split(" ",1)[0]
if (cmdline != cmdline_startup) and (name != "STARTUP"):
files.append(name)
files.insert(0,"STARTUP")
elif getMachineBuild() in ("gb7252"):
for name in os.listdir(path):
if name != 'bootname' and os.path.isfile(os.path.join(path, name)):
try:
cmdline = self.read_startup("/boot/" + name).split("=",1)[1].split(" ",1)[0]
except IndexError:
continue
cmdline_startup = self.read_startup("/boot/STARTUP").split("=",1)[1].split(" ",1)[0]
if (cmdline != cmdline_startup) and (name != "STARTUP"):
files.append(name)
files.insert(0,"STARTUP")
else:
for name in os.listdir(path):
if name != 'bootname' and os.path.isfile(os.path.join(path, name)):
try:
cmdline = self.read_startup("/boot/" + name).split("=",1)[1].split(" ",1)[0]
except IndexError:
continue
cmdline_startup = self.read_startup("/boot/cmdline.txt").split("=",1)[1].split(" ",1)[0]
if (cmdline != cmdline_startup) and (name != "cmdline.txt"):
files.append(name)
files.insert(0,"cmdline.txt")
else:
files = "None"
return files
class doFlashImage(Screen):
skin = """
<screen position="center,center" size="700,500" title="Flash On the fly (select a image)">
<ePixmap position="0,460" zPosition="1" size="140,40" pixmap="skin_default/buttons/red.png" transparent="1" alphatest="on" />
<ePixmap position="140,460" zPosition="1" size="140,40" pixmap="skin_default/buttons/green.png" transparent="1" alphatest="on" />
<ePixmap position="280,460" zPosition="1" size="140,40" pixmap="skin_default/buttons/yellow.png" transparent="1" alphatest="on" />
<ePixmap position="420,460" zPosition="1" size="140,40" pixmap="skin_default/buttons/blue.png" transparent="1" alphatest="on" />
<widget name="key_red" position="0,460" zPosition="2" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" shadowColor="black" shadowOffset="-1,-1" />
<widget name="key_green" position="140,460" zPosition="2" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" shadowColor="black" shadowOffset="-1,-1" />
<widget name="key_yellow" position="280,460" zPosition="2" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" shadowColor="black" shadowOffset="-1,-1" />
<widget name="key_blue" position="420,460" zPosition="2" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" shadowColor="black" shadowOffset="-1,-1" />
<widget name="imageList" position="10,10" zPosition="1" size="680,450" font="Regular;20" scrollbarMode="showOnDemand" transparent="1" />
</screen>"""
def __init__(self, session, online, list=None, multi=None, devrootfs=None ):
Screen.__init__(self, session)
self.session = session
Screen.setTitle(self, _("Flash On the fly (select a image)"))
self["key_green"] = Button(_("Flash"))
self["key_red"] = Button(_("Exit"))
self["key_blue"] = Button("")
self["key_yellow"] = Button("")
self.imagesCounter = imagesCounter
self.filename = None
self.imagelist = []
self.simulate = False
self.Online = online
self.List = list
self.multi=multi
self.devrootfs=devrootfs
self.imagePath = imagePath
self.feedurl = images[self.imagesCounter][1]
self["imageList"] = MenuList(self.imagelist)
self["actions"] = ActionMap(["OkCancelActions", "ColorActions"],
{
"green": self.green,
"ok": self.green,
"yellow": self.yellow,
"red": self.quit,
"blue": self.blue,
"cancel": self.quit,
}, -2)
self.onLayoutFinish.append(self.layoutFinished)
def quit(self):
if self.simulate or not self.List == "STARTUP":
fbClass.getInstance().unlock()
self.close()
def blue(self):
if self.Online:
if self.imagesCounter <= len(images) - 2:
self.imagesCounter = self.imagesCounter + 1
else:
self.imagesCounter = 0
self.feed = images[self.imagesCounter][0]
self.layoutFinished()
return
sel = self["imageList"].l.getCurrentSelection()
if sel == None:
print"Nothing to select !!"
return
self.filename = sel
self.session.openWithCallback(self.RemoveCB, MessageBox, _("Do you really want to delete\n%s ?") % (sel), MessageBox.TYPE_YESNO)
def RemoveCB(self, ret):
if ret:
if os.path.exists(self.imagePath + "/" + self.filename):
os.remove(self.imagePath + "/" + self.filename)
self.imagelist.remove(self.filename)
self["imageList"].l.setList(self.imagelist)
def box(self):
box = getBoxType()
machinename = getMachineName()
if box in ('uniboxhd1', 'uniboxhd2', 'uniboxhd3'):
box = "ventonhdx"
elif box == 'odinm6':
box = getMachineName().lower()
elif box == "inihde" and machinename.lower() == "xpeedlx":
box = "xpeedlx"
elif box in ('xpeedlx1', 'xpeedlx2'):
box = "xpeedlx"
elif box == "inihde" and machinename.lower() == "hd-1000":
box = "sezam-1000hd"
elif box == "ventonhdx" and machinename.lower() == "hd-5000":
box = "sezam-5000hd"
elif box == "ventonhdx" and machinename.lower() == "premium twin":
box = "miraclebox-twin"
elif box == "xp1000" and machinename.lower() == "sf8 hd":
box = "sf8"
elif box.startswith('et') and not box in ('et8000', 'et8500', 'et8500s', 'et10000'):
box = box[0:3] + 'x00'
elif box == "odinm9":
box = 'maram9'
elif box == "dm525":
box = 'dm520'
return box
def green(self, ret = None):
sel = self["imageList"].l.getCurrentSelection()
if sel == None:
print"Nothing to select !!"
return
file_name = self.imagePath + "/" + sel
self.filename = file_name
self.sel = sel
box = self.box()
self.hide()
if self.Online:
if self.imagesCounter == 0:
url = self.feedurl + "/" + sel
else:
url = self.feedurl + "/" + box + "/" + sel
#print "URL:", url
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (sel, file_size)
job = ImageDownloadJob(url, file_name, sel)
job.afterEvent = "close"
job_manager.AddJob(job)
job_manager.failed_jobs = []
self.session.openWithCallback(self.ImageDownloadCB, JobView, job, backgroundable = False, afterEventChangeable = False)
else:
if sel == str(flashTmp):
self.Start_Flashing()
else:
self.unzip_image(self.filename, flashPath)
def ImageDownloadCB(self, ret):
if ret:
return
if job_manager.active_job:
job_manager.active_job = None
self.close()
return
if len(job_manager.failed_jobs) == 0:
self.session.openWithCallback(self.askUnzipCB, MessageBox, _("The image is downloaded. Do you want to flash now?"), MessageBox.TYPE_YESNO)
else:
self.session.open(MessageBox, _("Download Failed !!"), type = MessageBox.TYPE_ERROR)
def askUnzipCB(self, ret):
if ret:
self.unzip_image(self.filename, flashPath)
else:
self.show()
def unzip_image(self, filename, path):
if getBoxType() in "dm7080" "dm820" "dm520" "dm525":
print "Untaring %s to %s" %(filename,path)
os.system('mkdir /dbackup.new')
self.session.openWithCallback(self.cmdFinished, Console, title = _("Untaring files, Please wait ..."), cmdlist = ['tar -xJf ' + filename + ' -C ' + '/dbackup.new', "sleep 3"], closeOnSuccess = True)
else:
print "Unzip %s to %s" %(filename,path)
self.session.openWithCallback(self.cmdFinished, Console, title = _("Unzipping files, Please wait ..."), cmdlist = ['unzip ' + filename + ' -o -d ' + path, "sleep 3"], closeOnSuccess = True)
def cmdFinished(self):
self.prepair_flashtmp(flashPath)
self.Start_Flashing()
def Start_Flashing(self):
if getBoxType() in "dm7080" "dm820" "dm520" "dm525":
os.system('/usr/lib/enigma2/python/Plugins/Extensions/dBackup/bin/swaproot 0')
else:
print "Start Flashing"
cmdlist = []
if os.path.exists(ofgwritePath):
text = _("Flashing: ")
if self.simulate:
text += _("Simulate (no write)")
if SystemInfo["HaveMultiBoot"]:
cmdlist.append("%s -n -r -k -m%s %s > /dev/null 2>&1" % (ofgwritePath, self.multi, flashTmp))
else:
cmdlist.append("%s -n -r -k %s > /dev/null 2>&1" % (ofgwritePath, flashTmp))
self.close()
message = "echo -e '\n"
message += _('Show only found image and mtd partitions.\n')
message += "'"
else:
text += _("root and kernel")
if SystemInfo["HaveMultiBoot"]:
if not self.List == "STARTUP":
os.system('mkfs.ext4 -F ' + self.devrootfs)
cmdlist.append("%s -r -k -m%s %s > /dev/null 2>&1" % (ofgwritePath, self.multi, flashTmp))
if not self.List == "STARTUP":
cmdlist.append("umount -fl /oldroot_bind")
cmdlist.append("umount -fl /newroot")
else:
cmdlist.append("%s -r -k %s > /dev/null 2>&1" % (ofgwritePath, flashTmp))
message = "echo -e '\n"
if not self.List == "STARTUP" and SystemInfo["HaveMultiBoot"]:
message += _('ofgwrite flashing ready.\n')
message += _('please press exit to go back to the menu.\n')
else:
message += _('ofgwrite will stop enigma2 now to run the flash.\n')
message += _('Your STB will freeze during the flashing process.\n')
message += _('Please: DO NOT reboot your STB and turn off the power.\n')
message += _('The image or kernel will be flashing and auto booted in few minutes.\n')
if self.box() == 'gb800solo':
message += _('GB800SOLO takes about 20 mins !!\n')
message += "'"
cmdlist.append(message)
self.session.open(Console, title = text, cmdlist = cmdlist, finishedCallback = self.quit, closeOnSuccess = False)
if not self.List == "STARTUP":
self.close()
def prepair_flashtmp(self, tmpPath):
if os.path.exists(flashTmp):
flashTmpold = flashTmp + 'old'
os.system('mv %s %s' %(flashTmp, flashTmpold))
os.system('rm -rf %s' %flashTmpold)
if not os.path.exists(flashTmp):
os.mkdir(flashTmp)
kernel = True
rootfs = True
for path, subdirs, files in os.walk(tmpPath):
for name in files:
if name.find('kernel') > -1 and name.endswith('.bin') and kernel:
binfile = os.path.join(path, name)
dest = flashTmp + '/%s' %KERNELBIN
shutil.copyfile(binfile, dest)
kernel = False
elif name.find('root') > -1 and (name.endswith('.bin') or name.endswith('.jffs2') or name.endswith('.bz2')) and rootfs:
binfile = os.path.join(path, name)
dest = flashTmp + '/%s' %ROOTFSBIN
shutil.copyfile(binfile, dest)
rootfs = False
elif name.find('uImage') > -1 and kernel:
binfile = os.path.join(path, name)
dest = flashTmp + '/uImage'
shutil.copyfile(binfile, dest)
kernel = False
elif name.find('e2jffs2') > -1 and name.endswith('.img') and rootfs:
binfile = os.path.join(path, name)
dest = flashTmp + '/e2jffs2.img'
shutil.copyfile(binfile, dest)
rootfs = False
def yellow(self):
if not self.Online:
self.session.openWithCallback(self.DeviceBrowserClosed, DeviceBrowser, None, matchingPattern="^.*\.(zip|bin|jffs2)", showDirectories=True, showMountpoints=True, inhibitMounts=["/autofs/sr0/"])
def DeviceBrowserClosed(self, path, filename, binorzip):
if path:
print path, filename, binorzip
strPath = str(path)
if strPath[-1] == '/':
strPath = strPath[:-1]
self.imagePath = strPath
if os.path.exists(flashTmp):
os.system('rm -rf ' + flashTmp)
os.mkdir(flashTmp)
if binorzip == 0:
for files in os.listdir(self.imagePath):
if files.endswith(".bin") or files.endswith('.jffs2') or files.endswith('.img'):
self.prepair_flashtmp(strPath)
break
self.Start_Flashing()
elif binorzip == 1:
self.unzip_image(strPath + '/' + filename, flashPath)
else:
self.layoutFinished()
else:
self.imagePath = imagePath
def layoutFinished(self):
box = self.box()
self.imagelist = []
if self.Online:
self["key_yellow"].setText("")
self.feedurl = images[self.imagesCounter][1]
self["key_blue"].setText(images[self.imagesCounter][0])
if self.imagesCounter == 0:
url = '%s' % (self.feedurl)
else:
url = '%s/%s' % (self.feedurl,box)
req = urllib2.Request(url)
try:
response = urllib2.urlopen(req)
except urllib2.URLError as e:
print "URL ERROR: %s" % e
return
try:
the_page = response.read()
except urllib2.HTTPError as e:
print "HTTP download ERROR: %s" % e.code
return
lines = the_page.split('\n')
tt = len(box)
for line in lines:
if line.find(box + "-") > -1:
t = line.find('<a href="')
if line.find('zip"') > -1:
e = line.find('zip"')
self.imagelist.append(line[t+9:e+3])
if line.find('.xz"') > -1:
e = line.find('xz"')
self.imagelist.append(line[t+9:e+2])
else:
self["key_blue"].setText(_("Delete"))
self["key_yellow"].setText(_("Devices"))
for name in os.listdir(self.imagePath):
if name.endswith(".zip") or name.endswith(".xz"): # and name.find(box) > 1:
self.imagelist.append(name)
# if name.find(box):
# self.imagelist.append(name)
self.imagelist.sort()
if os.path.exists(flashTmp):
for file in os.listdir(flashTmp):
if file.find(".bin") > -1:
self.imagelist.insert( 0, str(flashTmp))
break
self["imageList"].l.setList(self.imagelist)
def SaveEPG(self):
from enigma import eEPGCache
epgcache = eEPGCache.getInstance()
epgcache.save()
class ImageDownloadJob(Job):
def __init__(self, url, filename, file):
Job.__init__(self, _("Downloading %s") %file)
ImageDownloadTask(self, url, filename)
class DownloaderPostcondition(Condition):
def check(self, task):
return task.returncode == 0
def getErrorMessage(self, task):
return self.error_message
class ImageDownloadTask(Task):
def __init__(self, job, url, path):
Task.__init__(self, job, _("Downloading"))
self.postconditions.append(DownloaderPostcondition())
self.job = job
self.url = url
self.path = path
self.error_message = ""
self.last_recvbytes = 0
self.error_message = None
self.download = None
self.aborted = False
def run(self, callback):
self.callback = callback
self.download = downloadWithProgress(self.url,self.path)
self.download.addProgress(self.download_progress)
self.download.start().addCallback(self.download_finished).addErrback(self.download_failed)
print "[ImageDownloadTask] downloading", self.url, "to", self.path
def abort(self):
print "[ImageDownloadTask] aborting", self.url
if self.download:
self.download.stop()
self.aborted = True
def download_progress(self, recvbytes, totalbytes):
if ( recvbytes - self.last_recvbytes ) > 100000: # anti-flicker
self.progress = int(100*(float(recvbytes)/float(totalbytes)))
self.name = _("Downloading") + ' ' + _("%d of %d kBytes") % (recvbytes/1024, totalbytes/1024)
self.last_recvbytes = recvbytes
def download_failed(self, failure_instance=None, error_message=""):
self.error_message = error_message
if error_message == "" and failure_instance is not None:
self.error_message = failure_instance.getErrorMessage()
Task.processFinished(self, 1)
def download_finished(self, string=""):
if self.aborted:
self.finish(aborted = True)
else:
Task.processFinished(self, 0)
class DeviceBrowser(Screen, HelpableScreen):
skin = """
<screen name="DeviceBrowser" position="center,center" size="520,430" >
<ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on" />
<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<widget source="message" render="Label" position="5,50" size="510,150" font="Regular;16" />
<widget name="filelist" position="5,210" size="510,220" scrollbarMode="showOnDemand" />
</screen>"""
def __init__(self, session, startdir, message="", showDirectories = True, showFiles = True, showMountpoints = True, matchingPattern = "", useServiceRef = False, inhibitDirs = False, inhibitMounts = False, isTop = False, enableWrapAround = False, additionalExtensions = None):
Screen.__init__(self, session)
HelpableScreen.__init__(self)
Screen.setTitle(self, _("Please select medium"))
self["key_red"] = StaticText(_("Cancel"))
self["key_green"] = StaticText()
self["message"] = StaticText(message)
self.filelist = FileList(startdir, showDirectories = showDirectories, showFiles = showFiles, showMountpoints = showMountpoints, matchingPattern = matchingPattern, useServiceRef = useServiceRef, inhibitDirs = inhibitDirs, inhibitMounts = inhibitMounts, isTop = isTop, enableWrapAround = enableWrapAround, additionalExtensions = additionalExtensions)
self["filelist"] = self.filelist
self["FilelistActions"] = ActionMap(["SetupActions", "ColorActions"],
{
"green": self.use,
"red": self.exit,
"ok": self.ok,
"cancel": self.exit
})
hotplugNotifier.append(self.hotplugCB)
self.onShown.append(self.updateButton)
self.onClose.append(self.removeHotplug)
def hotplugCB(self, dev, action):
print "[hotplugCB]", dev, action
self.updateButton()
def updateButton(self):
if self["filelist"].getFilename() or self["filelist"].getCurrentDirectory():
self["key_green"].text = _("Flash")
else:
self["key_green"].text = ""
def removeHotplug(self):
print "[removeHotplug]"
hotplugNotifier.remove(self.hotplugCB)
def ok(self):
if self.filelist.canDescent():
if self["filelist"].showMountpoints == True and self["filelist"].showDirectories == False:
self.use()
else:
self.filelist.descent()
def use(self):
print "[use]", self["filelist"].getCurrentDirectory(), self["filelist"].getFilename()
if self["filelist"].getFilename() is not None and self["filelist"].getCurrentDirectory() is not None:
if self["filelist"].getFilename().endswith(".bin") or self["filelist"].getFilename().endswith(".jffs2"):
self.close(self["filelist"].getCurrentDirectory(), self["filelist"].getFilename(), 0)
elif self["filelist"].getFilename().endswith(".zip"):
self.close(self["filelist"].getCurrentDirectory(), self["filelist"].getFilename(), 1)
else:
return
def exit(self):
self.close(False, False, -1)