Add files via upload

This commit is contained in:
gutosie
2020-01-07 11:19:16 +02:00
committed by GitHub
parent 6c78fc2456
commit 71f57c6ffb
11 changed files with 3513 additions and 0 deletions

968
NeoBoot/files/Harddisk.py Normal file
View File

@@ -0,0 +1,968 @@
# -*- coding: utf-8 -*-
#from __future__ import print_function
#from Plugins.Extensions.NeoBoot.__init__ import _
import os
import time
from Tools.Directories import fileExists, pathExists#, fileCheck
from Tools.CList import CList
from Components.SystemInfo import SystemInfo
from Components.Console import Console
from Task import LoggingTask
import Task
def readFile(filename):
file = open(filename)
data = file.read().strip()
file.close()
return data
def getProcMounts():
try:
mounts = open('/proc/mounts', 'r')
except IOError as ex:
print '[Harddisk] Failed to open /proc/mounts', ex
return []
result = [ line.strip().split(' ') for line in mounts ]
for item in result:
item[1] = item[1].replace('\\040', ' ')
return result
def getNonNetworkMediaMounts():
return [ x[1] for x in getProcMounts() if x[1].startswith('/media/') and not x[0].startswith('//') ]
def isFileSystemSupported(filesystem):
try:
for fs in open('/proc/filesystems', 'r'):
if fs.strip().endswith(filesystem):
return True
return False
except Exception as ex:
print '[Harddisk] Failed to read /proc/filesystems:', ex
def findMountPoint(path):
path = os.path.abspath(path)
while not os.path.ismount(path):
path = os.path.dirname(path)
return path
DEVTYPE_UDEV = 0
DEVTYPE_DEVFS = 1
class Harddisk():
def __init__(self, device, removable = False):
self.device = device
if os.access('/dev/.udev', 0):
self.type = DEVTYPE_UDEV
elif os.access('/dev/.devfsd', 0):
self.type = DEVTYPE_DEVFS
else:
print '[Harddisk] Unable to determine structure of /dev'
self.type = -1
self.card = False
self.max_idle_time = 0
self.idle_running = False
self.last_access = time.time()
self.last_stat = 0
self.timer = None
self.is_sleeping = False
self.dev_path = ''
self.disk_path = ''
self.mount_path = None
self.mount_device = None
self.phys_path = os.path.realpath(self.sysfsPath('device'))
self.removable = removable
self.internal = 'pci' in self.phys_path or 'ahci' in self.phys_path or 'sata' in self.phys_path
try:
data = open('/sys/block/%s/queue/rotational' % device, 'r').read().strip()
self.rotational = int(data)
except:
self.rotational = True
if self.type == DEVTYPE_UDEV:
self.dev_path = '/dev/' + self.device
self.disk_path = self.dev_path
self.card = 'sdhci' in self.phys_path
elif self.type == DEVTYPE_DEVFS:
tmp = readFile(self.sysfsPath('dev')).split(':')
s_major = int(tmp[0])
s_minor = int(tmp[1])
for disc in os.listdir('/dev/discs'):
dev_path = os.path.realpath('/dev/discs/' + disc)
disk_path = dev_path + '/disc'
try:
rdev = os.stat(disk_path).st_rdev
except OSError:
continue
if s_major == os.major(rdev) and s_minor == os.minor(rdev):
self.dev_path = dev_path
self.disk_path = disk_path
break
self.card = self.device[:2] == 'hd' and 'host0' not in self.dev_path
print '[Harddisk] new device', self.device, '->', self.dev_path, '->', self.disk_path
if not removable and not self.card:
self.startIdle()
return
def __lt__(self, ob):
return self.device < ob.device
def partitionPath(self, n):
if self.type == DEVTYPE_UDEV:
if self.dev_path.startswith('/dev/mmcblk0'):
return self.dev_path + 'p' + n
else:
return self.dev_path + n
elif self.type == DEVTYPE_DEVFS:
return self.dev_path + '/part' + n
def sysfsPath(self, filename):
return os.path.join('/sys/block/', self.device, filename)
def stop(self):
if self.timer:
self.timer.stop()
self.timer.callback.remove(self.runIdle)
def bus(self):
ret = _('External')
if self.type == DEVTYPE_UDEV:
type_name = ' (SD/MMC)'
elif self.type == DEVTYPE_DEVFS:
type_name = ' (CF)'
if self.card:
ret += type_name
else:
if self.internal:
ret = _('Internal')
if not self.rotational:
ret += ' (SSD)'
return ret
def diskSize(self):
cap = 0
try:
line = readFile(self.sysfsPath('size'))
cap = int(line)
return cap / 1000 * 512 / 1000
except:
dev = self.findMount()
if dev:
try:
stat = os.statvfs(dev)
cap = int(stat.f_blocks * stat.f_bsize)
return cap / 1000 / 1000
except:
pass
return cap
def capacity(self):
cap = self.diskSize()
if cap == 0:
return ''
if cap < 1000:
return _('%03d MB') % cap
return _('%d.%03d GB') % (cap / 1000, cap % 1000)
def model(self):
try:
if self.device[:2] == 'hd':
return readFile('/proc/ide/' + self.device + '/model')
if self.device[:2] == 'sd':
vendor = readFile(self.sysfsPath('device/vendor'))
model = readFile(self.sysfsPath('device/model'))
return vendor + '(' + model + ')'
if self.device.startswith('mmcblk0'):
return readFile(self.sysfsPath('device/name'))
raise Exception, '[Harddisk] no hdX or sdX or mmcX'
except Exception as e:
print '[Harddisk] Failed to get model:', e
return '-?-'
def free(self):
dev = self.findMount()
if dev:
try:
stat = os.statvfs(dev)
return stat.f_bfree / 1000 * (stat.f_bsize / 1024)
except:
pass
return -1
def numPartitions(self):
numPart = -1
if self.type == DEVTYPE_UDEV:
try:
devdir = os.listdir('/dev')
except OSError:
return -1
for filename in devdir:
if filename.startswith(self.device):
numPart += 1
elif self.type == DEVTYPE_DEVFS:
try:
idedir = os.listdir(self.dev_path)
except OSError:
return -1
for filename in idedir:
if filename.startswith('disc'):
numPart += 1
if filename.startswith('part'):
numPart += 1
return numPart
def mountDevice(self):
for parts in getProcMounts():
if os.path.realpath(parts[0]).startswith(self.dev_path):
self.mount_device = parts[0]
self.mount_path = parts[1]
return parts[1]
return None
def enumMountDevices(self):
for parts in getProcMounts():
if os.path.realpath(parts[0]).startswith(self.dev_path):
yield parts[1]
def findMount(self):
if self.mount_path is None:
return self.mountDevice()
else:
return self.mount_path
def unmount(self):
dev = self.mountDevice()
if dev is None:
return 0
else:
cmd = 'umount ' + dev
print '[Harddisk]', cmd
res = os.system(cmd)
return res >> 8
def createPartition(self):
cmd = 'printf "8,\n;0,0\n;0,0\n;0,0\ny\n" | sfdisk -f -uS ' + self.disk_path
res = os.system(cmd)
return res >> 8
def mkfs(self):
return 1
def mount(self):
if self.mount_device is None:
dev = self.partitionPath('1')
else:
dev = self.mount_device
try:
fstab = open('/etc/fstab')
lines = fstab.readlines()
fstab.close()
except IOError:
return -1
for line in lines:
parts = line.strip().split(' ')
fspath = os.path.realpath(parts[0])
if fspath == dev:
print '[Harddisk] mounting:', fspath
cmd = 'mount -t auto ' + fspath
res = os.system(cmd)
return res >> 8
res = -1
if self.type == DEVTYPE_UDEV:
res = os.system('hdparm -z ' + self.disk_path)
from time import sleep
sleep(3)
return res >> 8
def fsck(self):
return 1
def killPartitionTable(self):
zero = 512 * '\x00'
h = open(self.dev_path, 'wb')
for i in range(9):
h.write(zero)
h.close()
def killPartition(self, n):
zero = 512 * '\x00'
part = self.partitionPath(n)
h = open(part, 'wb')
for i in range(3):
h.write(zero)
h.close()
def createInitializeJob(self):
job = Task.Job(_('Initializing storage device...'))
size = self.diskSize()
print '[HD] size: %s MB' % size
task = UnmountTask(job, self)
task = Task.PythonTask(job, _('Removing partition table'))
task.work = self.killPartitionTable
task.weighting = 1
task = Task.LoggingTask(job, _('Rereading partition table'))
task.weighting = 1
task.setTool('hdparm')
task.args.append('-z')
task.args.append(self.disk_path)
task = Task.ConditionTask(job, _('Waiting for partition'), timeoutCount=20)
task.check = lambda : not os.path.exists(self.partitionPath('1'))
task.weighting = 1
if os.path.exists('/usr/sbin/parted'):
use_parted = True
elif size > 2097151:
addInstallTask(job, 'parted')
use_parted = True
else:
use_parted = False
task = Task.LoggingTask(job, _('Creating partition'))
task.weighting = 5
if use_parted:
task.setTool('parted')
if size < 1024:
alignment = 'min'
else:
alignment = 'opt'
if size > 2097151:
parttype = 'gpt'
else:
parttype = 'msdos'
task.args += ['-a',
alignment,
'-s',
self.disk_path,
'mklabel',
parttype,
'mkpart',
'primary',
'0%',
'100%']
else:
task.setTool('sfdisk')
task.args.append('-f')
task.args.append('-uS')
task.args.append(self.disk_path)
if size > 128000:
print '[HD] Detected >128GB disk, using 4k alignment'
task.initial_input = '8,,L\n;0,0\n;0,0\n;0,0\ny\n'
else:
task.initial_input = ',,L\n;\n;\n;\ny\n'
task = Task.ConditionTask(job, _('Waiting for partition'))
task.check = lambda : os.path.exists(self.partitionPath('1'))
task.weighting = 1
task = MkfsTask(job, _('Creating filesystem'))
big_o_options = ['dir_index']
if isFileSystemSupported('ext4'):
task.setTool('mkfs.ext4')
if size > 20000:
try:
version = map(int, open('/proc/version', 'r').read().split(' ', 4)[2].split('.', 2)[:2])
if version[0] > 3 or version[0] > 2 and version[1] >= 2:
task.args += ['-C', '262144']
big_o_options.append('bigalloc')
except Exception as ex:
print 'Failed to detect Linux version:', ex
else:
task.setTool('mkfs.ext3')
if size > 250000:
task.args += ['-T',
'largefile',
'-N',
'262144']
big_o_options.append('sparse_super')
elif size > 16384:
task.args += ['-T', 'largefile']
big_o_options.append('sparse_super')
elif size > 2048:
task.args += ['-T',
'largefile',
'-N',
str(size * 32)]
task.args += ['-m0',
'-O',
','.join(big_o_options),
self.partitionPath('1')]
task = MountTask(job, self)
task.weighting = 3
task = Task.ConditionTask(job, _('Waiting for mount'), timeoutCount=20)
task.check = self.mountDevice
task.weighting = 1
return job
def initialize(self):
return -5
def check(self):
return -5
def createCheckJob(self):
job = Task.Job(_('Checking filesystem...'))
if self.findMount():
UnmountTask(job, self)
dev = self.mount_device
else:
dev = self.partitionPath('1')
task = Task.LoggingTask(job, 'fsck')
task.setTool('fsck.ext3')
task.args.append('-f')
task.args.append('-p')
task.args.append(dev)
MountTask(job, self)
task = Task.ConditionTask(job, _('Waiting for mount'))
task.check = self.mountDevice
return job
def getDeviceDir(self):
return self.dev_path
def getDeviceName(self):
return self.disk_path
def readStats(self):
try:
l = open('/sys/block/%s/stat' % self.device).read()
except IOError:
return (-1, -1)
data = l.split(None, 5)
return (int(data[0]), int(data[4]))
def startIdle(self):
from enigma import eTimer
if self.bus() == _('External'):
Console().ePopen(('sdparm',
'sdparm',
'--set=SCT=0',
self.disk_path))
else:
Console().ePopen(('hdparm',
'hdparm',
'-S0',
self.disk_path))
self.timer = eTimer()
self.timer.callback.append(self.runIdle)
self.idle_running = True
self.setIdleTime(self.max_idle_time)
def runIdle(self):
if not self.max_idle_time:
return
t = time.time()
idle_time = t - self.last_access
stats = self.readStats()
l = sum(stats)
if l != self.last_stat and l >= 0:
self.last_stat = l
self.last_access = t
idle_time = 0
self.is_sleeping = False
if idle_time >= self.max_idle_time and not self.is_sleeping:
self.setSleep()
self.is_sleeping = True
def setSleep(self):
if self.bus() == _('External'):
Console().ePopen(('sdparm',
'sdparm',
'--flexible',
'--readonly',
'--command=stop',
self.disk_path))
else:
Console().ePopen(('hdparm',
'hdparm',
'-y',
self.disk_path))
def setIdleTime(self, idle):
self.max_idle_time = idle
if self.idle_running:
if not idle:
self.timer.stop()
else:
self.timer.start(idle * 100, False)
def isSleeping(self):
return self.is_sleeping
class Partition():
def __init__(self, mountpoint, device = None, description = '', force_mounted = False):
self.mountpoint = mountpoint
self.description = description
self.force_mounted = mountpoint and force_mounted
self.is_hotplug = force_mounted
self.device = device
def __str__(self):
return 'Partition(mountpoint=%s,description=%s,device=%s)' % (self.mountpoint, self.description, self.device)
def stat(self):
if self.mountpoint:
return os.statvfs(self.mountpoint)
raise OSError, 'Device %s is not mounted' % self.device
def free(self):
try:
s = self.stat()
return s.f_bavail * s.f_bsize
except OSError:
return None
return None
def total(self):
try:
s = self.stat()
return s.f_blocks * s.f_bsize
except OSError:
return None
return None
def tabbedDescription(self):
if self.mountpoint.startswith('/media/net') or self.mountpoint.startswith('/media/autofs'):
return self.description
return self.description + '\t' + self.mountpoint
def mounted(self, mounts = None):
if self.force_mounted:
return True
else:
if self.mountpoint:
if mounts is None:
mounts = getProcMounts()
for parts in mounts:
if self.mountpoint.startswith(parts[1]):
return True
return False
def filesystem(self, mounts = None):
if self.mountpoint:
if mounts is None:
mounts = getProcMounts()
for fields in mounts:
if self.mountpoint.endswith('/') and not self.mountpoint == '/':
if fields[1] + '/' == self.mountpoint:
return fields[2]
elif fields[1] == self.mountpoint:
return fields[2]
return ''
def addInstallTask(job, package):
task = Task.LoggingTask(job, 'update packages')
task.setTool('opkg')
task.args.append('update')
task = Task.LoggingTask(job, 'Install ' + package)
task.setTool('opkg')
task.args.append('install')
task.args.append(package)
class HarddiskManager():
def __init__(self):
self.hdd = []
self.cd = ''
self.partitions = []
self.devices_scanned_on_init = []
self.on_partition_list_change = CList()
self.enumerateBlockDevices()
p = (('/media/hdd', _('Hard disk')),
('/media/card', _('Card')),
('/media/cf', _('Compact flash')),
('/media/mmc1', _('MMC card')),
('/media/net', _('Network mount')),
('/media/net1', _('Network mount %s') % '1'),
('/media/net2', _('Network mount %s') % '2'),
('/media/net3', _('Network mount %s') % '3'),
('/media/ram', _('Ram disk')),
('/media/usb', _('USB stick')),
('/media/usb1', _('USB1 stick')),
('/media/usb2', _('USB2 stick')),
('/', _('Internal flash')))
known = set([ os.path.normpath(a.mountpoint) for a in self.partitions if a.mountpoint ])
for m, d in p:
if m not in known and os.path.ismount(m):
self.partitions.append(Partition(mountpoint=m, description=d))
def getBlockDevInfo(self, blockdev):
HasMMC = fileExists('/proc/cmdline') and 'root=/dev/mmcblk' in open('/proc/cmdline', 'r').read()
devpath = '/sys/block/' + blockdev
error = False
removable = False
blacklisted = False
is_cdrom = False
partitions = []
try:
if os.path.exists(devpath + '/removable'):
removable = bool(int(readFile(devpath + '/removable')))
if os.path.exists(devpath + '/dev'):
dev = int(readFile(devpath + '/dev').split(':')[0])
else:
dev = None
blacklisted = dev in [1,
7,
31,
253,
254] + (['HasMMC'] and [179] or [])
if blockdev[0:2] == 'sr':
is_cdrom = True
if blockdev[0:2] == 'hd':
try:
media = readFile('/proc/ide/%s/media' % blockdev)
if 'cdrom' in media:
is_cdrom = True
except IOError:
error = True
if not is_cdrom and os.path.exists(devpath):
for partition in os.listdir(devpath):
if partition[0:len(blockdev)] != blockdev:
continue
partitions.append(partition)
else:
self.cd = blockdev
except IOError:
error = True
medium_found = True
try:
open('/dev/' + blockdev).close()
except IOError as err:
if err.errno == 159:
medium_found = False
return (error,
blacklisted,
removable,
is_cdrom,
partitions,
medium_found)
def enumerateBlockDevices(self):
print '[Harddisk] enumerating block devices...'
for blockdev in os.listdir('/sys/block'):
error, blacklisted, removable, is_cdrom, partitions, medium_found = self.addHotplugPartition(blockdev)
if not error and not blacklisted and medium_found:
for part in partitions:
self.addHotplugPartition(part)
self.devices_scanned_on_init.append((blockdev,
removable,
is_cdrom,
medium_found))
def getAutofsMountpoint(self, device):
r = self.getMountpoint(device)
if r is None:
return '/media/' + device
else:
return r
def getMountpoint(self, device):
dev = '/dev/%s' % device
for item in getProcMounts():
if item[0] == dev:
return item[1]
return None
def addHotplugPartition(self, device, physdev = None):
if not physdev:
dev, part = self.splitDeviceName(device)
try:
physdev = os.path.realpath('/sys/block/' + dev + '/device')[4:]
except OSError:
physdev = dev
print "couldn't determine blockdev physdev for device", device
error, blacklisted, removable, is_cdrom, partitions, medium_found = self.getBlockDevInfo(device)
if not blacklisted and medium_found:
description = self.getUserfriendlyDeviceName(device, physdev)
p = Partition(mountpoint=self.getMountpoint(device), description=description, force_mounted=True, device=device)
self.partitions.append(p)
if p.mountpoint:
self.on_partition_list_change('add', p)
l = len(device)
if l and (not device[l - 1].isdigit() or device == 'mmcblk0'):
self.hdd.append(Harddisk(device, removable))
self.hdd.sort()
SystemInfo['Harddisk'] = True
return (error,
blacklisted,
removable,
is_cdrom,
partitions,
medium_found)
def addHotplugAudiocd(self, device, physdev = None):
if not physdev:
dev, part = self.splitDeviceName(device)
try:
physdev = os.path.realpath('/sys/block/' + dev + '/device')[4:]
except OSError:
physdev = dev
print "couldn't determine blockdev physdev for device", device
error, blacklisted, removable, is_cdrom, partitions, medium_found = self.getBlockDevInfo(device)
if not blacklisted and medium_found:
description = self.getUserfriendlyDeviceName(device, physdev)
p = Partition(mountpoint='/media/audiocd', description=description, force_mounted=True, device=device)
self.partitions.append(p)
self.on_partition_list_change('add', p)
SystemInfo['Harddisk'] = False
return (error,
blacklisted,
removable,
is_cdrom,
partitions,
medium_found)
def removeHotplugPartition(self, device):
for x in self.partitions[:]:
if x.device == device:
self.partitions.remove(x)
if x.mountpoint:
self.on_partition_list_change('remove', x)
l = len(device)
if l and not device[l - 1].isdigit():
for hdd in self.hdd:
if hdd.device == device:
hdd.stop()
self.hdd.remove(hdd)
break
SystemInfo['Harddisk'] = len(self.hdd) > 0
def HDDCount(self):
return len(self.hdd)
def HDDList(self):
list = []
for hd in self.hdd:
hdd = hd.model() + ' - ' + hd.bus()
cap = hd.capacity()
if cap != '':
hdd += ' (' + cap + ')'
list.append((hdd, hd))
return list
def getCD(self):
return self.cd
def getMountedPartitions(self, onlyhotplug = False, mounts = None):
if mounts is None:
mounts = getProcMounts()
parts = [ x for x in self.partitions if (x.is_hotplug or not onlyhotplug) and x.mounted(mounts) ]
devs = set([ x.device for x in parts ])
for devname in devs.copy():
if not devname:
continue
dev, part = self.splitDeviceName(devname)
if part and dev in devs:
devs.remove(dev)
return [ x for x in parts if not x.device or x.device in devs ]
def splitDeviceName(self, devname):
dev = devname[:3]
part = devname[3:]
for p in part:
if not p.isdigit():
return (devname, 0)
return (dev, part and int(part) or 0)
def getUserfriendlyDeviceName(self, dev, phys):
dev, part = self.splitDeviceName(dev)
description = _('External Storage %s') % dev
try:
description = readFile('/sys' + phys + '/model')
except IOError as s:
print "couldn't read model: ", s
if part and part != 1:
description += _(' (Partition %d)') % part
return description
def addMountedPartition(self, device, desc):
for x in self.partitions:
if x.mountpoint == device:
return
self.partitions.append(Partition(mountpoint=device, description=desc))
def removeMountedPartition(self, mountpoint):
for x in self.partitions[:]:
if x.mountpoint == mountpoint:
self.partitions.remove(x)
self.on_partition_list_change('remove', x)
def setDVDSpeed(self, device, speed = 0):
ioctl_flag = int(21282)
if not device.startswith('/'):
device = '/dev/' + device
try:
from fcntl import ioctl
cd = open(device)
ioctl(cd.fileno(), ioctl_flag, speed)
cd.close()
except Exception as ex:
print '[Harddisk] Failed to set %s speed to %s' % (device, speed), ex
class UnmountTask(Task.LoggingTask):
def __init__(self, job, hdd):
Task.LoggingTask.__init__(self, job, _('Unmount'))
self.hdd = hdd
self.mountpoints = []
def prepare(self):
try:
dev = self.hdd.disk_path.split('/')[-1]
open('/dev/nomount.%s' % dev, 'wb').close()
except Exception as e:
print 'ERROR: Failed to create /dev/nomount file:', e
self.setTool('umount')
self.args.append('-f')
for dev in self.hdd.enumMountDevices():
self.args.append(dev)
self.postconditions.append(Task.ReturncodePostcondition())
self.mountpoints.append(dev)
if not self.mountpoints:
print 'UnmountTask: No mountpoints found?'
self.cmd = 'true'
self.args = [self.cmd]
def afterRun(self):
for path in self.mountpoints:
try:
os.rmdir(path)
except Exception as ex:
print "Failed to remove path '%s':" % path, ex
class MountTask(Task.LoggingTask):
def __init__(self, job, hdd):
Task.LoggingTask.__init__(self, job, _('Mount'))
self.hdd = hdd
def prepare(self):
try:
dev = self.hdd.disk_path.split('/')[-1]
os.unlink('/dev/nomount.%s' % dev)
except Exception as e:
print 'ERROR: Failed to remove /dev/nomount file:', e
if self.hdd.mount_device is None:
dev = self.hdd.partitionPath('1')
else:
dev = self.hdd.mount_device
fstab = open('/etc/fstab')
lines = fstab.readlines()
fstab.close()
for line in lines:
parts = line.strip().split(' ')
fspath = os.path.realpath(parts[0])
if os.path.realpath(fspath) == dev:
self.setCmdline('mount -t auto ' + fspath)
self.postconditions.append(Task.ReturncodePostcondition())
return
if self.hdd.type == DEVTYPE_UDEV:
self.setCmdline('sleep 2; hdparm -z ' + self.hdd.disk_path)
self.postconditions.append(Task.ReturncodePostcondition())
return
class MkfsTask(Task.LoggingTask):
def prepare(self):
self.fsck_state = None
return
def processOutput(self, data):
print '[Mkfs]', data
if 'Writing inode tables:' in data:
self.fsck_state = 'inode'
elif 'Creating journal' in data:
self.fsck_state = 'journal'
self.setProgress(80)
elif 'Writing superblocks ' in data:
self.setProgress(95)
elif self.fsck_state == 'inode':
if '/' in data:
try:
d = data.strip(' \x08\r\n').split('/', 1)
if '\x08' in d[1]:
d[1] = d[1].split('\x08', 1)[0]
self.setProgress(80 * int(d[0]) / int(d[1]))
except Exception as e:
print '[Mkfs] E:', e
return
self.log.append(data)
harddiskmanager = HarddiskManager()
def isSleepStateDevice(device):
ret = os.popen('hdparm -C %s' % device).read()
if 'SG_IO' in ret or 'HDIO_DRIVE_CMD' in ret:
return None
elif 'drive state is: standby' in ret or 'drive state is: idle' in ret:
return True
elif 'drive state is: active/idle' in ret:
return False
else:
return None
def internalHDDNotSleeping(external = False):
state = False
if harddiskmanager.HDDCount():
for hdd in harddiskmanager.HDDList():
if hdd[1].internal or external:
if hdd[1].idle_running and hdd[1].max_idle_time and not hdd[1].isSleeping():
state = True
return state
harddiskmanager = HarddiskManager()
SystemInfo['ext4'] = isFileSystemSupported('ext4') or isFileSystemSupported('ext3')

19
NeoBoot/files/NeoBoot.sh Normal file
View File

@@ -0,0 +1,19 @@
#!/bin/sh
IMAGE=ImageBoot
NEOBOOTMOUNT=$( cat /usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/.location)
if [ -f $NEOBOOTMOUNT/NeoBoot_Backup.tar.gz ] ; then
rm -R $NEOBOOTMOUNT/NeoBoot_Backupt.tar.gz
/bin/tar -czf $NEOBOOTMOUNT/NeoBoot_Backup.tar.gz /usr/lib/enigma2/python/Plugins/Extensions/NeoBoot*/
echo " "
echo "Kopia o nazwie NeoBoot_Backup.tar.gz zostala utworzona w lokalizacji:" $NEOBOOTMOUNT" . "
echo " "
else
/bin/tar -czf $NEOBOOTMOUNT/NeoBoot_Backup.tar.gz /usr/lib/enigma2/python/Plugins/Extensions/NeoBoot*/
echo " "
echo "Kopia o nazwie NeoBoot_Backup.tar.gz zostala utworzona w lokalizacji:" $NEOBOOTMOUNT" . "
echo " "
fi
exit 0

36
NeoBoot/files/S50fat.sh Normal file
View File

@@ -0,0 +1,36 @@
#!/bin/sh
# script gutosie
IMAGEKATALOG=ImageBoot
NEODEVICE=$( cat /usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/.location)
if [ ! -e /usr/bin/ipkg ]; then
ln -sfn /usr/bin/opkg /usr/bin/ipkg
fi
if [ ! -e /usr/bin/ipkg-cl ]; then
ln -sfn /usr/bin/opkg-cl /usr/bin/ipkg-cl
fi
#echo "Start network and telnet ..."
#/etc/init.d/networking stop; sync; /etc/init.d/networking start;
if [ -f /etc/init.d/inadyn-mt ] ; then
/etc/init.d/inadyn-mt start
fi
if [ ! -e $NEODEVICE$IMAGEKATALOG/.neonextboot ]; then
if [ -e /usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/files/neom ]; then
/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/files/neom
fi
fi
if [ -f /etc/rcS.d/S50fat.sh ] ; then
ln -s /usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/files/S50fat.sh /etc/rcS.d/S50neo.sh
telnetd on
echo ok
rm -f /etc/rcS.d/S50fat.sh
echo "file S50fat.sh delete"
fi
echo ok

523
NeoBoot/files/Task.py Normal file
View File

@@ -0,0 +1,523 @@
# -*- coding: utf-8 -*-
#from __future__ import print_function
#from Plugins.Extensions.NeoBoot.__init__ import _
from Tools.CList import CList
class Job(object):
NOT_STARTED, IN_PROGRESS, FINISHED, FAILED = range(4)
def __init__(self, name):
self.tasks = []
self.resident_tasks = []
self.workspace = '/tmp'
self.current_task = 0
self.callback = None
self.name = name
self.finished = False
self.end = 100
self.__progress = 0
self.weightScale = 1
self.afterEvent = None
self.state_changed = CList()
self.status = self.NOT_STARTED
self.onSuccess = None
return
def fromDescription(self, description):
pass
def createDescription(self):
return None
def getProgress(self):
if self.current_task == len(self.tasks):
return self.end
t = self.tasks[self.current_task]
jobprogress = t.weighting * t.progress / float(t.end) + sum([ task.weighting for task in self.tasks[:self.current_task] ])
return int(jobprogress * self.weightScale)
progress = property(getProgress)
def getStatustext(self):
return {self.NOT_STARTED: _('Waiting'),
self.IN_PROGRESS: _('In progress'),
self.FINISHED: _('Finished'),
self.FAILED: _('Failed')}[self.status]
def task_progress_changed_CB(self):
self.state_changed()
def addTask(self, task):
task.job = self
task.task_progress_changed = self.task_progress_changed_CB
self.tasks.append(task)
def start(self, callback):
self.callback = callback
self.restart()
def restart(self):
self.status = self.IN_PROGRESS
self.state_changed()
self.runNext()
sumTaskWeightings = sum([ t.weighting for t in self.tasks ]) or 1
self.weightScale = self.end / float(sumTaskWeightings)
def runNext(self):
if self.current_task == len(self.tasks):
if len(self.resident_tasks) == 0:
self.status = self.FINISHED
self.state_changed()
self.callback(self, None, [])
self.callback = None
else:
print 'still waiting for %d resident task(s) %s to finish' % (len(self.resident_tasks), str(self.resident_tasks))
else:
self.tasks[self.current_task].run(self.taskCallback)
self.state_changed()
return
def taskCallback(self, task, res, stay_resident = False):
cb_idx = self.tasks.index(task)
if stay_resident:
if cb_idx not in self.resident_tasks:
self.resident_tasks.append(self.current_task)
print 'task going resident:', task
else:
print 'task keeps staying resident:', task
return
if len(res):
print '>>> Error:', res
self.status = self.FAILED
self.state_changed()
self.callback(self, task, res)
if cb_idx != self.current_task:
if cb_idx in self.resident_tasks:
print 'resident task finished:', task
self.resident_tasks.remove(cb_idx)
if res == []:
self.state_changed()
self.current_task += 1
self.runNext()
def retry(self):
self.restart()
def abort(self):
if self.current_task < len(self.tasks):
self.tasks[self.current_task].abort()
for i in self.resident_tasks:
self.tasks[i].abort()
def cancel(self):
self.abort()
def __str__(self):
return 'Components.Task.Job name=%s #tasks=%s' % (self.name, len(self.tasks))
class Task(object):
def __init__(self, job, name):
self.name = name
self.immediate_preconditions = []
self.global_preconditions = []
self.postconditions = []
self.returncode = None
self.initial_input = None
self.job = None
self.end = 100
self.weighting = 100
self.__progress = 0
self.cmd = None
self.cwd = '/tmp'
self.args = []
self.cmdline = None
self.task_progress_changed = None
self.output_line = ''
job.addTask(self)
self.container = None
return
def setCommandline(self, cmd, args):
self.cmd = cmd
self.args = args
def setTool(self, tool):
self.cmd = tool
self.args = [tool]
self.global_preconditions.append(ToolExistsPrecondition())
self.postconditions.append(ReturncodePostcondition())
def setCmdline(self, cmdline):
self.cmdline = cmdline
def checkPreconditions(self, immediate = False):
not_met = []
if immediate:
preconditions = self.immediate_preconditions
else:
preconditions = self.global_preconditions
for precondition in preconditions:
if not precondition.check(self):
not_met.append(precondition)
return not_met
def _run(self):
if self.cmd is None and self.cmdline is None:
self.finish()
return
else:
from enigma import eConsoleAppContainer
self.container = eConsoleAppContainer()
self.container.appClosed.append(self.processFinished)
self.container.stdoutAvail.append(self.processStdout)
self.container.stderrAvail.append(self.processStderr)
if self.cwd is not None:
self.container.setCWD(self.cwd)
if not self.cmd and self.cmdline:
print 'execute:', self.container.execute(self.cmdline), self.cmdline
else:
print 'execute:', self.container.execute(self.cmd, *self.args), ' '.join(self.args)
if self.initial_input:
self.writeInput(self.initial_input)
return
return
def run(self, callback):
failed_preconditions = self.checkPreconditions(True) + self.checkPreconditions(False)
if failed_preconditions:
print '[Task] preconditions failed'
callback(self, failed_preconditions)
return
self.callback = callback
try:
self.prepare()
self._run()
except Exception as ex:
print '[Task] exception:', ex
self.postconditions = [FailedPostcondition(ex)]
self.finish()
def prepare(self):
pass
def cleanup(self, failed):
pass
def processStdout(self, data):
self.processOutput(data)
def processStderr(self, data):
self.processOutput(data)
def processOutput(self, data):
self.output_line += data
while True:
i = self.output_line.find('\n')
if i == -1:
break
self.processOutputLine(self.output_line[:i + 1])
self.output_line = self.output_line[i + 1:]
def processOutputLine(self, line):
print '[Task %s]' % self.name, line[:-1]
def processFinished(self, returncode):
self.returncode = returncode
self.finish()
def abort(self):
if self.container:
self.container.kill()
self.finish(aborted=True)
def finish(self, aborted = False):
self.afterRun()
not_met = []
if aborted:
not_met.append(AbortedPostcondition())
else:
for postcondition in self.postconditions:
if not postcondition.check(self):
not_met.append(postcondition)
self.cleanup(not_met)
self.callback(self, not_met)
def afterRun(self):
pass
def writeInput(self, input):
self.container.write(input)
def getProgress(self):
return self.__progress
def setProgress(self, progress):
if progress > self.end:
progress = self.end
if progress < 0:
progress = 0
self.__progress = progress
if self.task_progress_changed:
self.task_progress_changed()
progress = property(getProgress, setProgress)
def __str__(self):
return 'Components.Task.Task name=%s' % self.name
class LoggingTask(Task):
def __init__(self, job, name):
Task.__init__(self, job, name)
self.log = []
def processOutput(self, data):
print '[%s]' % self.name, data,
self.log.append(data)
class PythonTask(Task):
def _run(self):
from twisted.internet import threads
from enigma import eTimer
self.aborted = False
self.pos = 0
threads.deferToThread(self.work).addBoth(self.onComplete)
self.timer = eTimer()
self.timer.callback.append(self.onTimer)
self.timer.start(5)
def work(self):
raise NotImplemented, 'work'
def abort(self):
self.aborted = True
if self.callback is None:
self.finish(aborted=True)
return
def onTimer(self):
self.setProgress(self.pos)
def onComplete(self, result):
self.postconditions.append(FailedPostcondition(result))
self.timer.stop()
del self.timer
self.finish()
class ConditionTask(Task):
def __init__(self, job, name, timeoutCount = None):
Task.__init__(self, job, name)
self.timeoutCount = timeoutCount
def _run(self):
self.triggerCount = 0
def prepare(self):
from enigma import eTimer
self.timer = eTimer()
self.timer.callback.append(self.trigger)
self.timer.start(1000)
def cleanup(self, failed):
if hasattr(self, 'timer'):
self.timer.stop()
del self.timer
def check(self):
return True
def trigger(self):
self.triggerCount += 1
try:
if self.timeoutCount is not None and self.triggerCount > self.timeoutCount:
raise Exception, 'Timeout elapsed, sorry'
res = self.check()
except Exception as e:
self.postconditions.append(FailedPostcondition(e))
res = True
if res:
self.finish()
return
class JobManager:
def __init__(self):
self.active_jobs = []
self.failed_jobs = []
self.job_classes = []
self.in_background = False
self.visible = False
self.active_job = None
return
def AddJob(self, job, onSuccess = None, onFail = None):
job.onSuccess = onSuccess
if onFail is None:
job.onFail = self.notifyFailed
else:
job.onFail = onFail
self.active_jobs.append(job)
self.kick()
return
def kick(self):
if self.active_job is None:
if self.active_jobs:
self.active_job = self.active_jobs.pop(0)
self.active_job.start(self.jobDone)
return
def notifyFailed(self, job, task, problems):
from Tools import Notifications
from Screens.MessageBox import MessageBox
if problems[0].RECOVERABLE:
Notifications.AddNotificationWithCallback(self.errorCB, MessageBox, _('Error: %s\nRetry?') % problems[0].getErrorMessage(task))
return True
else:
Notifications.AddNotification(MessageBox, job.name + '\n' + _('Error') + ': %s' % problems[0].getErrorMessage(task), type=MessageBox.TYPE_ERROR)
return False
def jobDone(self, job, task, problems):
print 'job', job, 'completed with', problems, 'in', task
if problems:
if not job.onFail(job, task, problems):
self.errorCB(False)
else:
self.active_job = None
if job.onSuccess:
job.onSuccess(job)
self.kick()
return
def popupTaskView(self, job):
if not self.visible:
from Tools import Notifications
from Screens.TaskView import JobView
self.visible = True
Notifications.AddNotification(JobView, job)
def errorCB(self, answer):
if answer:
print 'retrying job'
self.active_job.retry()
else:
print 'not retrying job.'
self.failed_jobs.append(self.active_job)
self.active_job = None
self.kick()
return
def getPendingJobs(self):
list = []
if self.active_job:
list.append(self.active_job)
list += self.active_jobs
return list
class Condition:
RECOVERABLE = False
def getErrorMessage(self, task):
return _('An unknown error occurred!') + ' (%s @ task %s)' % (self.__class__.__name__, task.__class__.__name__)
class WorkspaceExistsPrecondition(Condition):
def check(self, task):
return os.access(task.job.workspace, os.W_OK)
class DiskspacePrecondition(Condition):
def __init__(self, diskspace_required):
self.diskspace_required = diskspace_required
self.diskspace_available = 0
def check(self, task):
import os
try:
s = os.statvfs(task.job.workspace)
self.diskspace_available = s.f_bsize * s.f_bavail
return self.diskspace_available >= self.diskspace_required
except OSError:
return False
def getErrorMessage(self, task):
return _('Not enough disk space. Please free up some disk space and try again. (%d MB required, %d MB available)') % (self.diskspace_required / 1024 / 1024, self.diskspace_available / 1024 / 1024)
class ToolExistsPrecondition(Condition):
def check(self, task):
import os
if task.cmd[0] == '/':
self.realpath = task.cmd
print '[Task.py][ToolExistsPrecondition] WARNING: usage of absolute paths for tasks should be avoided!'
return os.access(self.realpath, os.X_OK)
self.realpath = task.cmd
path = os.environ.get('PATH', '').split(os.pathsep)
path.append(task.cwd + '/')
absolutes = filter(lambda file: os.access(file, os.X_OK), map(lambda directory, file = task.cmd: os.path.join(directory, file), path))
if absolutes:
self.realpath = absolutes[0]
return True
return False
def getErrorMessage(self, task):
return _('A required tool (%s) was not found.') % self.realpath
class AbortedPostcondition(Condition):
def getErrorMessage(self, task):
return 'Cancelled upon user request'
class ReturncodePostcondition(Condition):
def check(self, task):
return task.returncode == 0
def getErrorMessage(self, task):
if hasattr(task, 'log') and task.log:
log = ''.join(task.log).strip()
log = log.split('\n')[-3:]
log = '\n'.join(log)
return log
else:
return _('Error code') + ': %s' % task.returncode
class FailedPostcondition(Condition):
def __init__(self, exception):
self.exception = exception
def getErrorMessage(self, task):
if isinstance(self.exception, int):
if hasattr(task, 'log'):
log = ''.join(task.log).strip()
log = log.split('\n')[-4:]
log = '\n'.join(log)
return log
else:
return _('Error code') + ' %s' % self.exception
return str(self.exception)
def check(self, task):
return self.exception is None or self.exception == 0
job_manager = JobManager()

23
NeoBoot/files/__init__.py Normal file
View File

@@ -0,0 +1,23 @@
# -*- coding: utf-8 -*-
from Components.Language import language
from Tools.Directories import resolveFilename, SCOPE_PLUGINS, SCOPE_LANGUAGE
import os, gettext
PluginLanguageDomain = 'NeoBoot'
PluginLanguagePath = 'Extensions/NeoBoot/locale'
def localeInit():
lang = language.getLanguage()[:2]
os.environ['LANGUAGE'] = lang
print '[NeoBoot] set language to ', lang
gettext.bindtextdomain(PluginLanguageDomain, resolveFilename(SCOPE_PLUGINS, PluginLanguagePath))
def _(txt):
t = gettext.dgettext(PluginLanguageDomain, txt)
if t == txt:
print '[NeoBoot] fallback to default translation for', txt
t = gettext.dgettext('enigma2', txt)
return t
localeInit()
language.addCallback(localeInit)

BIN
NeoBoot/files/__init__.pyo Normal file

Binary file not shown.

479
NeoBoot/files/devices.py Normal file
View File

@@ -0,0 +1,479 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __init__ import _
from enigma import getDesktop
from Plugins.Plugin import PluginDescriptor
from Screens.ChoiceBox import ChoiceBox
from Screens.InputBox import InputBox
from Screens.Screen import Screen
from enigma import eTimer
from Screens.MessageBox import MessageBox
from Screens.Standby import TryQuitMainloop
from Components.ActionMap import ActionMap
from Components.Label import Label
from Components.Pixmap import Pixmap
from Components.ConfigList import ConfigListScreen
from Components.config import getConfigListEntry, config, ConfigSelection, NoSave, configfile
from Components.Console import Console
from Components.Sources.List import List
from Components.Sources.StaticText import StaticText
from Plugins.Extensions.NeoBoot.files.Harddisk import Harddisk
from Tools.LoadPixmap import LoadPixmap
from Tools.Directories import fileExists, resolveFilename, SCOPE_CURRENT_SKIN
from os import system, rename, path, mkdir, remove, listdir
from time import sleep
import fileinput
import re
import os
class ManagerDevice(Screen):
screenwidth = getDesktop(0).size().width()
if screenwidth and screenwidth == 1920:
skin = '<screen name="ManagerDevice" position="center,center" size="1235,748">\n\t\t<ePixmap pixmap="skin_default/buttons/red.png" position="35,16" size="253,52" alphatest="on" />\n\t\t<ePixmap pixmap="skin_default/buttons/green.png" position="315,15" size="279,50" alphatest="on" />\n\t\t<ePixmap pixmap="skin_default/buttons/yellow.png" position="647,18" size="263,48" alphatest="on" />\n\t\t<ePixmap pixmap="skin_default/buttons/blue.png" position="965,19" size="269,51" alphatest="on" />\n\t\t<widget name="key_red" position="14,17" zPosition="1" size="258,48" font="Regular;30" halign="center" valign="center" backgroundColor="un9f1313" transparent="1" />\n\t\t<widget name="key_green" position="297,17" zPosition="1" size="298,48" font="Regular;30" halign="center" valign="center" backgroundColor="un1f771f" transparent="1" />\n\t\t<widget name="key_yellow" position="631,18" zPosition="1" size="268,48" font="Regular;30" halign="center" valign="center" backgroundColor="una08500" transparent="1" />\n\t\t<widget name="key_blue" position="940,21" zPosition="1" size="266,45" font="Regular;30" halign="center" valign="center" backgroundColor="un18188b" transparent="1" />\n\t\t<widget source="list" render="Listbox" position="12,76" size="1212,651" scrollbarMode="showOnDemand">\n\t\t\t<convert type="TemplatedMultiContent">\n\t\t\t\t{"template": [\n\t\t\t\t MultiContentEntryText(pos = (90, 5), size = (600, 30), font=0, text = 0),\n\t\t\t\t MultiContentEntryText(pos = (110, 60), size = (900, 100), font=1, flags = RT_VALIGN_TOP, text = 1),\n\t\t\t\t MultiContentEntryPixmapAlphaBlend(pos = (0, 0), size = (160, 160,), png = 2),\n\t\t\t\t],\n\t\t\t\t"fonts": [gFont("Regular", 33),gFont("Regular", 33)],\n\t\t\t\t"itemHeight": 140\n\t\t\t\t}\n\t\t\t</convert>\n\t\t</widget>\n\t\t<widget name="lab1" zPosition="2" position="32,92" size="1182,69" font="Regular;30" halign="center" transparent="1" />\n\t</screen>'
else:
skin = '<screen position="center,center" size="640,460">\n\t\t<ePixmap pixmap="skin_default/buttons/red.png" position="25,0" size="140,40" alphatest="on" />\n\t\t<ePixmap pixmap="skin_default/buttons/green.png" position="175,0" size="140,40" alphatest="on" />\n\t\t<ePixmap pixmap="skin_default/buttons/yellow.png" position="325,0" size="140,40" alphatest="on" />\n\t\t<ePixmap pixmap="skin_default/buttons/blue.png" position="475,0" size="140,40" alphatest="on" />\n\t\t<widget name="key_red" position="25,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />\n\t\t<widget name="key_green" position="175,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />\n\t\t<widget name="key_yellow" position="325,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" />\n\t\t <widget name="key_blue" position="475,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" />\n\t\t<widget source="list" render="Listbox" position="10,50" size="620,450" scrollbarMode="showOnDemand" >\n\t\t\t<convert type="TemplatedMultiContent">\n\t\t\t\t{"template": [\n\t\t\t\t MultiContentEntryText(pos = (90, 0), size = (600, 30), font=0, text = 0),\n\t\t\t\t MultiContentEntryText(pos = (110, 30), size = (600, 50), font=1, flags = RT_VALIGN_TOP, text = 1),\n\t\t\t\t MultiContentEntryPixmapAlphaBlend(pos = (0, 0), size = (80, 80), png = 2),\n\t\t\t\t],\n\t\t\t\t"fonts": [gFont("Regular", 24),gFont("Regular", 20)],\n\t\t\t\t"itemHeight": 85\n\t\t\t\t}\n\t\t\t</convert>\n\t\t</widget>\n\t\t<widget name="lab1" zPosition="2" position="50,90" size="600,40" font="Regular;22" halign="center" transparent="1"/>\n\t</screen>'
def __init__(self, session):
Screen.__init__(self, session)
Screen.setTitle(self, _('Mount Manager'))
self['key_red'] = Label(_('Initialize'))
self['key_green'] = Label(_('SetupMounts'))
self['key_yellow'] = Label(_('Unmount'))
self['key_blue'] = Label(_('Exit'))
self['lab1'] = Label()
self.onChangedEntry = []
self.list = []
self['list'] = List(self.list)
self['list'].onSelectionChanged.append(self.selectionChanged)
self['actions'] = ActionMap(['WizardActions', 'ColorActions', 'MenuActions'], {'back': self.close,
'red': self.Format,
'green': self.SetupMounts,
'yellow': self.Unmount,
'blue': self.Mount})
self.activityTimer = eTimer()
self.activityTimer.timeout.get().append(self.updateList2)
self.updateList()
self.onShown.append(self.setWindowTitle)
def setWindowTitle(self):
self.setTitle(_('Mount Manager'))
def createSummary(self):
return DeviceManagerSummary
def selectionChanged(self):
if len(self.list) == 0:
return
self.sel = self['list'].getCurrent()
seldev = self.sel
if self.sel:
try:
name = str(self.sel[0])
desc = str(self.sel[1].replace('\t', ' '))
except:
name = ''
desc = ''
else:
name = ''
desc = ''
for cb in self.onChangedEntry:
cb(name, desc)
def updateList(self, result = None, retval = None, extra_args = None):
scanning = _('Wait please while scanning for devices...')
self['lab1'].setText(scanning)
self.activityTimer.start(10)
def updateList2(self):
self.activityTimer.stop()
self.list = []
list2 = []
f = open('/proc/partitions', 'r')
for line in f.readlines():
parts = line.strip().split()
if not parts:
continue
device = parts[3]
if not re.search('sd[a-z][1-9]', device):
continue
if device in list2:
continue
self.buildMy_rec(device)
list2.append(device)
f.close()
self['list'].list = self.list
self['lab1'].hide()
def buildMy_rec(self, device):
mypath = SkinPath()
device2 = re.sub('[0-9]', '', device)
devicetype = path.realpath('/sys/block/' + device2 + '/device')
d2 = device
name = _('HARD DISK: ')
mypixmap = '/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/dev_hdd.png'
model = file('/sys/block/' + device2 + '/device/model').read()
model = str(model).replace('\n', '')
des = ''
if devicetype.find('usb') != -1:
name = _('USB: ')
mypixmap = '/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/dev_usb.png'
if devicetype.find('usb1') != -1:
name = _('USB1: ')
mypixmap = '/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/dev_usb.png'
if devicetype.find('usb2') != -1:
name = _('USB2: ')
mypixmap = '/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/dev_usb.png'
name = name + model
self.Console = Console()
self.Console.ePopen("sfdisk -l /dev/sd? | grep swap | awk '{print $(NF-9)}' >/tmp/devices.tmp")
sleep(0.5)
f = open('/tmp/devices.tmp', 'r')
swapdevices = f.read()
f.close()
if path.exists('/tmp/devices.tmp'):
remove('/tmp/devices.tmp')
swapdevices = swapdevices.replace('\n', '')
swapdevices = swapdevices.split('/')
f = open('/proc/mounts', 'r')
for line in f.readlines():
if line.find(device) != -1:
parts = line.strip().split()
d1 = parts[1]
dtype = parts[2]
rw = parts[3]
break
continue
elif device in swapdevices:
parts = line.strip().split()
d1 = _('None')
dtype = 'swap'
rw = _('None')
break
continue
else:
d1 = _('None')
dtype = _('unavailable')
rw = _('None')
f.close()
size = Harddisk(device).diskSize()
if float(size) / 1024 / 1024 >= 1:
des = _('Size: ') + str(round(float(size) / 1024 / 1024, 2)) + _('TB')
elif size / 1024 >= 1:
des = _('Size: ') + str(round(float(size) / 1024, 2)) + _('GB')
elif size >= 1:
des = _('Size: ') + str(size) + _('MB')
else:
des = _('Size: ') + _('unavailable')
if des != '':
if rw.startswith('rw'):
rw = ' R/W'
elif rw.startswith('ro'):
rw = ' R/O'
else:
rw = ''
des += '\t' + _('Mount: ') + d1 + '\n' + _('Device: ') + '/dev/' + device + '\t' + _('Type: ') + dtype + rw
png = LoadPixmap(mypixmap)
res = (name, des, png)
self.list.append(res)
def SetupMounts(self):
self.session.openWithCallback(self.updateList, DevicesConf)
def Format(self):
from Screens.HarddiskSetup import HarddiskSelection
self.session.openWithCallback(self.updateList, HarddiskSelection)
def Mount(self):
self.close()
def Unmount(self):
sel = self['list'].getCurrent()
if sel:
des = sel[1]
des = des.replace('\n', '\t')
parts = des.strip().split('\t')
mountp = parts[1].replace(_('Mount: '), '')
device = parts[2].replace(_('Device: '), '')
system('umount ' + mountp)
try:
mounts = open('/proc/mounts')
mountcheck = mounts.readlines()
mounts.close()
for line in mountcheck:
parts = line.strip().split(' ')
if path.realpath(parts[0]).startswith(device):
self.session.open(MessageBox, _("Can't unmount partition, make sure it is not being used for swap or record/timeshift paths"), MessageBox.TYPE_INFO, timeout=10)
except IOError:
return -1
self.updateList()
def saveMypoints(self):
sel = self['list'].getCurrent()
if sel:
parts = sel[1].split()
self.device = parts[5]
self.mountp = parts[3]
self.Console.ePopen('umount ' + self.device)
if self.mountp.find('/media/hdd') < 0:
self.Console.ePopen('umount /media/hdd')
self.Console.ePopen('/sbin/blkid | grep ' + self.device, self.add_fstab, [self.device, self.mountp])
else:
self.session.open(MessageBox, _('This Device is already mounted as HDD.'), MessageBox.TYPE_INFO, timeout=10, close_on_any_key=True)
def add_fstab(self, result = None, retval = None, extra_args = None):
self.device = extra_args[0]
self.mountp = extra_args[1]
self.device_uuid = 'UUID=' + result.split('UUID=')[1].split(' ')[0].replace('"', '')
if not path.exists(self.mountp):
mkdir(self.mountp, 493)
file('/etc/fstab.tmp', 'w').writelines([ l for l in file('/etc/fstab').readlines() if '/media/hdd' not in l ])
rename('/etc/fstab.tmp', '/etc/fstab')
file('/etc/fstab.tmp', 'w').writelines([ l for l in file('/etc/fstab').readlines() if self.device not in l ])
rename('/etc/fstab.tmp', '/etc/fstab')
file('/etc/fstab.tmp', 'w').writelines([ l for l in file('/etc/fstab').readlines() if self.device_uuid not in l ])
rename('/etc/fstab.tmp', '/etc/fstab')
out = open('/etc/fstab', 'a')
line = self.device_uuid + '\t/media/hdd\tauto\tdefaults\t0 0\n'
out.write(line)
out.close()
self.Console.ePopen('mount -a', self.updateList)
def restBo(self, answer):
if answer is True:
self.session.open(TryQuitMainloop, 2)
else:
self.updateList()
self.selectionChanged()
class DevicesConf(Screen, ConfigListScreen):
screenwidth = getDesktop(0).size().width()
if screenwidth and screenwidth == 1920:
skin = '<screen name="DevicesConf" position="center,center" size="976,728" title="Choose where to mount your devices to:">\n\t\t<ePixmap pixmap="skin_default/buttons/red.png" position="109,16" size="251,63" alphatest="on" />\n\t\t<ePixmap pixmap="skin_default/buttons/green.png" position="551,15" size="257,63" alphatest="on" />\n\t\t<widget name="key_red" position="110,13" zPosition="1" size="252,67" font="Regular;35" halign="center" valign="center" backgroundColor="#FF0000" transparent="1" />\n\t\t<widget name="key_green" position="549,15" zPosition="1" size="262,65" font="Regular;35" halign="center" valign="center" backgroundColor="#008000" transparent="1" />\n\t\t<widget name="config" position="31,113" size="898,489" font="Regular;25" scrollbarMode="showOnDemand" />\n\t\t<widget name="Linconn" position="34,621" size="904,32" font="Regular;33" halign="center" valign="center" backgroundColor="#FF0000" />\n\t</screen>'
else:
skin = '<screen position="center,center" size="640,460" title="Choose where to mount your devices to:">\n\t\t<ePixmap pixmap="skin_default/buttons/red.png" position="25,0" size="140,40" alphatest="on" />\n\t\t<ePixmap pixmap="skin_default/buttons/green.png" position="175,0" size="140,40" alphatest="on" />\n\t\t<widget name="key_red" position="25,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />\n\t\t<widget name="key_green" position="175,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />\n\t\t<widget name="config" position="30,60" size="580,275" scrollbarMode="showOnDemand"/>\n\t\t<widget name="Linconn" position="30,375" size="580,20" font="Regular;18" halign="center" valign="center" backgroundColor="#9f1313"/>\n\t</screen>'
def __init__(self, session):
Screen.__init__(self, session)
self.list = []
ConfigListScreen.__init__(self, self.list)
Screen.setTitle(self, _('Choose where to mount your devices to:'))
self['key_green'] = Label(_('Save'))
self['key_red'] = Label(_('Cancel'))
self['Linconn'] = Label(_('Wait please while scanning your %s %s devices...n\\ Szukam dysku...'))
self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'green': self.saveMypoints,
'red': self.close,
'back': self.close})
self.updateList()
def updateList(self):
self.list = []
list2 = []
self.Console = Console()
self.Console.ePopen("sfdisk -l /dev/sd? | grep swap | awk '{print $(NF-9)}' >/tmp/devices.tmp")
sleep(0.5)
f = open('/tmp/devices.tmp', 'r')
swapdevices = f.read()
f.close()
if path.exists('/tmp/devices.tmp'):
remove('/tmp/devices.tmp')
swapdevices = swapdevices.replace('\n', '')
swapdevices = swapdevices.split('/')
f = open('/proc/partitions', 'r')
for line in f.readlines():
parts = line.strip().split()
if not parts:
continue
device = parts[3]
if not re.search('sd[a-z][1-9]', device):
continue
if device in list2:
continue
if device in swapdevices:
continue
self.buildMy_rec(device)
list2.append(device)
f.close()
self['config'].list = self.list
self['config'].l.setList(self.list)
self['Linconn'].hide()
def buildMy_rec(self, device):
mypath = SkinPath()
device2 = re.sub('[0-9]', '', device)
devicetype = path.realpath('/sys/block/' + device2 + '/device')
d2 = device
name = _('HARD DISK: ')
mypixmap = '/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/dev_hdd.png'
model = file('/sys/block/' + device2 + '/device/model').read()
model = str(model).replace('\n', '')
des = ''
if devicetype.find('usb') != -1:
name = _('USB: ')
mypixmap = '/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/dev_usb.png'
if devicetype.find('usb1') != -1:
name = _('USB1: ')
mypixmap = '/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/dev_usb.png'
if devicetype.find('usb2') != -1:
name = _('USB2: ')
mypixmap = '/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/dev_usb.png'
name = name + model
f = open('/proc/mounts', 'r')
for line in f.readlines():
if line.find(device) != -1:
parts = line.strip().split()
d1 = parts[1]
dtype = parts[2]
break
continue
else:
d1 = _('None')
dtype = _('unavailable')
f.close()
size = Harddisk(device).diskSize()
if float(size) / 1024 / 1024 >= 1:
des = _('Size: ') + str(round(float(size) / 1024 / 1024, 2)) + _('TB')
elif size / 1024 >= 1:
des = _('Size: ') + str(round(float(size) / 1024, 2)) + _('GB')
elif size >= 1:
des = _('Size: ') + str(size) + _('MB')
else:
des = _('Size: ') + _('unavailable')
item = NoSave(ConfigSelection(default='/media/' + device, choices=[('/media/' + device, '/media/' + device),
('/media/hdd', '/media/hdd'),
('/media/hdd2', '/media/hdd2'),
('/media/hdd3', '/media/hdd3'),
('/media/usb', '/media/usb'),
('/media/usb1', '/media/usb1'),
('/media/usb2', '/media/usb2'),
('/media/usb3', '/media/usb3')]))
if dtype == 'Linux':
dtype = 'ext2', 'ext3', 'ext4'
else:
dtype = 'auto'
item.value = d1.strip()
text = name + ' ' + des + ' /dev/' + device
res = getConfigListEntry(text, item, device, dtype)
if des != '' and self.list.append(res):
pass
def saveMypoints(self):
system('mount media -a')
system('cp -r -f /etc/fstab /etc/fstab.org')
self.Console = Console()
mycheck = False
for x in self['config'].list:
self.device = x[2]
self.mountp = x[1].value
self.type = x[3]
self.Console.ePopen('umount ' + self.device)
self.Console.ePopen('/sbin/blkid | grep ' + self.device + ' && opkg list-installed ntfs-3g', self.add_fstab, [self.device, self.mountp])
message = _('Continues mounting equipment...')
ybox = self.session.openWithCallback(self.delay, MessageBox, message, type=MessageBox.TYPE_INFO, timeout=5, enable_input=False)
ybox.setTitle(_('Please, wait....'))
def delay(self, val):
#if fileExists('/etc/init.d/volatile-media.sh'):
#system('mv /etc/init.d/volatile-media.sh /etc/init.d/volatile-media.sh.org')
message = _('Completed assembly of disks.\nReturn to installation ?')
ybox = self.session.openWithCallback(self.myclose, MessageBox, message, MessageBox.TYPE_YESNO)
ybox.setTitle(_('MOUNTING....'))
def myclose(self, answer):
if answer is True:
self.messagebox = self.session.open(MessageBox, _('Return to installation...'), MessageBox.TYPE_INFO)
self.close()
else:
self.messagebox = self.session.open(MessageBox, _('Return to installation...'), MessageBox.TYPE_INFO)
self.close()
def add_fstab(self, result = None, retval = None, extra_args = None):
print '[MountManager] RESULT:', result
if result:
self.device = extra_args[0]
self.mountp = extra_args[1]
self.device_uuid = 'UUID=' + result.split('UUID=')[1].split(' ')[0].replace('"', '')
self.device_type = result.split('TYPE=')[1].split(' ')[0].replace('"', '')
if self.device_type.startswith('ext'):
self.device_type = 'auto'
elif self.device_type.startswith('ntfs') and result.find('ntfs-3g') != -1:
self.device_type = 'ntfs-3g'
elif self.device_type.startswith('ntfs') and result.find('ntfs-3g') == -1:
self.device_type = 'ntfs'
if not path.exists(self.mountp):
mkdir(self.mountp, 493)
file('/etc/fstab.tmp', 'w').writelines([ l for l in file('/etc/fstab').readlines() if self.device not in l ])
rename('/etc/fstab.tmp', '/etc/fstab')
file('/etc/fstab.tmp', 'w').writelines([ l for l in file('/etc/fstab').readlines() if self.device_uuid not in l ])
rename('/etc/fstab.tmp', '/etc/fstab')
out = open('/etc/fstab', 'a')
line = self.device_uuid + '\t' + self.mountp + '\t' + self.device_type + '\tdefaults\t0 0\n'
out.write(line)
out.close()
#system('cp -r -f /etc/fstab /usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/files')
self.device_uuid2 = result.split('UUID=')[1].split(' ')[0].replace('"', '')
if fileExists('/usr/lib/enigma2/python/Plugins/SystemPlugins/DeviceManager2'):
out1 = open('/etc/devicemanager.cfg', 'a')
line1 = '"' + self.device_uuid2 + '"' + ':' + self.mountp + '\n'
out1.write(line1)
out1.close()
elif fileExists('/usr/lib/enigma2/python/Plugins/SystemPlugins/DeviceManager'):
out2 = open('/usr/lib/enigma2/python/Plugins/SystemPlugins/DeviceManager/devicemanager.cfg', 'a')
line2 = '"' + self.device_uuid2 + '"' + ':' + self.mountp + '\n'
out2.write(line2)
out2.close()
if fileExists('/etc/init.d/udev'):
filename = '/etc/init.d/udev'
if os.path.exists(filename):
filename2 = filename + '.tmp'
out = open(filename2, 'w')
f = open(filename, 'r')
for line in f.readlines():
if line.find('exit 0') != -1:
line = '\n'
out.write(line)
f.close()
out.close()
os.rename(filename2, filename)
os.system('mount -a; echo "mount -a" >> /etc/init.d/udev; echo "/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/files/mountpoint.sh" >> /etc/init.d/udev; echo "exit 0" >> /etc/init.d/udev')
if fileExists('/etc/init.d/mdev'):
system('mount -a; echo "" >> /etc/init.d/mdev; echo "mount -a" >> /etc/init.d/mdev; echo "/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/files/mountpoint.sh" >> /etc/init.d/mdev')
class DeviceManagerSummary(Screen):
def __init__(self, session, parent):
Screen.__init__(self, session, parent=parent)
self['entry'] = StaticText('')
self['desc'] = StaticText('')
self.onShow.append(self.addWatcher)
self.onHide.append(self.removeWatcher)
def addWatcher(self):
self.parent.onChangedEntry.append(self.selectionChanged)
self.parent.selectionChanged()
def removeWatcher(self):
self.parent.onChangedEntry.remove(self.selectionChanged)
def selectionChanged(self, name, desc):
self['entry'].text = name
self['desc'].text = desc
def SkinPath():
myskinpath = resolveFilename(SCOPE_CURRENT_SKIN, '')
if myskinpath == '/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/':
myskinpath = '/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/'
return myskinpath

View File

@@ -0,0 +1,16 @@
#!/bin/sh
#DESCRIPTION=This script by gutosie
opkg update
opkg install --force-reinstall mtd-utils
opkg install --force-reinstall mtd-utils-ubifs
opkg install --force-reinstall mtd-utils-jffs2
opkg install --force-reinstall kernel-module-nandsim
opkg install --force-reinstall python-subprocess
opkg install --force-reinstall python-argparse
opkg install --force-reinstall curl
opkg install --force-reinstall liblzo2-2
opkg install --force-reinstall python-imaging
opkg install --force-maintainer --force-reinstall --force-overwrite kernel-image
opkg configure update-modules
cd

View File

@@ -0,0 +1,22 @@
#!/bin/sh
IMAGE=ImageBoot
NEOBOOTMOUNT=$( cat /usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/.location)
rm -f /usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/files/neom
orgimag=`mount | sed '/sd/!d' | cut -d" " -f1`
for item in $orgimag; do
ohdd=`echo $item | cut -d"/" -f3`
nhdd=`mount | sed "/\$ohdd/!d" | sed q | cut -d" " -f3`
if [ $nhdd == '$NEOBOOTMOUNT' ]; then
echo $nhdd
echo "mkdir "$nhdd >> /usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/files/neom
echo "mount "$item $nhdd >> /usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/files/neom
else
echo "umount "$nhdd >> /usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/files/neom
echo "mkdir "$nhdd >> /usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/files/neom
echo "mount "$item $nhdd >> /usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/files/neom
echo ok
fi
done
chmod 0755 /usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/files/neom

View File

@@ -0,0 +1,542 @@
# -*- coding: utf-8 -*-
#from __future__ import print_function
#from Plugins.Extensions.NeoBoot.__init__ import _ , Log, PluginPath
import sys
import os
import time
from Tools.Directories import fileExists, SCOPE_PLUGINS
def fileCheck(f, mode = 'r'):
return fileExists(f, mode) and f
#check install
def getNeoLocation():
locatino='UNKNOWN'
if os.path.exists('/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/.location'):
with open('/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/.location', 'r') as f:
locatino = f.readline().strip()
f.close()
return locatino
def Log(param = ''):
global LogFileObj
#first close object if exists
if param.lower() in ['open','write','append','close']:
if LogFileObj is not None:
LogFileObj.close()
if LogFileObj.closed:
LogFileObj = None
try:
with open('/tmp/NeoBoot.log','a') as f:
f.write('LogFile closed properly\n')
f.close()
except Exception:
print("ERROR closing LogFile!!!")
else:
print("ERROR closing LogFile!!!")
#second create object if does not exist
if LogFileObj is None:
if param.lower() in ['open','write']:
LogFileObj = open(LogFile, "w")
elif param.lower() in ['append']:
LogFileObj = open(LogFile, "a")
elif param.lower() in ['close']:
pass
elif param.lower() in ['flush']:
LogFileObj.flush()
return LogFileObj
def clearMemory():
with open("/proc/sys/vm/drop_caches", "w") as f:
f.write("1\n")
f.close()
###############################################
#typ procesora arm lub mips
def getCPUtype():
cpu='UNKNOWN'
if os.path.exists('/proc/cpuinfo'):
with open('/proc/cpuinfo', 'r') as f:
lines = f.read()
f.close()
if lines.find('ARMv7') != -1:
cpu='ARMv7'
elif lines.find('mips') != -1:
cpu='MIPS'
return cpu
#check install
def getFSTAB():
install='UNKNOWN'
if os.path.exists('/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/bin/install'):
with open('/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/bin/install', 'r') as f:
lines = f.read()
f.close()
if lines.find('UUID') != -1:
install='OKinstall'
elif not lines.find('UUID') != -1:
install='NOinstall'
return install
def getFSTAB2():
install='UNKNOWN'
if os.path.exists('/etc/fstab'):
with open('/etc/fstab', 'r') as f:
lines = f.read()
f.close()
if lines.find('UUID') != -1:
install='OKinstall'
elif not lines.find('UUID') != -1:
install='NOinstall'
return install
def getINSTALLNeo():
neoinstall='UNKNOWN'
if os.path.exists('/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/bin/install'):
with open('/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/bin/install', 'r') as f:
lines = f.read()
f.close()
if lines.find('/dev/sda1') != -1:
neoinstall='/dev/sda1'
elif lines.find('/dev/sda2') != -1:
neoinstall='/dev/sda2'
elif lines.find('/dev/sdb1') != -1:
neoinstall='/dev/sdb1'
elif lines.find('/dev/sdb2') != -1:
neoinstall='/dev/sdb2'
elif lines.find('/dev/sdc1') != -1:
neoinstall='/dev/sdc1'
elif lines.find('/dev/sdd1') != -1:
neoinstall='/dev/sdd1'
elif lines.find('/dev/sde1') != -1:
neoinstall='/dev/sde1'
elif lines.find('/dev/sdf1') != -1:
neoinstall='/dev/sdf1'
return neoinstall
def getLabelDisck():
label='UNKNOWN'
if os.path.exists('/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/bin/installblkid'):
with open('/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/bin/installblkid', 'r') as f:
lines = f.read()
f.close()
if lines.find('LABEL=') != -1:
label='LABEL='
return label
#checking device neo
def getNeoMount():
neo='UNKNOWN'
if os.path.exists('/proc/mounts'):
with open('/proc/mounts', 'r') as f:
lines = f.read()
f.close()
if lines.find('/dev/sda1 /media/hdd') != -1:
neo='hdd_install_/dev/sda1'
elif lines.find('/dev/sdb1 /media/hdd') != -1:
neo='hdd_install_/dev/sdb1'
elif lines.find('/dev/sda2 /media/hdd') != -1:
neo='hdd_install_/dev/sda2'
elif lines.find('/dev/sdb2 /media/hdd') != -1:
neo='hdd_install_/dev/sdb2'
return neo
def getNeoMount2():
neo='UNKNOWN'
if os.path.exists('/proc/mounts'):
with open('/proc/mounts', 'r') as f:
lines = f.read()
f.close()
if lines.find('/dev/sda1 /media/usb') != -1:
neo='usb_install_/dev/sda1'
elif lines.find('/dev/sdb1 /media/usb') != -1:
neo='usb_install_/dev/sdb1'
elif lines.find('/dev/sdb2 /media/usb') != -1:
neo='usb_install_/dev/sdb2'
elif lines.find('/dev/sdc1 /media/usb') != -1:
neo='usb_install_/dev/sdc1'
elif lines.find('/dev/sdd1 /media/usb') != -1:
neo='usb_install_/dev/sdd1'
elif lines.find('/dev/sde1 /media/usb') != -1:
neo='usb_install_/dev/sde1'
elif lines.find('/dev/sdf1 /media/usb') != -1:
neo='usb_install_/dev/sdf1'
return neo
#zwraca typ chipa prcesora
def getCPUSoC():
chipset='UNKNOWN'
if os.path.exists('/proc/stb/info/chipset'):
with open('/proc/stb/info/chipset', 'r') as f:
chipset = f.readline().strip()
f.close()
if chipset == '7405(with 3D)':
chipset = '7405'
return chipset
def getCPUSoCModel():
devicetree='UNKNOWN'
if os.path.exists('/proc/device-tree/model'):
with open('/proc/device-tree/model', 'r') as f:
devicetree = f.readline().strip()
f.close()
return devicetree
#zwraca wybrane image w neoboot do uruchomienia
def getImageNeoBoot():
imagefile='UNKNOWN'
if os.path.exists('%sImageBoot/.neonextboot' % getNeoLocation() ):
with open('%sImageBoot/.neonextboot' % getNeoLocation() , 'r') as f:
imagefile = f.readline().strip()
f.close()
return imagefile
#zwraca model vuplus
def getBoxVuModel():
vumodel='UNKNOWN'
if fileExists("/proc/stb/info/vumodel") and not fileExists("/proc/stb/info/boxtype"):
with open('/proc/stb/info/vumodel', 'r') as f:
vumodel = f.readline().strip()
f.close()
elif fileExists("/proc/stb/info/boxtype") and not fileExists("/proc/stb/info/vumodel"):
with open('/proc/stb/info/boxtype', 'r') as f:
vumodel = f.readline().strip()
f.close()
return vumodel
def getVuModel():
if fileExists("/proc/stb/info/vumodel") and not fileExists("/proc/stb/info/boxtype"):
brand = "Vu+"
f = open("/proc/stb/info/vumodel",'r')
procmodel = f.readline().strip()
f.close()
model = procmodel.title().replace("olose", "olo SE").replace("olo2se", "olo2 SE").replace("2", "²")
return model
#zwraca nazwe stb z pliku hostname
def getBoxHostName():
if os.path.exists('/etc/hostname'):
with open('/etc/hostname', 'r') as f:
myboxname = f.readline().strip()
f.close()
return myboxname
#zwraca vuplus/vumodel
def getTunerModel(): #< neoboot.py
BOX_NAME = ''
if os.path.isfile('/proc/stb/info/vumodel') and not os.path.isfile("/proc/stb/info/boxtype"):
BOX_NAME = open('/proc/stb/info/vumodel').read().strip()
ImageFolder = 'vuplus/%s' % BOX_NAME
elif os.path.isfile('proc/stb/info/boxtype'):
BOX_NAME = open('/proc/stb/info/boxtype').read().strip()
elif os.path.isfile('proc/stb/info/model') and not os.path.isfile("/proc/stb/info/mid"):
BOX_NAME = open('/proc/stb/info/model').read().strip()
return BOX_NAME
def getBoxModelVU():
try:
if os.path.isfile('/proc/stb/info/vumodel'):
return open('/proc/stb/info/vumodel').read().strip().upper()
except:
pass
return _('unavailable')
#zwraca strukture folderu zip - vuplus/vumodel
def getImageFolder():
if os.path.isfile('/proc/stb/info/vumodel'):
BOX_NAME = getBoxModelVU()
ImageFolder = 'vuplus/' + BOX_NAME
return ImageFolder
#zwraca nazwe kernela z /lib/modules
def getKernelVersion():
try:
return open('/proc/version', 'r').read().split(' ', 4)[2].split('-', 2)[0]
except:
return _('unknown')
# czysci pamiec
def runCMDS(cmdsList):
clearMemory()
if isinstance(cmdsList, (list, tuple)):
myCMD = '\n'.join(cmdsList)# + '\n'
ret = os.system(myCMD)
return rett
#####################################
def getImageDistro():
if fileExists('/etc/issue.net'):
try:
obraz = open('/etc/issue.net', 'r').readlines()
imagetype = obraz[0][:-1]
image = imagetype[0:-2]
return image
except:
False
elif fileExists('/etc/vtiversion.info'):
image = 'VTI'
return image
def getKernelVersionString():
try:
result = popen('uname -r', 'r').read().strip('\n').split('-')
kernel_version = result[0]
return kernel_version
except:
pass
return 'unknown'
def getKernelImageVersion():
try:
from glob import glob
lines = open(glob('/var/lib/opkg/info/kernel-*.control')[0], 'r').readlines()
kernelimage = lines[1][:-1]
except:
kernelimage = getKernelVersionString
return kernelimage
def getTypBoxa():
if not fileExists('/etc/typboxa'):
os.system('touch /etc/typboxa')
f2 = open('/etc/hostname', 'r')
mypath2 = f2.readline().strip()
f2.close()
if mypath2 == 'vuuno':
out = open('/etc/typboxa ', 'w')
out.write('Vu+Uno ')
out.close()
elif mypath2 == 'vuultimo':
out = open('/etc/typboxa', 'w')
out.write('Vu+Ultimo ')
out.close()
elif mypath2 == 'vuduo':
out = open('/etc/typboxa ', 'w')
out.write('Vu+Duo ')
out.close()
elif mypath2 == 'vuduo2':
out = open('/etc/typboxa ', 'w')
out.write('Vu+Duo2 ')
out.close()
elif mypath2 == 'vusolo':
out = open('/etc/typboxa ', 'w')
out.write('Vu+Solo ')
out.close()
elif mypath2 == 'vusolo2':
out = open('/etc/typboxa ', 'w')
out.write('Vu+Solo2 ')
out.close()
elif mypath2 == 'vusolose':
out = open('/etc/typboxa ', 'w')
out.write('Vu+Solo-SE ')
out.close()
elif mypath2 == 'vuvzero':
out = open('/etc/typboxa ', 'w')
out.write('Vu+Zero ')
out.close()
elif mypath2 == 'vuuno4k':
out = open('/etc/typboxa ', 'w')
out.write('Vu+Uno4k ')
out.close()
elif mypath2 == 'vuultimo4k':
out = open('/etc/typboxa ', 'w')
out.write('Vu+Ultimo4k ')
out.close()
elif mypath2 == 'vusolo4k':
out = open('/etc/typboxa ', 'w')
out.write('Vu+Solo4k ')
out.close()
elif mypath2 == 'mbmini':
out = open('/etc/typboxa', 'w')
out.write('Miraclebox-Mini ')
out.close()
elif mypath2 == 'mutant51':
out = open('/etc/typboxa', 'w')
out.write('Mutant 51 ')
out.close()
elif mypath2 == 'sf4008':
out = open('/etc/typboxa', 'w')
out.write('Ocatgon sf4008 ')
out.close()
elif mypath2 == 'ax51':
out = open('/etc/typboxa', 'w')
out.write('ax51 ')
out.close()
try:
lines = open('/etc/typboxa', 'r').readlines()
typboxa = lines[0][:-1]
except:
typboxa = 'not detected'
return typboxa
def getImageVersionString():
try:
if os.path.isfile('/var/lib/opkg/status'):
st = os.stat('/var/lib/opkg/status')
else:
st = os.stat('/usr/lib/ipkg/status')
tm = time.localtime(st.st_mtime)
if tm.tm_year >= 2015:
return time.strftime('%Y-%m-%d %H:%M:%S', tm)
except:
pass
return _('unavailable')
def getModelString():
try:
file = open('/proc/stb/info/boxtype', 'r')
model = file.readline().strip()
file.close()
return model
except IOError:
return 'unknown'
def getChipSetString():
try:
f = open('/proc/stb/info/chipset', 'r')
chipset = f.read()
f.close()
return str(chipset.lower().replace('\n', '').replace('bcm', ''))
except IOError:
return 'unavailable'
def getCPUString():
try:
file = open('/proc/cpuinfo', 'r')
lines = file.readlines()
for x in lines:
splitted = x.split(': ')
if len(splitted) > 1:
splitted[1] = splitted[1].replace('\n', '')
if splitted[0].startswith('system type'):
system = splitted[1].split(' ')[0]
elif splitted[0].startswith('Processor'):
system = splitted[1].split(' ')[0]
file.close()
return system
except IOError:
return 'unavailable'
def getCpuCoresString():
try:
file = open('/proc/cpuinfo', 'r')
lines = file.readlines()
for x in lines:
splitted = x.split(': ')
if len(splitted) > 1:
splitted[1] = splitted[1].replace('\n', '')
if splitted[0].startswith('processor'):
if int(splitted[1]) > 0:
cores = 2
else:
cores = 1
file.close()
return cores
except IOError:
return 'unavailable'
def getEnigmaVersionString():
import enigma
enigma_version = enigma.getEnigmaVersionString()
if '-(no branch)' in enigma_version:
enigma_version = enigma_version[:-12]
return enigma_version
def getKernelVersionString():
try:
f = open('/proc/version', 'r')
kernelversion = f.read().split(' ', 4)[2].split('-', 2)[0]
f.close()
return kernelversion
except:
return _('unknown')
def getHardwareTypeString():
try:
if os.path.isfile('/proc/stb/info/boxtype'):
return open('/proc/stb/info/boxtype').read().strip().upper() + ' (' + open('/proc/stb/info/board_revision').read().strip() + '-' + open('/proc/stb/info/version').read().strip() + ')'
if os.path.isfile('/proc/stb/info/vumodel'):
return 'VU+' + open('/proc/stb/info/vumodel').read().strip().upper() + '(' + open('/proc/stb/info/version').read().strip().upper() + ')'
if os.path.isfile('/proc/stb/info/model'):
return open('/proc/stb/info/model').read().strip().upper()
except:
pass
return _('unavailable')
def getImageTypeString():
try:
return open('/etc/issue').readlines()[-2].capitalize().strip()[:-6]
except:
pass
return _('undefined')
def getMachineBuild():
try:
return open('/proc/version', 'r').read().split(' ', 4)[2].split('-', 2)[0]
except:
return 'unknown'
def getVuBoxModel():
if fileExists('/proc/stb/info/vumodel'):
try:
l = open('/proc/stb/info/vumodel')
model = l.read()
l.close()
BOX_NAME = str(model.lower().strip())
l.close()
BOX_MODEL = 'vuplus'
except:
BOX_MODEL = 'not detected'
return BOX_MODEL
def getMachineProcModel():
if os.path.isfile('/proc/stb/info/vumodel'):
BOX_NAME = getBoxModel()
BOX_MODEL = getVuBoxModel()
if BOX_MODEL == 'vuplus':
if BOX_NAME == 'duo':
GETMACHINEPROCMODEL = 'bcm7335'
elif BOX_NAME == 'solo':
GETMACHINEPROCMODEL = 'bcm7325'
elif BOX_NAME == 'solo2':
GETMACHINEPROCMODEL = 'bcm7346'
elif BOX_NAME == 'solose':
GETMACHINEPROCMODEL = 'bcm7241'
elif BOX_NAME == 'ultimo' or BOX_NAME == 'uno':
GETMACHINEPROCMODEL = 'bcm7413'
elif BOX_NAME == 'zero':
GETMACHINEPROCMODEL = 'bcm7362'
elif BOX_NAME == 'duo2':
GETMACHINEPROCMODEL = 'bcm7425'
elif BOX_NAME == 'ultimo4k':
GETMACHINEPROCMODEL = 'bcm7444S'
elif BOX_NAME == 'uno4k':
GETMACHINEPROCMODEL = 'bcm7252S'
elif BOX_NAME == 'solo4k':
GETMACHINEPROCMODEL = 'bcm7376'
elif BOX_NAME == 'zero4K':
GETMACHINEPROCMODEL = 'bcm72604'
elif BOX_NAME == 'uno4kse':
GETMACHINEPROCMODEL = ''
procmodel = getMachineProcModel()
return procmodel
boxbrand = sys.modules[__name__]

885
NeoBoot/files/tools.py Normal file
View File

@@ -0,0 +1,885 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __init__ import _
import codecs
from enigma import getDesktop
from Components.ActionMap import ActionMap
from Components.Label import Label
from Components.ScrollLabel import ScrollLabel
from Components.Pixmap import Pixmap
from Components.Sources.List import List
from Components.ConfigList import ConfigListScreen
from Components.MultiContent import MultiContentEntryText, MultiContentEntryPixmapAlphaTest
from Components.config import getConfigListEntry, config, ConfigYesNo, ConfigText, ConfigSelection, NoSave
from Plugins.Extensions.NeoBoot.plugin import Plugins
from Plugins.Plugin import PluginDescriptor
from Screens.Standby import TryQuitMainloop
from Screens.MessageBox import MessageBox
from Screens.Console import Console
from Screens.Screen import Screen
from Tools.LoadPixmap import LoadPixmap
from Tools.Directories import resolveFilename, SCOPE_PLUGINS, SCOPE_SKIN_IMAGE, SCOPE_CURRENT_SKIN, fileExists, pathExists, createDir
from os import system, listdir, mkdir, chdir, getcwd, rename as os_rename, remove as os_remove, popen
from os.path import dirname, isdir, isdir as os_isdir
from enigma import eTimer
from Plugins.Extensions.NeoBoot.files.stbbranding import getNeoLocation, getImageNeoBoot, getKernelVersionString
import os
import time
import sys
import struct, shutil
PLUGINVERSION = '5.00'
neoboot = getNeoLocation()
def getKernelVersion():
try:
return open('/proc/version', 'r').read().split(' ', 4)[2].split('-', 2)[0]
except:
return _('unknown')
def getCPUtype():
cpu='UNKNOWN'
if os.path.exists('/proc/cpuinfo'):
with open('/proc/cpuinfo', 'r') as f:
lines = f.read()
f.close()
if lines.find('ARMv7') != -1:
cpu='ARMv7'
elif lines.find('mips') != -1:
cpu='MIPS'
return cpu
if os.path.exists('/etc/hostname'):
with open('/etc/hostname', 'r') as f:
myboxname = f.readline().strip()
f.close()
if os.path.exists('/proc/stb/info/vumodel'):
with open('/proc/stb/info/vumodel', 'r') as f:
vumodel = f.readline().strip()
f.close()
if os.path.exists('/proc/stb/info/boxtype'):
with open('/proc/stb/info/boxtype', 'r') as f:
boxtype = f.readline().strip()
f.close()
class BoundFunction:
__module__ = __name__
def __init__(self, fnc, *args):
self.fnc = fnc
self.args = args
def __call__(self):
self.fnc(*self.args)
class MBTools(Screen):
screenwidth = getDesktop(0).size().width()
if screenwidth and screenwidth == 1920:
skin = '\n <screen name="NeoBoot" position="center,center" size="1159,750" title="Narzedzia NeoBoota">\n\t\t<widget source="list" render="Listbox" position="15,27" size="1131,720" scrollbarMode="showOnDemand">\n\t\t\t<convert type="TemplatedMultiContent">\n \t\t{"template": [\n \t\t\tMultiContentEntryText(pos = (50, 1), size = (820, 46), flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 0),\n \t\t\tMultiContentEntryPixmapAlphaTest(pos = (4, 2), size = (66, 66), png = 1),\n \t\t\t],\n \t\t\t"fonts": [gFont("Regular", 35)],\n \t\t\t"itemHeight": 50\n \t\t}\n \t\t</convert>\n\t\t</widget>\n </screen>'
else:
skin = '\n <screen position="center,center" size="590,330" title="Narzedzia NeoBoota">\n\t\t<widget source="list" render="Listbox" position="10,16" size="570,300" scrollbarMode="showOnDemand" >\n\t\t\t<convert type="TemplatedMultiContent">\n \t\t{"template": [\n \t\t\tMultiContentEntryText(pos = (50, 1), size = (520, 36), flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 0),\n \t\t\tMultiContentEntryPixmapAlphaTest(pos = (4, 2), size = (36, 36), png = 1),\n \t\t\t],\n \t\t\t"fonts": [gFont("Regular", 22)],\n \t\t\t"itemHeight": 36\n \t\t}\n \t\t</convert>\n\t\t</widget>\n </screen>'
__module__ = __name__
def __init__(self, session):
Screen.__init__(self, session)
self.list = []
self['list'] = List(self.list)
self.updateList()
self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'ok': self.KeyOk,
'back': self.close})
def updateList(self):
self.list = []
mypath = '/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot'
if not fileExists(mypath + 'icons'):
mypixmap = '/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/ok.png'
png = LoadPixmap(mypixmap)
res = (_('Wykonaj kopi\xc4\x99 obrazu z NeoBoota'), png, 0)
self.list.append(res)
self['list'].list = self.list
res = (_('Przywr\xc3\xb3\xc4\x87 kopi\xc4\x99 obrazu do NeoBoota'), png, 1)
self.list.append(res)
self['list'].list = self.list
res = (_('Menad\xc5\xbcer urz\xc4\x85dze\xc5\x84'), png, 2)
self.list.append(res)
self['list'].list = self.list
res = (_('Usu\xc5\x84 image ZIP z katalogu ImagesUpload '), png, 3)
self.list.append(res)
self['list'].list = self.list
res = (_('Odinstalowanie NeoBoota'), png, 4)
self.list.append(res)
self['list'].list = self.list
res = (_('Reinstalacja NeoBoota'), png, 5)
self.list.append(res)
self['list'].list = self.list
res = (_('Zaktualizuj NeoBoota na wszystkich obrazach.'), png, 6)
self.list.append(res)
self['list'].list = self.list
res = (_('Kopia Zapasowa NeoBoota'), png, 7)
self.list.append(res)
self['list'].list = self.list
res = (_('Aktualizacja listy TV na zainstalowanych image.'), png, 8)
self.list.append(res)
self['list'].list = self.list
res = (_('Aktualizacja IPTVPlayer na zainstalowanych image.'), png, 9)
self.list.append(res)
self['list'].list = self.list
res = (_('Usuniecie hasla do root.'), png, 10)
self.list.append(res)
self['list'].list = self.list
res = (_('Sprawdz poprawnosc instalacji neoboota'), png, 11)
self.list.append(res)
self['list'].list = self.list
res = (_('Informacje NeoBoota'), png, 12)
self.list.append(res)
self['list'].list = self.list
res = (_('Wspierane tunery sat'), png, 13)
self.list.append(res)
self['list'].list = self.list
def KeyOk(self):
self.sel = self['list'].getCurrent()
if self.sel:
self.sel = self.sel[2]
if self.sel == 0 and self.session.open(MBBackup):
pass
if self.sel == 1 and self.session.open(MBRestore):
pass
if self.sel == 2 and self.session.open(MenagerDevices):
pass
if self.sel == 3 and self.session.open(MBDeleUpload):
pass
if self.sel == 4 and self.session.open(UnistallMultiboot):
pass
if self.sel == 5 and self.session.open(ReinstllNeoBoot):
pass
if self.sel == 6 and self.session.open(UpdateNeoBoot):
pass
if self.sel == 7 and self.session.open(BackupMultiboot):
pass
if self.sel == 8 and self.session.open(ListTv):
pass
if self.sel == 9 and self.session.open(IPTVPlayer):
pass
if self.sel == 10 and self.session.open(SetPasswd):
pass
if self.sel == 11 and self.session.open(CheckInstall):
pass
if self.sel == 12 and self.session.open(MultiBootMyHelp):
pass
if self.sel == 13 and self.session.open(TunerInfo):
pass
class MBBackup(Screen):
screenwidth = getDesktop(0).size().width()
if screenwidth and screenwidth == 1920:
skin = ' <screen position="center,center" size="850,750" title="Wykonaj kopie zapasowa obrazu z NeoBoota">\n\t\t\n <widget name="lab1" position="24, 5" size="819, 62" font="Regular;35" halign="center" valign="center" transparent="1" foregroundColor="blue" />\n\n <widget name="lab2" position="22, 82" size="819, 61" font="Regular;35" halign="center" valign="center" transparent="1" foregroundColor="blue" />\n\n <widget name="lab3" position="21, 150" size="819, 62" font="Regular;35" halign="center" valign="center" transparent="1" foregroundColor="blue" />\n \n <widget source="list" render="Listbox" itemHeight="40" selectionPixmap="/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/selektor.png" font="Regular;25" position="20, 218" zPosition="1" size="820, 376" scrollbarMode="showOnDemand" transparent="1">\n\t\t\t\n <convert type="StringList" font="Regular;35" />\n\n </widget>\n\n <ePixmap position="336, 596" size="181, 29" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/redcor.png" alphatest="on" zPosition="1" />\n\n <widget name="key_red" position="307, 629" zPosition="2" size="251, 77" font="Regular;35" halign="center" valign="center" backgroundColor="red" transparent="1" foregroundColor="red" />\n\n </screen>'
else:
skin = ' <screen position="center,center" size="700,550" title="Wykonaj kopie zapasowa obrazu z NeoBoota">\n\t\t\n <widget name="lab1" position="20,20" size="660,30" font="Regular;24" halign="center" valign="center" transparent="1"/>\n\n <widget name="lab2" position="20,50" size="660,30" font="Regular;24" halign="center" valign="center" transparent="1"/>\n\n <widget name="lab3" position="20,100" size="660,30" font="Regular;22" halign="center" valign="center" transparent="1"/>\n \n <widget source="list" render="Listbox" position="40,130" zPosition="1" size="620,360" scrollbarMode="showOnDemand" transparent="1" >\n\t\t\t\n <convert type="StringList" />\n</widget>\n<ePixmap position="280,500" size="140,40" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/redcor.png" alphatest="on" zPosition="1" />\n\n <widget name="key_red" position="280,500" zPosition="2" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="red" transparent="1" />\n\n </screen>'
def __init__(self, session):
Screen.__init__(self, session)
self['lab1'] = Label('')
self['lab2'] = Label('')
self['lab3'] = Label(_('Wybierz obraz z kt\xc3\xb3rego chcesz zrobi\xc4\x87 kopie'))
self['key_red'] = Label(_('Kopia Zapasowa'))
self['list'] = List([])
self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'back': self.close,
'ok': self.backupImage,
'red': self.backupImage})
if pathExists('/media/usb/ImageBoot'):
neoboot = 'usb'
elif pathExists('/media/hdd/ImageBoot'):
neoboot = 'hdd'
self.backupdir = '/media/' + neoboot + '/NeoBootImageBackup'
self.availablespace = '0'
self.onShow.append(self.updateInfo)
def updateInfo(self):
if pathExists('/media/usb/ImageBoot'):
neoboot = 'usb'
elif pathExists('/media/hdd/ImageBoot'):
neoboot = 'hdd'
device = '/media/' + neoboot + ''
usfree = '0'
devicelist = ['cf',
'hdd',
'card',
'usb',
'usb2']
for d in devicelist:
test = '/media/' + d + '/ImageBoot/.neonextboot'
if fileExists(test):
device = '/media/' + d
rc = system('df > /tmp/ninfo.tmp')
f = open('/proc/mounts', 'r')
for line in f.readlines():
if line.find('/hdd') != -1:
self.backupdir = '/media/' + neoboot + '/NeoBootImageBackup'
device = '/media/' + neoboot + ''
f.close()
if pathExists(self.backupdir) == 0 and createDir(self.backupdir):
pass
if fileExists('/tmp/ninfo.tmp'):
f = open('/tmp/ninfo.tmp', 'r')
for line in f.readlines():
line = line.replace('part1', ' ')
parts = line.strip().split()
totsp = len(parts) - 1
if parts[totsp] == device:
if totsp == 5:
usfree = parts[3]
else:
usfree = parts[2]
break
f.close()
os_remove('/tmp/ninfo.tmp')
self.availablespace = usfree[0:-3]
strview = _('Masz zainstalowane nas\xc5\xa7\xc4\x99puj\xc4\x85ce obrazy')
self['lab1'].setText(strview)
strview = _('Masz jeszcze wolne: ') + self.availablespace + ' MB'
self['lab2'].setText(strview)
imageslist = ['Flash']
for fn in listdir('/media/' + neoboot + '/ImageBoot'):
dirfile = '/media/' + neoboot + '/ImageBoot/' + fn
if os_isdir(dirfile) and imageslist.append(fn):
pass
self['list'].list = imageslist
def backupImage(self):
image = self['list'].getCurrent()
if image:
self.backimage = image.strip()
myerror = ''
if self.backimage == 'Flash':
myerror = _('Niestety nie mo\xc5\xbcna wykona\xc4\x87 kopii zapasowej z flesza t\xc4\x85 wtyczk\xc4\x85\nZainstaluj backupsuite do kopii obrazu z pamieci flesza')
if int(self.availablespace) < 150:
myerror = _('Brak miejca do zrobienia kopii obrazu. Potrzebne jest 150 Mb wolnego miejsca na kopie obrazu.')
if myerror == '':
message = _('Wykona\xc4\x87 kopi\xc4\x99 obrazu:') + image + ' teraz ?'
ybox = self.session.openWithCallback(self.dobackupImage, MessageBox, message, MessageBox.TYPE_YESNO)
ybox.setTitle(_('Potwierdzenie kopii zapasowej'))
else:
self.session.open(MessageBox, myerror, MessageBox.TYPE_INFO)
def dobackupImage(self, answer):
if answer is True:
if pathExists('/media/usb/ImageBoot'):
neoboot = 'usb'
elif pathExists('/media/hdd/ImageBoot'):
neoboot = 'hdd'
cmd = "echo -e '\n\n%s '" % _('Prosz\xc4\x99 czeka\xc4\x87, NeoBoot dzia\xc5\x82a, wykonywanie kopii zapasowej moze zajac kilka chwil, proces w toku...')
cmd1 = '/bin/tar -cf ' + self.backupdir + '/' + self.backimage + '.tar /media/' + neoboot + '/ImageBoot/' + self.backimage + ' > /dev/null 2>&1'
cmd2 = 'mv -f ' + self.backupdir + '/' + self.backimage + '.tar ' + self.backupdir + '/' + self.backimage + '.mb'
cmd3 = "echo -e '\n\n%s '" % _('NeoBoot: Kopia Zapasowa KOMPLETNA !')
self.session.open(Console, _('NeoBoot: Kopia Zapasowa Obrazu'), [cmd,
cmd1,
cmd2,
cmd3])
self.close()
class MBRestore(Screen):
__module__ = __name__
skin = ' \n\t<screen position="center,center" size="700,550" title="NeoBoot Przywracanie Obrazu">\n <widget name="lab1" position="20,20" size="660,30" font="Regular;24" halign="center" valign="center" transparent="1"/>\n <widget name="lab2" position="20,50" size="660,30" font="Regular;24" halign="center" valign="center" transparent="1"/>\n <widget name="lab3" position="20,100" size="660,30" font="Regular;22" halign="center" valign="center" transparent="1"/>\n <widget source="list" render="Listbox" position="40,130" zPosition="1" size="620,380" scrollbarMode="showOnDemand" transparent="1" >\n\t\t\t<convert type="StringList" />\n </widget>\n <ePixmap position="140,500" size="140,40" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/redcor.png" alphatest="on" zPosition="1" />\n <ePixmap position="420,500" size="140,40" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/greencor.png" alphatest="on" zPosition="1" />\n <widget name="key_red" position="140,500" zPosition="2" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="red" transparent="1" />\n <widget name="key_green" position="420,500" zPosition="2" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="green" transparent="1" />\n </screen>'
def __init__(self, session):
Screen.__init__(self, session)
self['lab1'] = Label('')
self['lab2'] = Label('')
self['lab3'] = Label(_('Wybierz kopi\xc4\x99 kt\xc3\xb3r\xc4\x85 chcesz przywr\xc3\xb3ci\xc4\x87'))
self['key_red'] = Label(_('Restore'))
self['key_green'] = Label(_('Delete'))
self['list'] = List([])
self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'back': self.close,
'ok': self.restoreImage,
'red': self.restoreImage,
'green': self.deleteback})
self.backupdir = '' + getNeoLocation() + 'NeoBootImageBackup'
self.availablespace = '0'
self.onShow.append(self.updateInfo)
def updateInfo(self):
linesdevice = open('/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/.location', 'r').readlines()
deviceneo = linesdevice[0][0:-1]
device = deviceneo
usfree = '0'
devicelist = ['cf',
'CF',
'hdd',
'card',
'sd',
'SD',
'usb',
'USB',
'usb2']
for d in devicelist:
test = '/media/' + d + '/ImageBoot/.neonextboot'
if fileExists(test):
device = device + d
rc = system('df > /tmp/ninfo.tmp')
f = open('/proc/mounts', 'r')
for line in f.readlines():
if line.find('/hdd') != -1:
self.backupdir = '' + getNeoLocation() + 'NeoBootImageBackup'
elif line.find('/usb') != -1:
self.backupdir = '' + getNeoLocation() + 'NeoBootImageBackup'
f.close()
if pathExists(self.backupdir) == 0 and createDir(self.backupdir):
pass
if fileExists('/tmp/ninfo.tmp'):
f = open('/tmp/ninfo.tmp', 'r')
for line in f.readlines():
line = line.replace('part1', ' ')
parts = line.strip().split()
totsp = len(parts) - 1
if parts[totsp] == device:
if totsp == 5:
usfree = parts[3]
else:
usfree = parts[2]
break
f.close()
os_remove('/tmp/ninfo.tmp')
self.availablespace = usfree[0:-3]
strview = _('Kopie Zapasowe znajduj\xc4\x85 si\xc4\x99 w katalogu /' + getNeoLocation() + 'NeoBootImageBackup')
self['lab1'].setText(strview)
strview = _('Ilo\xc5\x9b\xc4\x87 wolnego miejsca w Superbocie: ') + self.availablespace + ' MB'
self['lab2'].setText(strview)
imageslist = []
for fn in listdir(self.backupdir):
imageslist.append(fn)
self['list'].list = imageslist
def deleteback(self):
image = self['list'].getCurrent()
if image:
self.delimage = image.strip()
message = _('Wybierz obraz do przywr\xc3\xb3cenia lub usuni\xc4\x99cia:\n ') + image + '?'
ybox = self.session.openWithCallback(self.dodeleteback, MessageBox, message, MessageBox.TYPE_YESNO)
ybox.setTitle(_('Potwierdzenie Usuni\xc4\x99cia'))
def dodeleteback(self, answer):
if answer is True:
cmd = "echo -e '\n\n%s '" % _('SuperBoot usuwanie plik\xc3\xb3w kopi zapasowej.....')
cmd1 = 'rm ' + self.backupdir + '/' + self.delimage
self.session.open(Console, _('SuperBoot: Pliki kopii zapasowej usuni\xc4\x99te'), [cmd, cmd1])
self.updateInfo()
def restoreImage(self):
image = self['list'].getCurrent()
if image:
curimage = 'Flash'
if fileExists('/.neonextboot'):
f = open('/.neonextboot', 'r')
curimage = f.readline().strip()
f.close()
self.backimage = image.strip()
imagename = self.backimage[0:-3]
myerror = ''
if curimage == imagename:
myerror = _('Sorry you cannot overwrite the image currently booted from. Please, boot from Flash to restore this backup.')
if myerror == '':
message = _('Przed przywracaniem sprawdz czy masz wolne miejsce na swoim urz\xc4\x85dzeniu - 300Mb \nCzy chcesz przywr\xc3\xb3ci\xc4\x87 ten obraz:\n ') + image + '?'
ybox = self.session.openWithCallback(self.dorestoreImage, MessageBox, message, MessageBox.TYPE_YESNO)
ybox.setTitle(_('Potwierdzenie Przywracania'))
else:
self.session.open(MessageBox, myerror, MessageBox.TYPE_INFO)
def dorestoreImage(self, answer):
if answer is True:
imagename = self.backimage[0:-3]
cmd = "echo -e '\n\n%s '" % _('Wait please, NeoBoot is working: ....Restore in progress....')
cmd1 = 'mv -f ' + self.backupdir + '/' + self.backimage + ' ' + self.backupdir + '/' + imagename + '.tar'
cmd2 = '/bin/tar -xf ' + self.backupdir + '/' + imagename + '.tar -C /'
cmd3 = 'mv -f ' + self.backupdir + '/' + imagename + '.tar ' + self.backupdir + '/' + imagename + '.mb'
cmd4 = 'sync'
cmd5 = "echo -e '\n\n%s '" % _('Superboot: Restore COMPLETE !')
self.session.open(Console, _('NeoBoot: Restore Image'), [cmd,
cmd1,
cmd2,
cmd3,
cmd4,
cmd5])
self.close()
def myclose(self):
self.close()
def myclose2(self, message):
self.session.open(MessageBox, message, MessageBox.TYPE_INFO)
self.close()
class MenagerDevices(Screen):
__module__ = __name__
skin = '\n\t<screen position="center,center" size="700,300" title="Menad\xc5\xbcer urz\xc4\x85dze\xc5\x84">\n\t\t<widget name="lab1" position="20,20" size="660,215" font="Regular;24" halign="center" valign="center" transparent="1"/><ePixmap position="280,250" size="140,40" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/redcor.png" alphatest="on" zPosition="1" /><widget name="key_red" position="280,250" zPosition="2" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="red" transparent="1" /></screen>'
def __init__(self, session):
Screen.__init__(self, session)
self['lab1'] = Label('Uruchomic Menad\xc5\xbcer urz\xc4\x85dze\xc5\x84 ?')
self['key_red'] = Label(_('Uruchom'))
self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'back': self.close,
'red': self.MD})
def MD(self):
try:
from Plugins.Extensions.NeoBoot.files.devices import ManagerDevice
self.session.open(ManagerDevice)
except:
False
class UnistallMultiboot(Screen):
__module__ = __name__
skin = '\n\t<screen position="center,center" size="700,300" title="Odinstaluj NeoBoota">\n\t\t<widget name="lab1" position="20,20" size="660,215" font="Regular;24" halign="center" valign="center" transparent="1"/><ePixmap position="280,250" size="140,40" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/redcor.png" alphatest="on" zPosition="1" /><widget name="key_red" position="280,250" zPosition="2" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="red" transparent="1" /></screen>'
def __init__(self, session):
Screen.__init__(self, session)
self['lab1'] = Label('Czy odinstalowa\xc4\x87 NeoBoota ?')
self['key_red'] = Label(_('Odinstaluj'))
self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'back': self.close,
'red': self.usun})
def usun(self):
message = _('Je\xc5\x9bli wybierzesz Tak, zostan\xc4\x85 przywr\xc3\xb3cone ustawienia obrazu pli \nMultibot zostanie tylko odinstalowany. \nBedziesz m\xc3\xb3g\xc5\x82 go zainstalowa\xc4\x87 ponownie')
ybox = self.session.openWithCallback(self.reinstallneoboot, MessageBox, message, MessageBox.TYPE_YESNO)
ybox.setTitle(_('Delete Confirmation'))
def reinstallneoboot(self, answer):
if answer is True:
cmd0 = "echo -e '\n\nPrzywracanie ustawie\xc5\x84.....'"
cmd = "echo -e '\n%s '" % _('Czekaj usuwam...')
cmd1 = 'rm /sbin/multinit; sleep 2'
cmd1a = "echo -e '\nNeoBoot usuwanie mened\xc5\xbcera rozruchu....'"
cmd2 = 'rm /sbin/init; sleep 2'
cmd3 = 'ln -sfn /sbin/init.sysvinit /sbin/init'
cmd4 = 'chmod 777 /sbin/init; sleep 2'
cmd4a = "echo -e '\nNeoBoot restoring media mounts....'"
cmd6 = 'rm ' + getNeoLocation() + 'ImageBoot/.neonextboot;rm /usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/.location; sleep 2'
cmd7 = 'rm ' + getNeoLocation() + 'ImageBoot/.Flash; rm ' + getNeoLocation() + 'ImageBoot/.version'
cmd7a = "echo -e '\n\nOdinstalowywanie neoboota...'"
cmd8 = "echo -e '\n\nPrzywracanie montowania.'"
cmd9 = "echo -e '\n\nNeoBoot odinstalowany, mozesz zrobic reinstalacje.'"
self.session.openWithCallback(self.close, Console, _('NeoBoot is reinstall...'), [cmd0,
cmd,
cmd1,
cmd1a,
cmd2,
cmd3,
cmd4,
cmd4a,
cmd6,
cmd7,
cmd7a,
cmd8,
cmd9])
self.close()
class ReinstllNeoBoot(Screen):
__module__ = __name__
skin = '\n\t<screen position="center,center" size="700,300" title="Update NeoBoot">\n\t\t<widget name="lab1" position="20,20" size="660,215" font="Regular;24" halign="center" valign="center" transparent="1"/><ePixmap position="280,250" size="140,40" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/redcor.png" alphatest="on" zPosition="1" /><widget name="key_red" position="280,250" zPosition="2" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="red" transparent="1" /></screen>'
def __init__(self, session):
Screen.__init__(self, session)
self['lab1'] = Label('Przywrocic kopie NeoBoota z lokalizacji /media/neoboot ?')
self['key_red'] = Label(_('Backup'))
self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'back': self.close,
'red': self.reinstallMB})
def reinstallMB(self):
system('/bin/tar -xzvf ' + getNeoLocation() + 'NeoBoot_Backup.tar.gz -C /')
self.close()
class UpdateNeoBoot(Screen):
__module__ = __name__
skin = '\n\t<screen position="center,center" size="700,300" title="Update NeoBoot">\n\t\t<widget name="lab1" position="20,20" size="660,215" font="Regular;24" halign="center" valign="center" transparent="1"/><ePixmap position="280,250" size="140,40" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/redcor.png" alphatest="on" zPosition="1" /><widget name="key_red" position="280,250" zPosition="2" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="red" transparent="1" /></screen>'
def __init__(self, session):
Screen.__init__(self, session)
self['lab1'] = Label('Aktualizowac neoboota na wszystkich obrazach ?')
self['key_red'] = Label(_('Zainstaluj'))
self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'back': self.close,
'red': self.mbupload})
def mbupload(self):
self.session.open(MyUpgrade2)
class MyUpgrade2(Screen):
screenwidth = getDesktop(0).size().width()
if screenwidth and screenwidth == 1920:
skin = '<screen position="center,center" size="900,450" title="NeoBoot">\n\t\t<widget name="lab1" position="23,42" size="850,350" font="Regular;35" halign="center" valign="center" transparent="1" />\n</screen>'
else:
skin = '<screen position="center,center" size="400,200" title="NeoBoot">\n\t\t<widget name="lab1" position="10,10" size="380,180" font="Regular;24" halign="center" valign="center" transparent="1"/>\n\t</screen>'
def __init__(self, session):
Screen.__init__(self, session)
self['lab1'] = Label(_('[NeoBoot]Prosze czeka\xc4\x87, aktualizacja w toku...'))
self.activityTimer = eTimer()
self.activityTimer.timeout.get().append(self.updateInfo)
self.onShow.append(self.startShow)
def startShow(self):
self.activityTimer.start(10)
def updateInfo(self):
self.activityTimer.stop()
f2 = open('%sImageBoot/.neonextboot' % getNeoLocation(), 'r')
mypath2 = f2.readline().strip()
f2.close()
if mypath2 != 'Flash':
self.myClose(_('Sorry, NeoBoot can installed or upgraded only when booted from Flash STB'))
self.close()
else:
for fn in listdir('%sImageBoot' % getNeoLocation() ):
dirfile = '%sImageBoot/' % getNeoLocation() + fn
if isdir(dirfile):
target = dirfile + '/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot'
cmd = 'rm -r ' + target + ' > /dev/null 2>&1'
system(cmd)
cmd = 'cp -r /usr/lib/enigma2/python/Plugins/Extensions/NeoBoot ' + target
system(cmd)
out = open('%sImageBoot/.version' % getNeoLocation(), 'w')
out.write(PLUGINVERSION)
out.close()
self.myClose(_('NeoBoot successfully updated. You can restart the plugin now.\nHave fun !!'))
def myClose(self, message):
self.session.open(MessageBox, message, MessageBox.TYPE_INFO)
self.close()
class MBDeleUpload(Screen):
__module__ = __name__
skin = '\n\t<screen position="center,center" size="700,300" title="NeoBoot - wyczy\xc5\x9b\xc4\x87 pobrane image">\n\t\t<widget name="lab1" position="20,20" size="660,215" font="Regular;24" halign="center" valign="center" transparent="1"/><ePixmap position="280,250" size="140,40" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/redcor.png" alphatest="on" zPosition="1" /><widget name="key_red" position="280,250" zPosition="2" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="red" transparent="1" /></screen>'
def __init__(self, session):
Screen.__init__(self, session)
self['lab1'] = Label('Czy na pewno chcesz usun\xc4\x85\xc4\x87 obraz z katalogu ImagesUpload ?\n\nJe\xc5\x9bli wybierzesz czerwony przycisk na pilocie to usuniesz wszystkie obrazy ZIP z katalogu ImagesUpload')
self['key_red'] = Label(_('Wyczy\xc5\x9b\xc4\x87'))
self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'back': self.close,
'red': self.usunup})
def usunup(self):
message = _('Czy napewno chcesz wyczy\xc5\x9bci\xc4\x87')
ybox = self.session.openWithCallback(self.pedeleup, MessageBox, message, MessageBox.TYPE_YESNO)
ybox.setTitle(_('Czyszenie z pobranych obraz\xc3\xb3w'))
def pedeleup(self, answer):
if answer is True:
cmd = "echo -e '\n\n%s '" % _('Czekaj usuwam.....')
cmd1 = 'rm -r ' + getNeoLocation() + 'ImagesUpload/*.zip'
self.session.open(Console, _('Usuwanie pobranych obraz\xc3\xb3w....'), [cmd, cmd1])
self.close()
class BackupMultiboot(Screen):
__module__ = __name__
skin = '\n\t<screen position="center,center" size="590,330" title="Backup NeoBoot">\n\t\t<widget source="list" render="Listbox" position="10,16" size="570,300" scrollbarMode="showOnDemand" >\n\t\t\t<convert type="TemplatedMultiContent">\n \t\t{"template": [\n \t\t\tMultiContentEntryText(pos = (50, 1), size = (520, 36), flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 0),\n \t\t\tMultiContentEntryPixmapAlphaTest(pos = (4, 2), size = (36, 36), png = 1),\n \t\t\t],\n \t\t\t"fonts": [gFont("Regular", 22)],\n \t\t\t"itemHeight": 36\n \t\t}\n \t\t</convert>\n\t\t</widget>\n </screen>'
def __init__(self, session):
Screen.__init__(self, session)
self.list = []
self['list'] = List(self.list)
self.downList()
self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'ok': self.KeyOk,
'back': self.close})
def downList(self):
self.list = []
mypixmap = '/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/ok.png'
png = LoadPixmap(mypixmap)
res = (_('Wykonac kompletna kopie NeoBoota ?'), png, 0)
self.list.append(res)
self['list'].list = self.list
def KeyOk(self):
self.sel = self['list'].getCurrent()
if self.sel:
self.sel = self.sel[2]
if self.sel == 0:
cmd = 'sh /usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/files/NeoBoot.sh -i'
self.session.open(Console, _('Kopia zapasowa zostanie zapisana w lokalizacji /media/neoboot. Trwa wykonywanie....'), [cmd])
self.close()
class SetPasswd(Screen):
__module__ = __name__
skin = '\n\t<screen position="center,center" size="700,300" title="Zmiana Hasla">\n\t\t<widget name="lab1" position="20,20" size="660,215" font="Regular;24" halign="center" valign="center" transparent="1"/><ePixmap position="280,250" size="140,40" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/redcor.png" alphatest="on" zPosition="1" /><widget name="key_red" position="280,250" zPosition="2" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="red" transparent="1" /></screen>'
def __init__(self, session):
Screen.__init__(self, session)
self['lab1'] = Label('Czy skasowac haslo ?')
self['key_red'] = Label(_('Uruchom'))
self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'back': self.close,
'red': self.passwd})
def passwd(self):
os.system('passwd -d root')
restartbox = self.session.openWithCallback(self.restartGUI, MessageBox, _('GUI needs a restart.\nDo you want to Restart the GUI now?'), MessageBox.TYPE_YESNO)
restartbox.setTitle(_('Restart GUI now?'))
def restartGUI(self, answer):
if answer is True:
self.session.open(TryQuitMainloop, 3)
else:
self.close()
class ReinstallKernel(Screen):
__module__ = __name__
skin = '\n\t<screen position="center,center" size="700,300" title="Module kernel">\n\t\t<widget name="lab1" position="20,20" size="660,215" font="Regular;24" halign="center" valign="center" transparent="1"/><ePixmap position="280,250" size="140,40" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/redcor.png" alphatest="on" zPosition="1" /><widget name="key_red" position="280,250" zPosition="2" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="red" transparent="1" /></screen>'
def __init__(self, session):
Screen.__init__(self, session)
self['lab1'] = Label('Reinstalacja j\xc4\x85dra.\n\nZainstalowa\xc4\x87 ?')
self['key_red'] = Label(_('Instalacja'))
self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'back': self.close,
'red': self.kernel_image})
def kernel_image(self):
os.system('echo "Flash " > ' + getNeoLocation() + 'ImageBoot/.neonextboot')
out = open('' + getNeoLocation() + 'ImagesUpload/.kernel/used_flash_kernel', 'w')
out.write('Used Kernel: Flash')
out.close()
cmd1 = 'rm -f /home/root/*.ipk; opkg download kernel-image; sleep 2; opkg install --force-maintainer --force-reinstall --force-overwrite --force-downgrade /home/root/*.ipk; opkg configure update-modules'
self.session.open(Console, _('NeoBoot....'), [cmd1])
self.close()
class ListTv(Screen):
__module__ = __name__
screenwidth = getDesktop(0).size().width()
if screenwidth and screenwidth == 1920:
skin = '<screen position="center,center" size="900,450" title="NeoBoot">\n\t\t<widget name="lab1" position="23,42" size="850,350" font="Regular;35" halign="center" valign="center" transparent="1" />\n</screen>'
else:
skin = '<screen position="center,center" size="400,200" title="NeoBoot">\n\t\t<widget name="lab1" position="10,10" size="380,180" font="Regular;24" halign="center" valign="center" transparent="1"/>\n\t</screen>'
def __init__(self, session):
Screen.__init__(self, session)
self['lab1'] = Label(_('NeoBoot: Upgrading in progress\nPlease wait...'))
self.activityTimer = eTimer()
self.activityTimer.timeout.get().append(self.updateInfo)
self.onShow.append(self.startShow)
def startShow(self):
self.activityTimer.start(10)
def updateInfo(self):
self.activityTimer.stop()
f2 = open('' + getNeoLocation() + 'ImageBoot/.neonextboot', 'r')
mypath2 = f2.readline().strip()
f2.close()
if mypath2 != 'Flash':
self.myClose(_('Sorry, NeoBoot can installed or upgraded only when booted from Flash.'))
self.close()
else:
os.system('mv /etc/enigma2 /etc/enigma2.tmp')
os.system('mkdir -p /etc/enigma2')
os.system('cp -f /etc/enigma2.tmp/*.tv /etc/enigma2')
os.system('cp -f /etc/enigma2.tmp/*.radio /etc/enigma2')
os.system('cp -f /etc/enigma2.tmp/lamedb /etc/enigma2')
for fn in listdir('' + getNeoLocation() + 'ImageBoot'):
dirfile = '' + getNeoLocation() + 'ImageBoot/' + fn
if isdir(dirfile):
target = dirfile + '/etc/'
cmd = 'cp -r -f /etc/enigma2 ' + target
system(cmd)
target1 = dirfile + '/etc/tuxbox'
cmd = 'cp -r -f /etc/tuxbox/satellites.xml ' + target1
system(cmd)
target2 = dirfile + '/etc/tuxbox'
cmd = 'cp -r -f /etc/tuxbox/terrestrial.xml ' + target2
system(cmd)
os.system('rm -f -R /etc/enigma2')
os.system('mv /etc/enigma2.tmp /etc/enigma2/')
self.myClose(_('NeoBoot successfully updated list tv.\nHave fun !!'))
def myClose(self, message):
self.session.open(MessageBox, message, MessageBox.TYPE_INFO)
self.close()
class IPTVPlayer(Screen):
__module__ = __name__
screenwidth = getDesktop(0).size().width()
if screenwidth and screenwidth == 1920:
skin = '<screen position="center,center" size="900,450" title="IPTVPlayer">\n\t\t<widget name="lab1" position="23,42" size="850,350" font="Regular;35" halign="center" valign="center" transparent="1" />\n</screen>'
else:
skin = '<screen position="center,center" size="400,200" title="IPTVPlayer">\n\t\t<widget name="lab1" position="10,10" size="380,180" font="Regular;24" halign="center" valign="center" transparent="1"/>\n\t</screen>'
def __init__(self, session):
Screen.__init__(self, session)
self['lab1'] = Label(_('NeoBoot: Upgrading in progress\nPlease wait...'))
self.activityTimer = eTimer()
self.activityTimer.timeout.get().append(self.updateInfo)
self.onShow.append(self.startShow)
def startShow(self):
self.activityTimer.start(10)
def updateInfo(self):
self.activityTimer.stop()
f2 = open('' + getNeoLocation() + 'ImageBoot/.neonextboot', 'r')
mypath2 = f2.readline().strip()
f2.close()
if mypath2 != 'Flash':
self.myClose(_('Sorry, NeoBoot can installed or upgraded only when booted from Flash.'))
self.close()
elif not fileExists('/usr/lib/enigma2/python/Plugins/Extensions/IPTVPlayer'):
self.myClose(_('Sorry, IPTVPlayer not found.'))
self.close()
else:
for fn in listdir('' + getNeoLocation() + 'ImageBoot'):
dirfile = '' + getNeoLocation() + 'ImageBoot/' + fn
if isdir(dirfile):
target = dirfile + '/usr/lib/enigma2/python/Plugins/Extensions/IPTVPlayer'
cmd = 'rm -r ' + target + ' > /dev/null 2>&1'
system(cmd)
cmd = 'cp -r /usr/lib/enigma2/python/Plugins/Extensions/IPTVPlayer ' + target
system(cmd)
self.myClose(_('NeoBoot successfully updated IPTVPlayer.\nHave fun !!'))
def myClose(self, message):
self.session.open(MessageBox, message, MessageBox.TYPE_INFO)
self.close()
class SetPasswd(Screen):
__module__ = __name__
skin = '\n\t<screen position="center,center" size="700,300" title="Zmiana Hasla">\n\t\t<widget name="lab1" position="20,20" size="660,215" font="Regular;24" halign="center" valign="center" transparent="1"/><ePixmap position="280,250" size="140,40" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/redcor.png" alphatest="on" zPosition="1" /><widget name="key_red" position="280,250" zPosition="2" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="red" transparent="1" /></screen>'
def __init__(self, session):
Screen.__init__(self, session)
self['lab1'] = Label('Czy skasowac haslo ?')
self['key_red'] = Label(_('Uruchom'))
self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'back': self.close,
'red': self.passwd})
def passwd(self):
os.system('passwd -d root')
restartbox = self.session.openWithCallback(self.restartGUI, MessageBox, _('GUI needs a restart.\nDo you want to Restart the GUI now?'), MessageBox.TYPE_YESNO)
restartbox.setTitle(_('Restart GUI now?'))
def restartGUI(self, answer):
if answer is True:
self.session.open(TryQuitMainloop, 3)
else:
self.close()
class CheckInstall(Screen):
__module__ = __name__
skin = '\n\t<screen position="center,center" size="700,300" title="Zmiana Hasla">\n\t\t<widget name="lab1" position="20,20" size="660,215" font="Regular;24" halign="center" valign="center" transparent="1"/><ePixmap position="280,250" size="140,40" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/redcor.png" alphatest="on" zPosition="1" /><widget name="key_red" position="280,250" zPosition="2" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="red" transparent="1" /></screen>'
def __init__(self, session):
Screen.__init__(self, session)
self['lab1'] = Label('Sprawdzanie poprawnosci zainstalwoanych modulow dla NeoBoota')
self['key_red'] = Label(_('Uruchom'))
self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'back': self.close,
'red': self.neocheck})
def neocheck(self):
try:
cmd = ' /usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/files/module_neoboot.sh -i'
self.session.openWithCallback(self.close, Console, _('NeoBoot....'), [cmd,
cmd])
self.close()
except:
False
class MultiBootMyHelp(Screen):
screenwidth = getDesktop(0).size().width()
if screenwidth and screenwidth == 1920:
skin = '<screen name=" NeoBoot" position="center,center" size="1920,1080" title="NeoBoot - Opis" flags="wfNoBorder">\n<eLabel text="INFORMACJE NeoBoot" font="Regular; 35" position="69,66" size="1777,96" halign="center" foregroundColor="yellow" backgroundColor="black" transparent="1" /><widget name="lab1" position="69,162" size="1780,885" font="Regular;35" />\n</screen>'
else:
skin = '<screen name=" NeoBoot" position="center,center" size="1280,720" title="NeoBoot - Opis">\n<widget name="lab1" position="18,19" size="1249,615" font="Regular;20" />\n</screen>'
__module__ = __name__
def __init__(self, session):
Screen.__init__(self, session)
self['lab1'] = ScrollLabel('')
self['actions'] = ActionMap(['WizardActions', 'ColorActions', 'DirectionActions'], {'back': self.close,
'ok': self.close,
'up': self['lab1'].pageUp,
'left': self['lab1'].pageUp,
'down': self['lab1'].pageDown,
'right': self['lab1'].pageDown})
self['lab1'].hide()
self.updatetext()
def updatetext(self):
message = ''
message += 'NeoBoot Wersja ' + PLUGINVERSION + ' Enigma2\n\n'
message += 'NeoBoot opiera si\xc4\x99 na EGAMIBoot < mod by gutosie >\n\n'
message += 'Autor EGAMIBoota zezwolil na rozwijanie i edycje NeoBoot - Thanks/Dzi\xc4\x99ki\n\n'
message += 'nfidump by gutemine - Thanks/Dzi\xc4\x99ki\n\n'
message += 'ubi_reader by Jason Pruitt - Thanks/Dzi\xc4\x99ki\n\n'
message += 'T\xc5\x82umaczenie: gutosie\n\n'
message += _('Podziekowania wszystkim tu niewspomnianym za udzielenie pomocy w ulepszaniu NeoBoota \n\n')
message += _('Udanej zabawy :)\n\n')
self['lab1'].show()
self['lab1'].setText(message)
class TunerInfo(Screen):
__module__ = __name__
skin = '\n\t<screen position="center,center" size="700,300" title="NeoBoot - Tunery Sat">\n\t\t<widget name="lab1" position="20,20" size="660,215" font="Regular;24" halign="center" valign="center" transparent="1"/><ePixmap position="280,250" size="140,40" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/redcor.png" alphatest="on" zPosition="1" /><widget name="key_red" position="280,250" zPosition="2" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="red" transparent="1" /></screen>'
def __init__(self, session):
Screen.__init__(self, session)
self['lab1'] = Label('NeoBoot: Lista wspieranych modeli STB.')
self['key_red'] = Label(_('Uruchom - Red'))
self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'back': self.close,
'red': self.iNFO})
def iNFO(self):
try:
cmd = ' cat /usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/stbinfo'
cmd1 = ''
self.session.openWithCallback(self.close, Console, _('NeoBoot....'), [cmd,
cmd1])
self.close()
except:
False
def myboot(session, **kwargs):
session.open(MBTools)
def Plugins(path, **kwargs):
global pluginpath
pluginpath = path
return PluginDescriptor(name='NeoBoot', description='MENU NeoBoot', icon=None, where=PluginDescriptor.WHERE_PLUGINMENU, fnc=myboot)