Beispiel #1
0
 def __init__(self, devname):
     self._name = path.basename(devname)
     self._blockPath = path.join('/sys/block', self._name)
     self._classPath = path.realpath(path.join('/sys/class/block', self._name))
     self._deviceNode = devname
     try:
         self._partition = int(Util.readFile(self.sysfsPath('partition')))
     except:
         self._partition = 0
     try:
         # Partitions don't have a 'removable' property. Ask their parent.
         self._isRemovable = bool(int(Util.readFile(self.sysfsPath('removable', physdev=True))))
     except IOError:
         self._isRemovable = False
Beispiel #2
0
def parseMountFile(path):
    mount_points = []
    lines = readFile(path).splitlines()
    for line in lines:
        _, mount_point, _, _, _, _ = Util.parseFstabLine(line)
        if mount_point not in ignore_mount_points:
            mount_points.append(mount_point)
    logger.debug("mount_points: %s", mount_points)
    return mount_points
Beispiel #3
0
 def _onSharesApplied(self):
     logger.debug("...")
     for sharename, data in self._mounts.items():
         mountpoint = AutoMount.MOUNT_BASE + sharename
         data["isMounted"] = Util.findInMtab(dst=mountpoint)
         desc = data["sharename"]
         if data["hdd_replacement"]:  #hdd replacement hack
             self._linkAsHdd(mountpoint)
         harddiskmanager.addMountedPartition(mountpoint, desc)
def readCutsFile(path):
    #print("MVC: CutListUtils: readCutsFile: " + path)
    data = ""
    #	cut_list = []
    if os.path.isfile(path):
        data = Util.readFile(path)


#		cut_list = unpackCutList(data)
#print("MVC: CutListUtils: readCutsFile: cut_list: " + str(cut_list))
    return data
Beispiel #5
0
    def __readFile(self, path):
        meta = ["", "", "", "", "", "", ""]

        if os.path.isfile(path):
            lines = Util.readFile(path).splitlines()

            # Parse the lines
            if lines:
                # Strip lines and extract information
                lines = [l.strip() for l in lines]
                meta = lines[:]
        return meta
Beispiel #6
0
 def deactivateMount(self, mountpoint, callback=None):
     logger.debug("mountpoint: %s", mountpoint)
     res = False
     entry = Util.findInFstab(src=None, dst=mountpoint)
     if entry:
         self._unmount(mountpoint)
         harddiskmanager.modifyFstabEntry(entry["src"],
                                          entry["dst"],
                                          mode="remove")
         harddiskmanager.removeMountedPartition(mountpoint)
         res = True
     if callback is not None:
         callback(res)
Beispiel #7
0
	def removeMount(self, mountpoint, callback=None):
		res = False
		entry = Util.findInFstab(src=None, dst=mountpoint)
		if entry:
			sharename=os_path.basename(mountpoint)
			if sharename in self._mounts:
				del self._mounts[sharename]
			self._unmount(mountpoint)
			harddiskmanager.modifyFstabEntry(entry['src'], entry['dst'], mode="remove")
			harddiskmanager.removeMountedPartition(mountpoint)
			res = True
		if callback is not None:
			callback(res)
Beispiel #8
0
	def removeMount(self, mountpoint, callback=None):
		res = False
		entry = Util.findInFstab(src=None, dst=mountpoint)
		if entry:
			sharename=os_path.basename(mountpoint)
			if sharename in self._mounts:
				del self._mounts[sharename]
			self._unmount(mountpoint)
			harddiskmanager.modifyFstabEntry(entry['src'], entry['dst'], mode="remove")
			harddiskmanager.removeMountedPartition(mountpoint)
			res = True
		if callback is not None:
			callback(res)
	def getMountPointDevice(self, path):
		try:
			from Components.Harddisk import getProcMounts
			procMounts = getProcMounts()
		except:
			# http://git.opendreambox.org/?p=enigma2.git;a=blob;f=usr/lib/enigma2/python/Components/Harddisk.py
			from Components.Harddisk import Util
			procMounts = Util.mtab(virt=False)
		device = ""
		for x in procMounts:
			for entry in x:
				if path == entry:
					device = x[0]
		return device
Beispiel #10
0
 def updateHotplugDevices(self):
     self.hotplugServices = []
     print "[update hutplug]"
     try:
         import commands
         movieConfig = MovieConfig()
         lines = commands.getoutput('mount | grep /dev/sd').split('\n')
         print lines
         for mount in lines:
             if len(mount) < 2:
                 continue
             dev = mount.split(' on ')[0].strip()
             m = mount.split(' type')[0].split(' on ')
             m_dev, m_path = m[0], m[1]
             label = os.path.split(m_path)[-1]
             blkid = commands.getoutput('blkid ' + m_dev).split("\"")
             #if len(blkid) > 2 and blkid[1]:
             #    label = blkid[1]
             if "LABEL" in blkid:
                 label = blkid.split("LABEL=")[1].split(" ")[0].strip()
             if os.path.normpath(m_path) == "/media/hdd" or label in ("DUMBO", "TIMOTHY"):
                 continue
             if not movieConfig.isHiddenHotplug(label):
                 blkdev = BlockDevice(dev)
                 if m_path[-1] != "/":
                     m_path += "/"
                 
                 #print blkdev.isRemovable()
                 #print blkdev.name()
                 #print blkdev.capacityString()
                 if not blkdev.isRemovable():
                     continue
                 
                 service = eServiceReferenceHotplug(m_path)
                 devname = m_dev.replace("/dev/", "")[:-1]
                 filename = str.format("/sys/block/{0}/device/block/{0}/device/model", devname)
                 #model = commands.getoutput("cat " + filename)
                 model = Util.readFile(filename)
                 if label:
                     label += " - "
                 service.setName(label + model + " - " + blkdev.capacityString())
                 self.hotplugServices.append(service)
         
         for callback in self.notifier:
             try:
                 callback()
             except:
                 printStackTrace()
     except:
         printStackTrace()
Beispiel #11
0
 def getMountPointDevice(self, path):
     try:
         from Components.Harddisk import getProcMounts
         procMounts = getProcMounts()
     except:
         # http://git.opendreambox.org/?p=enigma2.git;a=blob;f=usr/lib/enigma2/python/Components/Harddisk.py
         from Components.Harddisk import Util
         procMounts = Util.mtab(virt=False)
     device = ""
     for x in procMounts:
         for entry in x:
             if path == entry:
                 device = x[0]
     return device
class ConfigScreen(ConfigListScreen, Screen, Trashcan, object):
    skin = Util.readFile(getSkinPath("ConfigScreen.xml"))

    def __init__(self, session):
        Screen.__init__(self, session)
        self.skinName = "ConfigScreenMenu"

        self["actions"] = ActionMap(
            ["SetupActions", "OkCancelActions", "MVCConfigActions"],
            {
                "ok": self.keyOK,
                "cancel": self.keyCancel,
                "red": self.keyCancel,
                "up": self.keyUp,
                "down": self.keyDown,
                "green": self.keySaveNew,
                #			"bluelong": self.loadPredefinedSettings,
                "blueshort": self.loadDefaultSettings,
                "nextBouquet": self.keyPreviousSection,
                "prevBouquet": self.keyNextSection,
            },
            -2  # higher priority
        )

        self["key_red"] = Button(_("Cancel"))
        self["key_green"] = Button(_("Save"))
        self["key_blue"] = Button(_("Defaults"))
        self["help"] = StaticText()

        self.list = []
        self.MVCConfig = []
        ConfigListScreen.__init__(self, self.list, on_change=self.changedEntry)
        self.needsRestartFlag = False
        self.defineConfig()
        self.createConfig()

        self.reloadTimer = eTimer()
        self.reloadTimer_conn = self.reloadTimer.timeout.connect(
            self.createConfig)

        # Override selectionChanged because our config tuples have a size bigger than 2
        def selectionChanged():
            current = self["config"].getCurrent()
            if self["config"].current != current:
                if self["config"].current:
                    try:
                        self["config"].current[1].onDeselect()
                    except Exception:
                        pass
                if current:
                    try:
                        current[1].onSelect()
                    except Exception:
                        pass
                self["config"].current = current
            for x in self["config"].onSelectionChanged:
                try:
                    x()
                except Exception:
                    pass

        self["config"].selectionChanged = selectionChanged
        self["config"].onSelectionChanged.append(self.updateHelp)

    def defineConfig(self):
        self.section = 400 * "¯"
        #    _config list entry
        #    _                                                      , config element
        #          _                                                ,                                      , function called on save
        #          _                                                ,                                      ,                       , function called if user has pressed OK
        #          _                                                ,                                      ,                       ,                      , usage setup level from E2
        #          _                                                ,                                      ,                       ,                      ,   0: simple+
        #          _                                                ,                                      ,                       ,                      ,   1: intermediate+
        #          _                                                ,                                      ,                       ,                      ,   2: expert+
        #          _                                                ,                                      ,                       ,                      ,       , depends on relative parent entries
        #          _                                                ,                                      ,                       ,                      ,       ,   parent config value < 0 = true
        #          _                                                ,                                      ,                       ,                      ,       ,   parent config value > 0 = false
        #          _                                                ,                                      ,                       ,                      ,       ,             , _context sensitive help text
        #          _                                                ,                                      ,                       ,                      ,       ,             ,                                                         ,
        #       _ 0                                                 , 1                                    , 2                     , 3                    , 4     , 5           , 6                                                       ,
        self.MVCConfig = [
            (self.section, _("GENERAL"), None, None, 0, [], ""),
            (_("About"), config.MVC.fake_entry, None, self.showInfo, 0, [],
             _("HELP About")),
            (_("Disable plugin"), config.MVC.ml_disable, self.needsRestart,
             None, 1, [], _("Help Disable Plugin")),
            (_("Start plugin with"), config.MVC.movie_launch,
             self.launchListSet, None, 0, [], _("Help Start plugin with")),
            (_("Show plugin config in extensions menu"),
             config.MVC.extmenu_plugin, self.needsRestart, None, 0, [],
             _("Help Show plugin config in extensions menu")),
            (_("Show plugin in extensions menu"), config.MVC.extmenu_list,
             self.needsRestart, None, 0, [],
             _("Help Show plugin in extensions menu")),
            (_("Movie home at start"), config.MVC.MVCStartHome, None, None, 0,
             [], _("Help Movie home at start")),
            (_("Default sort mode"), config.MVC.moviecenter_sort, None, None,
             0, [], _("Help Sort mode at startup")),
            (_("Movie home home path"), config.MVC.movie_homepath,
             self.validatePath, self.openLocationBox, 0, [],
             _("Help Movie home home path")),
            (_("Path access limit"), config.MVC.movie_pathlimit, None, None, 1,
             [], _("Help Path access limit")),
            (_("Display directory reading text"),
             config.MVC.moviecenter_loadtext, None, None, 1, [],
             _("Help Display directory reading text")),
            (self.section, _("KEYMAPPING"), None, None, 0, [], ""),
            (_("Bouquet buttons behaviour"), config.MVC.bqt_keys, None, None,
             0, [], _("Help Bouquet buttons behaviour")),
            (_("List entries to skip"), config.MVC.list_skip_size, None, None,
             0, [], _("Help List entries to skip")),
            (_("Red button function"), config.MVC.movie_redfunc, None, None, 0,
             [], _("Help Red button function")),
            (_("Long Red button function"), config.MVC.movie_longredfunc, None,
             None, 0, [], _("Help Long Red button function")),
            (_("Yellow button function"), config.MVC.movie_yellowfunc, None,
             None, 0, [], _("Help Yellow button function")),
            (_("Long Yellow button function"), config.MVC.movie_longyellowfunc,
             None, None, 0, [], _("Help Long Yellow button function")),
            (_("Blue button function"), config.MVC.movie_bluefunc, None, None,
             0, [], _("Help Blue button function")),
            (_("Long Blue button function"), config.MVC.movie_longbluefunc,
             None, None, 0, [], _("Help Long Blue button function")),
            (_("LongInfo Button"), config.MVC.InfoLong, None, None, 0, [],
             _("Help LongInfo Button")),
            (self.section, _("PLAYBACK"), None, None, 0, [], ""),
            (_("No resume below 10 seconds"),
             config.MVC.movie_ignore_firstcuts, None, None, 1, [],
             _("Help No resume below 10 seconds")),
            (_("Jump to first mark when playing movie"),
             config.MVC.movie_jump_first_mark, None, None, 1, [],
             _("Help Jump to first mark when playing movie")),
            (_("Rewind finished movies before playing"),
             config.MVC.movie_rewind_finished, None, None, 1, [],
             _("Help Rewind finished movies before playing")),
            (_("Zap to channel after record EOF"), config.MVC.record_eof_zap,
             None, None, 1, [], _("Help Zap to channel after record EOF")),
            (_("Re-open list after stop"), config.MVC.movie_reopen, None, None,
             1, [], _("Help Re-open list after STOP-press")),
            (_("Re-open list after movie end"), config.MVC.movie_reopenEOF,
             None, None, 1, [], _("Help Re-open list after Movie end")),
            (_("Leave movie with Exit"), config.MVC.movie_exit, None, None, 0,
             [], _("Help Leave Movie with Exit")),
            (_("Automatic timers list cleaning"), config.MVC.timer_autoclean,
             None, None, 1, [], _("Help Automatic timers list cleaning")),
            (self.section, _("DISPLAY-SETTINGS"), None, None, 0, [], ""),
            (_("Show directories"), config.MVC.directories_show, None, None, 0,
             [], _("Help Show directories")),
            (_("Show directories within movielist"),
             config.MVC.directories_ontop, None, None, 0, [-1],
             _("Help Show directories within movielist")),
            (_("Show directories information"), config.MVC.directories_info,
             None, None, 0, [-2], _("Help Show directories information")),
            (_("Hide movies being moved"), config.MVC.movie_hide_mov, None,
             None, 1, [], _("Help Hide movies being moved")),
            (_("Hide movies being deleted"), config.MVC.movie_hide_del, None,
             None, 1, [], _("Help Hide movies being deleted")),
            (_("Cursor predictive move after selection"),
             config.MVC.moviecenter_selmove, None, None, 0, [],
             _("Help Cursor predictive move after selection")),
            (_("Show bookmarks in movielist"), config.MVC.bookmarks, None,
             None, 0, [], _("Help Show Bookmarks in movielist")),
            (_("Description field update delay"), config.MVC.movie_descdelay,
             None, None, 2, [], _("Help Description field update delay")),
            (self.section, _("SKIN-SETTINGS"), None, None, 0, [], ""),
            (_("Skin style (needs reopen)"), config.MVC.skinstyle, None, None,
             0, [], _("Help Skin style (needs reopen)")),
            (_("Date format"), config.MVC.movie_date_format, None, None, 0, [],
             _("Help Date format")),
            (_("Horizontal alignment for count/size"),
             config.MVC.count_size_position, None, None, 0, [],
             _("Help Horizontal alignment for count / size")),
            (_("Show movie icons"), config.MVC.movie_icons, None, None, 0, [],
             _("Help Show movie icons")),
            (_("Show link arrow"), config.MVC.link_icons, None, None, 0, [-1],
             _("Help Show link arrow")),
            (_("Show movie picons"), config.MVC.movie_picons, None, None, 0,
             [], _("Help Show movie picons")),
            (_("Path to movie picons"), config.MVC.movie_picons_path,
             self.validatePath, self.openLocationBox, 0, [-1],
             _("Help Path to movie picons")),
            (_("Show movie progress"), config.MVC.movie_progress, None, None,
             0, [], _("Help Show movie progress")),
            (_("Short watching percent"), config.MVC.movie_watching_percent,
             None, None, 0, [-1], _("Help Short watching percent")),
            (_("Finished watching percent"), config.MVC.movie_finished_percent,
             None, None, 0, [-2], _("Help Finished watching percent")),
            (_("Default color for recording movie"),
             config.MVC.color_recording, None, None, 0, [-3],
             _("Help Default color recording")),
            (_("Default color for highlighted movie"),
             config.MVC.color_highlight, None, None, 0, [-4],
             _("Help Default color highlighted")),
            (_("Hide MiniTV"), config.MVC.hide_miniTV, None, None, 0, [],
             _("Help hide_MiniTV")),
            (self.section, _("COVER DISPLAY"), None, None, 0, [], ""),
            (_("Show Cover"), config.MVC.cover, None, None, 0, [],
             _("Help Show Cover")),
            (_("Cover delay in ms"), config.MVC.cover_delay, None, None, 0,
             [-1], _("Help Cover delay in ms")),
            (_("Cover background"), config.MVC.cover_background, None, None, 0,
             [-2], _("HELP_Cover background")),
            (_("Show fallback cover"), config.MVC.cover_fallback, None, None,
             0, [-3], _("Help Cover fallback")),
            (_("Hide MiniTV if Cover is shown"), config.MVC.cover_hide_miniTV,
             None, None, 0, [-4], _("Help Cover hide_MiniTV")),
            (self.section, _("COVER SEARCH"), None, None, 0, [], ""),
            (_("Cover language"), config.MVC.cover_language, None, None, 0, [],
             _("Help Cover language")),
            (_("Cover size"), config.MVC.cover_size, None, None, 0, [],
             _("Help Cover size")),
            (_("Cover automatic selection"), config.MVC.cover_auto_selection,
             None, None, 0, [], _("Help Cover auto selection")),
            (_("Cover in flash"), config.MVC.cover_flash, None, None, 0, [],
             _("Help Cover in flash")),
            (_("Cover bookmark"), config.MVC.cover_bookmark, self.validatePath,
             self.openLocationBox, 0, [-1], _("Help Cover bookmark")),
            (self.section, _("TRASHCAN"), None, None, 0, [], ""),
            (_("Trashcan enable"), config.MVC.movie_trashcan_enable,
             self.activateTrashcan, None, 0, [], _("Help Trashcan enable")),
            (_("Trashcan path"), config.MVC.movie_trashcan_path,
             self.validatePath, self.openLocationBox, 0, [-1],
             _("Help Trashcan path")),
            (_("Show trashcan directory"), config.MVC.movie_trashcan_show,
             None, None, 0, [-2], _("Help Show trashcan directory")),
            (_("Show trashcan information"), config.MVC.movie_trashcan_info,
             None, None, 0, [-3, -1], _("Help Dynamic trashcan")),
            (_("Delete validation"), config.MVC.movie_delete_validation, None,
             None, 0, [-4], _("Help Delete validation")),
            (_("Enable auto trashcan cleanup"),
             config.MVC.movie_trashcan_clean, None, None, 0, [-5],
             _("Help Enable auto trashcan cleanup")),
            (_("How many days files may remain in trashcan"),
             config.MVC.movie_trashcan_limit, None, None, 0, [-6, -1],
             _("Help How many days files may remain in trashcan")),
            (self.section, _("LANGUAGE"), None, None, 1, [], ""),
            (_("Preferred EPG language"), config.MVC.epglang, setEPGLanguage,
             None, 1, [], _("Help Preferred EPG language")),
            (_("Enable playback auto-subtitling"), config.MVC.autosubs, None,
             None, 1, [], _("Help Enable playback auto-subtitling")),
            (_("Primary playback subtitle language"),
             config.MVC.sublang1, None, None, 1, [-1],
             _("Help Primary playback subtitle language")),
            (_("Secondary playback subtitle language"),
             config.MVC.sublang2, None, None, 1, [-2],
             _("Help Secondary playback subtitle language")),
            (_("Tertiary playback subtitle language"),
             config.MVC.sublang3, None, None, 1, [-3],
             _("Help Tertiary playback subtitle language")),
            (_("Enable playback auto-language selection"),
             config.MVC.autoaudio, None, None, 1, [],
             _("Help Enable playback auto-language selection")),
            (_("Enable playback AC3-track first"), config.MVC.autoaudio_ac3,
             None, None, 1, [-1], _("Help Enable playback AC3-track first")),
            (_("Primary playback audio language"), config.MVC.audlang1, None,
             None, 1, [-2], _("Help Primary playback audio language")),
            (_("Secondary playback audio language"), config.MVC.audlang2, None,
             None, 1, [-3], _("Help Secondary playback audio language")),
            (_("Tertiary playback audio language"), config.MVC.audlang3, None,
             None, 1, [-4], _("Help Tertiary playback audio language")),
        ]

    def createConfig(self):
        self.list = []
        for i, conf in enumerate(self.MVCConfig):
            # 0 entry text
            # 1 variable
            # 2 validation
            # 3 pressed ok
            # 4 setup level
            # 5 parent entries
            # 6 help text
            # Config item must be valid for current usage setup level
            if config.usage.setup_level.index >= conf[4]:
                # Parent entries must be true
                for parent in conf[5]:
                    if parent < 0:
                        if not self.MVCConfig[i + parent][1].value:
                            break
                    elif parent > 0:
                        if self.MVCConfig[i - parent][1].value:
                            break
                else:
                    # Loop fell through without a break
                    if conf[0] == self.section:
                        if len(self.list) > 1:
                            self.list.append(
                                getConfigListEntry("", config.MVC.fake_entry,
                                                   None, None, 0, [], ""))
                        if conf[1] == "":
                            self.list.append(
                                getConfigListEntry("<DUMMY CONFIGSECTION>", ))
                        else:
                            self.list.append(getConfigListEntry(conf[1], ))
                    else:
                        self.list.append(
                            getConfigListEntry(conf[0], conf[1], conf[2],
                                               conf[3], conf[4], conf[5],
                                               conf[6]))
        self["config"].setList(self.list)
        self.setTitle(_("Setup"))

    def loadDefaultSettings(self):
        self.session.openWithCallback(
            self.loadDefaultSettingsCB, MessageBox,
            _("Loading default settings will overwrite all settings, really load them?"
              ), MessageBox.TYPE_YESNO)

    def loadDefaultSettingsCB(self, result):
        if result:
            # Refresh is done implicitly on change
            for conf in self.MVCConfig:
                if len(conf) > 1 and conf[0] != self.section:
                    conf[1].value = conf[1].default
            self.createConfig()

    def changedEntry(self, _addNotifier=None):
        if self.reloadTimer.isActive():
            self.reloadTimer.stop()
        self.reloadTimer.start(50, True)

    def updateHelp(self):
        cur = self["config"].getCurrent()
        self["help"].text = cur and cur[6] or ""

    def dirSelected(self, res):
        if res:
            res = os.path.normpath(res)
            self["config"].getCurrent()[1].value = res

    def keyOK(self):
        try:
            current = self["config"].getCurrent()
            if current:
                current[3](current[1])
        except Exception:
            pass

    def keySaveNew(self):
        config.MVC.needsreload.value = True

        for i, entry in enumerate(self.list):
            if len(entry) > 1:
                if entry[1].isChanged():
                    if entry[2]:
                        # execute value changed -function
                        if entry[2](entry[1]):
                            # Stop exiting, user has to correct the config
                            return
                    # Check parent entries
                    for parent in entry[5]:
                        try:
                            if self.list[i + parent][2]:
                                # execute parent value changed -function
                                if self.list[i + parent][2](
                                        self.MVCConfig[i + parent][1]):
                                    # Stop exiting, user has to correct the config
                                    return
                        except Exception:
                            continue
                    entry[1].save()
        configfile.save()
        if self.needsRestartFlag:
            self.session.open(MessageBox,
                              _("Some changes require a GUI restart"),
                              MessageBox.TYPE_INFO, 10)
        self.close()

    def activateTrashcan(self, element):
        if element:
            self.enableTrashcan()

    def launchListSet(self, element):
        if element:
            self.needsRestart()

    def needsRestart(self, dummy=None):
        self.needsRestartFlag = True

    def openLocationBox(self, element):
        if element:
            path = os.path.normpath(element.value)
            self.session.openWithCallback(self.dirSelected,
                                          LocationBox,
                                          windowTitle=_("Select Location"),
                                          text=_("Select directory"),
                                          currDir=str(path) + "/",
                                          bookmarks=config.movielist.videodirs,
                                          autoAdd=False,
                                          editDir=True,
                                          inhibitDirs=[
                                              "/bin", "/boot", "/dev", "/etc",
                                              "/lib", "/proc", "/sbin", "/sys",
                                              "/var"
                                          ],
                                          minFree=100)

    def showInfo(self, dummy=None):
        self.session.open(MessageBox, "MovieCockpit" + ": Version " + VERSION,
                          MessageBox.TYPE_INFO)

    def validatePath(self, element):
        element.value = os.path.normpath(element.value)
        if not os.path.exists(element.value):
            self.session.open(
                MessageBox,
                _("Path does not exist") + ": " + str(element.value),
                MessageBox.TYPE_ERROR)
            return False
Beispiel #13
0
    def __init__(self, session, returnService=None, playerInstance=None):
        print("MVC: MovieSelection: __init__")
        global instance
        instance = self

        Screen.__init__(self, session)
        EventInfo.__init__(self)
        MountPoints.__init__(self)

        self.skinName = ["MVCSelection"]
        self.skin = Util.readFile(self.getSkin())

        self.playerInstance = playerInstance
        self.multi_select_index = None

        self.lastservice = None
        self.cursorDir = 0
        self.savedIndex = 0

        self["wait"] = Label(_("Reading directory..."))
        self["wait"].hide()

        self["space_info"] = Label("")
        self["sort_mode"] = Label("")

        self["list"] = MovieCenter()

        if returnService:
            self.returnService = returnService
            set_current_path = True
            for entry in self["list"].list:
                if entry[MOVIE_IDX_SERVICE] == self.returnService:
                    set_current_path = False
                    break
            if set_current_path:
                self.current_path = os.path.dirname(returnService.getPath())

        self["key_red"] = Button()
        self["key_green"] = Button()
        self["key_yellow"] = Button()
        self["key_blue"] = Button()

        self.cover = config.MVC.cover.value

        helptext = self.initButtons()

        self["actions"] = HelpableActionMap(
            self,
            "PluginMovieSelectionActions",
            {
                "MVCOK": (self.entrySelected, _("Play selected movie(s)")),
                "MVCEXIT": (self.abort, _("Close plugin")),
                # 				"MVCEXITpowerdown":	(self.abortAndPowerDown, 	_("Close plugin and do power button action")),
                "MVCMENU": (self.openMenu, _("Open menu")),
                "MVCINFO": (self.showEventInformation, _("Show event info")),
                "MVCINFOL":
                (self.openInfoLong,
                 _("IMDBSearch / MVC-TMDBInfo / TMDBInfo / TMBDInfo / CSFDInfo"
                   )),
                "MVCRed": (self.redFunc, helptext[0]),  # redhelptext),
                "MVCGREEN":
                (self.greenFuncShort, helptext[2]),  # greenhelptext),
                "MVCYELLOW":
                (self.yellowFunc, helptext[4]),  # yellowhelptext),
                "MVCBLUE": (self.blueFunc, helptext[6]),  # bluehelptext),
                "MVCREDL":
                (self.redFuncLong, helptext[1]),  # redlonghelptext),
                "MVCGREENL":
                (self.greenFuncLong, helptext[3]),  # greenlonghelptext),
                "MVCYELLOWL":
                (self.yellowFuncLong, helptext[5]),  # yellowlonghelptext),
                "MVCBlueL":
                (self.blueFuncLong, helptext[7]),  # bluelonghelptext),
                "MVCLeft": (self.pageUp, _("Move cursor page up")),
                "MVCRight": (self.pageDown, _("Move cursor page down")),
                "MVCUp": (self.moveUp, _("Move cursor up")),
                "MVCDown": (self.moveDown, _("Move cursor down")),
                "MVCBqtPlus":
                (self.bqtPlus,
                 _("Move cursor to the top / Move cursor x entries up / Switch Folders in Movie Home (up)"
                   )),
                "MVCBqtMnus":
                (self.bqtMnus,
                 _("Move cursor to the end / Move cursor x entries down / Switch Folders in Movie Home (down)"
                   )),
                "MVCVIDEOB":
                (self.toggleSelectionList, _("Toggle service selection")),
                "MVCVIDEOL":
                (self.resetSelectionList, _("Remove service selection")),
                "MVCAUDIO":
                (self.openMenuPlugins, _("Available plugins menu")),
                "MVCTV": (self.openTimerList, _("Open Timer List")),
                "MVCRADIO": (self.resetProgress, _("Reset movie progress")),
                "MVCTEXT": (self.multiSelect, _("Start / end multiselection")),
                "0": (self.MVCKey0, _("Movie home")),
            },
            prio=
            -3  # give them a little more priority to win over base class buttons
        )
        self["actions"].csel = self

        HelpableScreen.__init__(self)

        if self.current_path is None:
            self.current_path = config.MVC.movie_homepath.value
        self.last_current_path = None
        self.selection_list = []  # Used for file operations
        self.hide_miniTV = False

        # Key press short long handling
        #TODO We have to rework this key press handling in order to allow different user defined color key functions
        self.toggle = True  # Used for long / short key press detection: Toggle sort mode / order, Toggle selection / reset selection
        self.move = True

        self.delayTimer = eTimer()
        self.delayTimer_conn = self.delayTimer.timeout.connect(
            self.updateInfoDelayed)

        self.coverTimer = eTimer()
        self.coverTimer_conn = self.coverTimer.timeout.connect(
            self.showCoverDelayed)

        self.onShow.append(self.onDialogShow)
        self.onHide.append(self.onDialogHide)
        self["list"].onSelectionChanged.append(self.selectionChanged)
Beispiel #14
0
class TMDBInfo(Screen, TMDB, Cover, object):
	skin = Util.readFile(getSkinPath("TMDBInfo.xml"))

	def __init__(self, session, moviename, spath=None):
		print("MVC: TMDBInfo: __init__: moviename: %s, spath: %s" % (moviename, spath))
		Screen.__init__(self, session)
		self.cover_size = config.MVC.cover_size.value
		self.show_format = config.MVC.movie_show_format.value
		self.moviename = self.getMovieNameWithoutExt(moviename)
		self.search_moviename = self.getMovieNameWithoutPhrases(self.moviename)
		self.movielist = None
		self.spath = spath
		self.page = PAGE_DETAILS
		self.info = None
		self.selection = None

		self.coverTimer = eTimer()
		self.coverTimer_conn = self.coverTimer.timeout.connect(self.showCover)

		self["previewcover"] = Pixmap()
		self["nocover"] = Pixmap()
		self["previewlist"] = MenuList([])
		self["movie_name"] = Label("")
		self["contenttxt"] = ScrollLabel()
		self["runtime"] = Label(_("Runtime") + ":")
		self["runtimetxt"] = Label("")
		self["genre"] = Label(_("Genre") + ":")
		self["genretxt"] = Label("")
		self["country"] = Label(_("Production Countries") + ":")
		self["countrytxt"] = Label("")
		self["release"] = Label(_("Release Date") + ":")
		self["releasetxt"] = Label("")
		self["rating"] = Label(_("Vote") + ":")
		self["ratingtxt"] = Label("")
		self["stars"] = ProgressBar()
		self["starsbg"] = Pixmap()
		self["stars"].hide()
		self["starsbg"].hide()
		self.ratingstars = -1
		self.deleteCover(TEMP_COVER)
		self.movielist = self.getMovieList(self.search_moviename, config.MVC.cover_auto_selection.value)
		if self.movielist:
			self["previewlist"] = MenuList(self.movielist[0])
			if self.movielist[1] > 1:
				self.page = PAGE_SELECTION
			else:
				self.page = PAGE_DETAILS

			self.selection = self["previewlist"].l.getCurrentSelection()
			print("MVC: TMDBInfo: __init__: selection: " + str(self.selection))
			if self.selection:
				self.info = self.getTMDBInfo(self.selection[SELECTION_ID], self.selection[SELECTION_TYPE], config.MVC.cover_language.value)
				self.downloadCover(self.info[IDX_COVER_URL], TEMP_COVER)
		else:
			self.page = PAGE_DETAILS
			self.selection = None
			self.info = None

		self.mpath = None

		self.onLayoutFinish.append(self.layoutFinished)
		self["actions"] = HelpableActionMap(
			self,
			"TMDBInfo",
			{
				"MVCEXIT": self.exit,
				"MVCUp": self.pageUp,
				"MVCDown": self.pageDown,
				"MVCOK": self.ok,
				"MVCGreen": self.ok,
				"MVCYellow": self.save,
				"MVCRed": self.exit,
			},
			-1
		)

		self["key_red"] = Button(_("Cancel"))
		self["key_green"] = Button(_("OK"))
		self["key_blue"] = Button("")
		self["key_yellow"] = Button(_("Save"))

		self["previewlist"].onSelectionChanged.append(self.selectionChanged)

	def layoutFinished(self):
		self.setTitle(_("Movie Information TMDb"))
		self.switchPage()

	def selectionChanged(self):
		print("MVC: TMDBInfo: selectionChanged")
		if self.page == PAGE_SELECTION:
			self.deleteCover(TEMP_COVER)
			self.selection = self["previewlist"].l.getCurrentSelection()
			print("MVC: TMDBInfo: selectionChanged: selection: " + str(self.selection))
			if self.selection:
				self.info = self.getTMDBInfo(self.selection[SELECTION_ID], self.selection[SELECTION_TYPE], config.MVC.cover_language.value)
				self.downloadCover(self.info[IDX_COVER_URL], TEMP_COVER)
				self.switchPage()

	def switchPage(self):
		print("MVC: TMDBInfo: switchPage: " + str(self.page))
		if self.page == PAGE_SELECTION:
			self["movie_name"].setText(_("Search results for") + ": " + self.search_moviename)
			self["previewlist"].show()
			self["contenttxt"].hide()
			self["key_yellow"].hide()
			self["key_green"].show()
		else:
			self["previewlist"].hide()
			self["contenttxt"].show()
			self["key_yellow"].show()
			self["key_green"].hide()

		if self.info:
			self["movie_name"].setText(self.moviename)
			content, runtime, genres, countries, release, vote, _cover_url = self.info
			self["contenttxt"].setText(content)
			if runtime != "":
				self["runtimetxt"].setText(runtime + " " + _("Minutes"))
			else:
				self["runtimetxt"].setText(runtime)
			self["genretxt"].setText(genres)
			self["countrytxt"].setText(countries)
			self["releasetxt"].setText(release)
			if vote:
				self["ratingtxt"].setText(vote.replace('\n', '') + " / 10")
				self.ratingstars = int(10 * round(float(vote.replace(',', '.')), 1))
				if self.ratingstars > 0:
					self["starsbg"].show()
					self["stars"].show()
					self["stars"].setValue(self.ratingstars)
				else:
					self["starsbg"].show()
					self["stars"].hide()
			else:
				self["ratingtxt"].setText("0 / 10")
				self["starsbg"].show()
				self["stars"].hide()
		else:
			self["movie_name"].setText(_("Search results for") + ": " + self.search_moviename)
			self["contenttxt"].setText(_("Nothing was found"))
			self["contenttxt"].show()
		self.coverTimer.start(int(config.MVC.cover_delay.value), True)

	def save(self):
		print("MVC: TMDBInfo: save: self.spath: " + self.spath)
		if self.page == PAGE_DETAILS and self.spath:
			self.mpath = self.getCoverPath(self.spath)
			if fileExists(self.mpath):
				self.session.openWithCallback(
					self.saveCallback,
					MessageBox,
					_("Cover exists")
					+ "\n"
					+ _("Do you want to replace the existing cover?"),
					MessageBox.TYPE_YESNO
				)
			else:
				self.saveTempCover(self.mpath)

	def saveCallback(self, result):
		if result:
			self.saveTempCover(self.mpath)

	def saveTempCover(self, cover_path):
		print("MVC: TMDBInfo: saveTempCover: cover_path: " + cover_path)
		if fileExists(TEMP_COVER):
			try:
				shutil.copy2(TEMP_COVER, cover_path)
				self.showMsg(failed=False)
			except Exception as e:
				print('MVC: TMDBInfo: saveTempCover: exception failure:\n', str(e))
				self.showMsg(failed=True)
		else:
			self.showMsg(failed=True)

	def showMsg(self, askno=False, failed=False):
		if not askno:
			if not failed:
				msg = _("Cover saved successfully")
			else:
				msg = _("Saving cover failed")
			self.session.open(
				MessageBox,
				msg,
				MessageBox.TYPE_INFO,
				5
			)

	def ok(self):
		if self.page == PAGE_SELECTION:
			self.page = PAGE_DETAILS
			self.switchPage()

	def pageUp(self):
		if self.page == PAGE_DETAILS:
			self["contenttxt"].pageUp()
		if self.page == PAGE_SELECTION:
			self["previewlist"].up()

	def pageDown(self):
		if self.page == PAGE_DETAILS:
			self["contenttxt"].pageDown()
		if self.page == PAGE_SELECTION:
			self["previewlist"].down()

	def showCover(self):
		print("MVC: TMDBInfo: ShowCover")
		self.displayCover(TEMP_COVER, self["previewcover"], getSkinPath("img/tmdb.svg"))

	def exit(self):
		print("MVC: TMDBInfo: exit")
		if self.movielist:
			if self.page == PAGE_DETAILS and self.movielist[1] > 1:
				self["movie_name"].setText(_("Search results for") + ": " + self.moviename)
				self.page = PAGE_SELECTION
				self.switchPage()
				return

		self["previewlist"].onSelectionChanged = []
		self.close()
Beispiel #15
0
 def capacityString(cap):
     return (Util.__capacityStringDiv(cap, 1000000000000, 'PB') or
         Util.__capacityStringDiv(cap, 1000000000, 'TB') or
         Util.__capacityStringDiv(cap, 1000000, 'GB') or
         Util.__capacityStringDiv(cap, 1000, 'MB') or
         Util.__capacityStringDiv(cap, 1, 'KB'))
Beispiel #16
0
 def __readFile(self, path):
     data = None
     if os.path.isfile(path):
         data = Util.readFile(path)
     return data
Beispiel #17
0
 def sectors(self):
     try:
         return int(Util.readFile(self.sysfsPath('size')))
     except:
         return 0
Beispiel #18
0
 def capacityString(self):
     return Util.capacityString(self.size())