Beispiel #1
0
	def updateAllTagList(self):
		root = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + resolveFilename(SCOPE_HDD))
		ml = MovieList(root)
		ml.load(root, None)
		xtmp = []
		xtmp.extend(ml.tags)
		self.usedTags = xtmp

		e = [] + self.pretags
		for i in ml.tags:
			try:
				self.pretags.index(i)
			except ValueError:
				e.append(i)

		taglist = []
		for i in e:
			res = [i]
			res.append(MultiContentEntryText(pos=(5, 0), size=(500, 25), font=0, text=i))
			if self.isUsedTag(i):
				res.append(MultiContentEntryText(pos=(220, 0), size=(20, 25), font=1, text="X", color=0x00FFFF00)) #yellow
			if self.isUserTag(i):
				res.append(MultiContentEntryText(pos=(240, 0), size=(20, 25), font=1, text="X", color=0x00FF0000)) #red
			if self.isPreTag(i):
				res.append(MultiContentEntryText(pos=(260, 0), size=(20, 25), font=1, text="X", color=0x0000FF00)) #green

			taglist.append(res)

		taglist.sort()
		self["aTaglist"].l.setList(taglist)
Beispiel #2
0
	def updateAllTagList(self):
		root = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + resolveFilename(SCOPE_HDD))
		ml = MovieList(root)
		ml.load(root,None)
		xtmp = []
		xtmp.extend(ml.tags)
		self.usedTags = xtmp

		e = []+self.pretags
		for i in ml.tags:
			try:
				self.pretags.index(i)
			except ValueError:
				e.append(i)

		taglist = []
		for i in e:
				res = [ i ]
				res.append(MultiContentEntryText(pos=(5, 0), size=(500, 25), font=0, text=i))
				if self.isUsedTag(i):
					res.append(MultiContentEntryText(pos=(220, 0),size=(61, 86), font=1,text="X",color=0x00FFFF00))
				if self.isUserTag(i) :
					res.append(MultiContentEntryText(pos=(240, 0),size=(61, 86), font=1,text="X",color=0x00FF0000))#red
				if self.isPreTag(i):
					res.append(MultiContentEntryText(pos=(260, 0),size=(61, 86), font=1,text="X",color=0x000000FF))#blue

				taglist.append(res)

		taglist.sort()
		self["aTaglist"].l.setList(taglist)
Beispiel #3
0
 def __init__(self, client=False):
     self.client = client
     self._channelList = []
     from Components.MovieList import MovieList
     from Tools.Directories import resolveFilename, SCOPE_HDD
     self.movielist = MovieList(
         eServiceReference("2:0:1:0:0:0:0:0:0:0:" +
                           resolveFilename(SCOPE_HDD)))
Beispiel #4
0
	def updateAllTagList(self):
		root = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + resolveFilename(SCOPE_HDD))
		ml = MovieList(root)
		ml.load(root,None)
		xtmp = []
		xtmp.extend(ml.tags)
		self.usedTags = xtmp

		e = self.pretags + [ x for x in ml.tags if x not in self.pretags ]
		
		taglist = []
		for i in e:
			taglist.append(self.getFlags(i))
		taglist.sort()
		self["aTaglist"].setList(taglist)
Beispiel #5
0
    def __init__(self, client=False):
        self.client = client
        self._channelList = []
        from Components.MovieList import MovieList
        from Tools.Directories import resolveFilename, SCOPE_HDD

        self.movielist = MovieList(eServiceReference("2:0:1:0:0:0:0:0:0:0:" + resolveFilename(SCOPE_HDD)))
Beispiel #6
0
    def __init__(self, session, request):
        WebScreen.__init__(self, session, request)
        from Components.MovieList import MovieList
        from Tools.Directories import resolveFilename, SCOPE_HDD
        from WebComponents.Sources.Movie import Movie

        movielist = MovieList(None)
        self["MovieList"] = Movie(session, movielist, func=Movie.LIST)
        self["MovieFileDel"] = Movie(session, movielist, func=Movie.DEL)
        self["MovieFileMove"] = Movie(session, movielist, func=Movie.MOVE)
Beispiel #7
0
    def __init__(self, session, request):
        WebScreen.__init__(self, session, request)
        from Components.MovieList import MovieList
        from Tools.Directories import resolveFilename, SCOPE_HDD
        from WebComponents.Sources.Movie import Movie

        movielist = MovieList(
            eServiceReference("2:0:1:0:0:0:0:0:0:0:" +
                              resolveFilename(SCOPE_HDD)))
        self["MovieList"] = Movie(session, movielist, func=Movie.LIST)
        self["MovieFileDel"] = Movie(session, movielist, func=Movie.DEL)
        self["localip"] = RequestData(request, what=RequestData.HOST)
Beispiel #8
0
class SimpleVDRProtocol(LineReceiver):
    def __init__(self, client=False):
        self.client = client
        self._channelList = []
        from Components.MovieList import MovieList
        from Tools.Directories import resolveFilename, SCOPE_HDD
        self.movielist = MovieList(
            eServiceReference("2:0:1:0:0:0:0:0:0:0:" +
                              resolveFilename(SCOPE_HDD)))

    def getChannelList(self):
        if not self._channelList:
            from Components.Sources.ServiceList import ServiceList
            bouquet = eServiceReference(
                '1:7:1:0:0:0:0:0:0:0:FROM BOUQUET "userbouquet.favourites.tv" ORDER BY bouquet'
            )
            slist = ServiceList(bouquet, validate_commands=False)
            services = slist.getServicesAsList(format="S")
            self._channelList = services[:]
        return self._channelList

    def setChannelList(self, channelList):
        self._channelList = channelList

    channelList = property(getChannelList, setChannelList)

    def connectionMade(self):
        self.factory.addClient(self)
        now = strftime('%a %b %d %H:%M:%S %Y', localtime())
        payload = "%d %s SVDRP VideoDiskRecorder (Enigma 2-Plugin %s); %s" % (
            CODE_HELO, uname()[1], VERSION, now)
        self.sendLine(payload)

    def connectionLost(self, reason):
        self.factory.removeClient(self)

    def stop(self, *args):
        payload = "%d %s closing connection" % (CODE_BYE, uname()[1])
        self.sendLine(payload)
        self.transport.loseConnection()

    def NOT_IMPLEMENTED(self, args):
        print("[SVDRP] command not implemented.")
        payload = "%d command not implemented." % (CODE_IMP_FUNC, )
        self.sendLine(payload)

    def CHAN(self, args):
        # allowed parameters: [ + | - | <number> | <name> | <id> ]
        if args == '+':
            InfoBar.instance.zapDown()
            payload = "%d channel changed" % (CODE_OK, )
        elif args == '-':
            InfoBar.instance.zapUp()
            payload = "%d channel changed" % (CODE_OK, )
        else:
            # can be number, name or id
            payload = "%d parameter not implemented" % (CODE_IMP_PARAM, )

        self.sendLine(payload)

    def LSTC(self, args):
        if args:
            payload = "%d parameter not implemented" % (CODE_IMP_PARAM, )
            return self.sendLine(payload)
        from Components.Sources.ServiceList import ServiceList
        bouquet = eServiceReference(
            '1:7:1:0:0:0:0:0:0:0:FROM BOUQUET "userbouquet.favourites.tv" ORDER BY bouquet'
        )
        slist = ServiceList(bouquet, validate_commands=False)
        services = slist.getServicesAsList(format="SNn")
        if services:

            def getServiceInfoValue(info, sref, what):
                if info is None: return ""
                v = info.getInfo(sref.ref, what)
                if v == -2: return info.getInfoString(sref.ref, what)
                elif v == -1: return "N/A"
                return v

            def sendServiceLine(service, counter, last=False):
                if service[0][:5] == '1:64:':
                    # format for markers:  ":Name"
                    line = "%d%s:%s" % (CODE_OK, '-' if not last else ' ',
                                        service[1])
                else:
                    # <id> <full name>,<short name>;<provider>:<freq>:<parameters>:<source>:<srate>:<vpid>:<apid>:<tpid>:<conditional access>:<:sid>:<nid>:<tid>:<:rid>
                    # e.g. 5  RTL Television,RTL:12188:h:S19.2E:27500:163:104:105:0:12003:1:1089:0
                    sref = ServiceReference(service[0])
                    info = sref.info()
                    # XXX: how to get this?! o0
                    feinfo = None  #sref.ref.frontendInfo()
                    fedata = feinfo.getAll(True) if feinfo else {}
                    prov = getServiceInfoValue(info, sref,
                                               iServiceInformation.sProvider)
                    frequency = fedata.get("frequency", 0) / 1000
                    param = -1
                    source = '-1'
                    srate = -1
                    vpid = '-1'
                    apid = '-1'
                    tpid = -1
                    ca = '-1'
                    sid = -1
                    nid = -1
                    tid = -1
                    rid = -1
                    # TODO: support full format, these are only the important fields ;)
                    line = "%d%s%d %s,%s;%s:%d:%s:%s:%d:%s:%s:%d:%s:%d:%d:%d:%d" % (
                        CODE_OK, '-' if not last else ' ', counter, service[1],
                        service[2], prov, frequency, param, source, srate,
                        vpid, apid, tpid, ca, sid, nid, tid, rid)
                self.sendLine(line)

            self.channelList = [
                x[0] for x in services
            ]  # always refresh cache b/c this is what the user works with from now on
            lastItem = services.pop()
            idx = 1
            for service in services:
                sendServiceLine(service, idx)
                idx += 1
            sendServiceLine(lastItem, idx, last=True)
        else:
            payload = "%d no services found" % (CODE_ERR_LOCAL, )
            self.sendLine(payload)

    def sendTimerLine(self, timer, counter, last=False):
        # <number> <flags>:<channel id>:<YYYY-MM-DD>:<HHMM>:<HHMM>:<priority>:<lifetime>:<name>:<auxiliary>
        flags = 0
        if not timer.disabled: flags |= 1
        if timer.state == timer.StateRunning: flags |= 8
        try:
            channelid = self.channelList.index(str(timer.service_ref)) + 1
        except ValueError as e:
            # XXX: ignore timers on channels that are not in our favourite bouquet
            return False
        else:
            datestring = strftime('%Y-%m-%d', localtime(timer.begin))
            beginstring = strftime('%H%M', localtime(timer.begin))
            endstring = strftime('%H%M', localtime(timer.end))
            line = "%d%s%d %d:%d:%s:%s:%s:%d:%d:%s:%s" % (
                CODE_OK, '-' if not last else ' ', counter, flags, channelid,
                datestring, beginstring, endstring, 1, 1, timer.name,
                timer.description)
            self.sendLine(line)
            return True

    def getTimerList(self):
        import NavigationInstance
        list = []
        recordTimer = NavigationInstance.instance.RecordTimer
        list.extend(recordTimer.timer_list)
        list.extend(recordTimer.processed_timers)
        list.sort(key=attrgetter('begin'))
        return list

    def LSTT(self, args):
        list = self.getTimerList()
        lastItem = list.pop()
        idx = 1
        for timer in list:
            self.sendTimerLine(timer, idx)
            idx += 1
        if not self.sendTimerLine(lastItem, idx, last=True):
            # send error if last item failed to send, else the other end might get stuck
            payload = "%d data inconsistency error." % (CODE_ERR_LOCAL, )
            self.sendLine(payload)

    def UPDT(self, args):
        # <id> <settings>
        args = args.split(None, 1)
        if len(args) != 2:
            payload = "%d argument error" % (CODE_SYNTAX, )
            return self.sendLine(payload)

        try:
            timerId = int(args[0])
        except ValueError:
            payload = "%d argument error" % (CODE_SYNTAX, )
            return self.sendLine(payload)

        list = self.getTimerList()

        if timerId < 1:
            payload = "%d argument error" % (CODE_SYNTAX, )
            return self.sendLine(payload)

        if len(list) >= timerId: oldTimer = list[timerId - 1]
        else: oldTimer = None

        try:
            flags, channelid, datestring, beginstring, endstring, priority, lifetime, name, description = args[
                1].split(':')
            flags = int(flags)
            service_ref = ServiceReference(self.channelList[int(channelid) -
                                                            1])
            datestruct = strptime(datestring, '%Y-%m-%d')
            timestruct = strptime(beginstring, '%H%M')
            begin = mktime(
                (datestruct.tm_year, datestruct.tm_mon, datestruct.tm_mday,
                 timestruct.tm_hour, timestruct.tm_min, 0, datestruct.tm_wday,
                 datestruct.tm_yday, -1))
            timestruct = strptime(endstring, '%H%M')
            end = mktime(
                (datestruct.tm_year, datestruct.tm_mon, datestruct.tm_mday,
                 timestruct.tm_hour, timestruct.tm_min, 0, datestruct.tm_wday,
                 datestruct.tm_yday, -1))
            del datestruct, timestruct
        except ValueError as e:
            payload = "%d argument error" % (CODE_SYNTAX, )
            return self.sendLine(payload)
        except KeyError as e:
            payload = "%d argument error" % (CODE_SYNTAX, )
            return self.sendLine(payload)

        if end < begin:
            end += 86400  # Add 1 day, beware - this is evil and might not work correctly due to dst
        timer = RecordTimerEntry(service_ref,
                                 begin,
                                 end,
                                 name,
                                 description,
                                 0,
                                 disabled=flags & 1 == 0)
        if oldTimer:
            recordTimer.removeEntry(oldTimer)
            timer.justplay = oldTimer.justplay
            timer.afterEvent = oldTimer.afterEvent
            timer.dirname = oldTimer.dirname
            timer.tags = oldTimer.tags
            timer.log_entries = oldTimer.log_entries

        conflict = recordTimer.record(timer)
        if conflict is None:
            return self.sendTimerLine(timer, timerId, last=True)
        else:
            payload = "%d timer conflict detected, original timer lost." % (
                CODE_ERR_LOCAL, )
            return self.sendLine(payload)

    def NEWT(self, args):
        self.UPDT("999999999 " + args)

    def MODT(self, args):
        # <id> on | off | <settings>
        args = args.split(None, 1)
        if len(args) != 2:
            payload = "%d argument error" % (CODE_SYNTAX, )
            return self.sendLine(payload)

        if args[1] in ('on', 'off'):
            try:
                timerId = int(args[0])
            except ValueError:
                payload = "%d argument error" % (CODE_SYNTAX, )
                return self.sendLine(payload)

            list = self.getTimerList()

            if timerId < 1 or len(list) < timerId:
                payload = "%d argument error" % (CODE_SYNTAX, )
                return self.sendLine(payload)

            timer = list[timerId - 1]
            disable = args[1] == 'off'
            if disable and timer.isRunning():
                payload = "%d timer is running, not disabling." % (
                    CODE_ERR_LOCAL, )
                return self.sendLine(payload)
            else:
                if timer.disabled and not disable:
                    timer.enable()
                    tsc = TimerSanityCheck(recordTimer.timer_list, timer)
                    if not timersanitycheck.check():
                        timer.disable()
                        payload = "%d timer conflict detected, aborting." % (
                            CODE_ERR_LOCAL, )
                        return self.sendLine(payload)
                    else:
                        if timersanitycheck.doubleCheck(): timer.disable()
                elif not timer.disabled and disable:
                    timer.disable()
                recordTimer.timeChanged(timer)
                sef.sendTimerLine(timer, timerId, last=True)
        else:
            self.UPDT(' '.join(args))

    def DELT(self, args):
        try:
            timerId = int(args)
        except ValueError:
            payload = "%d argument error" % (CODE_SYNTAX, )
            return self.sendLine(payload)

        list = self.getTimerList()

        if timerId < 1 or len(list) < timerId:
            payload = "%d argument error" % (CODE_SYNTAX, )
            return self.sendLine(payload)

        timer = list[timerId - 1]
        recordTimer.removeEntry(timer)
        payload = '%d Timer "%d" deleted' % (CODE_OK, timerId)
        self.sendLine(payload)

    def MESG(self, data):
        if not data:
            payload = "%d parameter not implemented" % (CODE_IMP_PARAM, )
            return self.sendLine(payload)

        Notifications.AddNotificationWithID(
            NOTIFICATIONID,
            MessageBox,
            text=data,
            type=MessageBox.TYPE_INFO,
            timeout=5,
            close_on_any_key=True,
        )
        payload = "%d Message queued" % (CODE_OK, )
        self.sendLine(payload)

    def VOLU(self, args):
        volctrl = eDVBVolumecontrol.getInstance()
        if args == "mute":
            from Components.VolumeControl import VolumeControl
            VolumeControl.instance.volMute()
        elif args == "+":
            from Components.VolumeControl import VolumeControl
            VolumeControl.instance.volUp()
        elif args == "-":
            from Components.VolumeControl import VolumeControl
            VolumeControl.instance.volDown()
        elif args:
            try:
                num = int(args) / 2.55
            except ValueError:
                payload = "%d %s" % (CODE_SYNTAX, str(e).replace(
                    '\n', ' ').replace('\r', ''))
                return self.sendLine(payload)
            else:
                volctr.setVolume(num, num)

        if volctrl.isMuted():
            payload = "%d Audio is mute" % (CODE_OK, )
        else:
            payload = "%d Audio volume is %d." % (CODE_OK,
                                                  volctrl.getVolume() * 2.55)
        self.sendLine(payload)

    def HELP(self, args):
        if not len(args) == 2:
            payload = "%d data inconsistency error." % (CODE_ERR_LOCAL, )
            return self.sendLine(payload)
        funcs, args = args
        if not args:
            funcnames = sorted(funcs.keys())
            payload = "%d-This is Enigma2 VDR-Plugin version %s" % (CODE_HELP,
                                                                    VERSION)
            self.sendLine(payload)
            payload = "%d-Topics:" % (CODE_HELP, )
            x = 5
            for func in funcnames:
                if x == 5:
                    self.sendLine(payload)
                    payload = "%d-    %s" % (CODE_HELP, func)
                    x = 1
                else:
                    payload += "      %s" % (func, )
                    x += 1
            self.sendLine(payload)
            payload = "%d-To report bugs in the implementation send email to" % (
                CODE_HELP, )
            self.sendLine(payload)
            payload = "%d-    svdrp AT ritzmo DOT de" % (CODE_HELP, )
            self.sendLine(payload)
            payload = "%d End of HELP info" % (CODE_HELP, )
            self.sendLine(payload)
        else:
            payload = "%d parameter not implemented" % (CODE_IMP_PARAM, )
            return self.sendLine(payload)

    def LSTR(self, args):
        if args:
            payload = "%d parameter not implemented" % (CODE_IMP_PARAM, )
            return self.sendLine(payload)

        self.movielist.reload()

        def sendMovieLine(sref, info, begin, counter, last=False):
            # <number> <date> <begin> <name>
            ctime = info.getInfo(
                serviceref, iServiceInformation.sTimeCreate
            )  # XXX: difference to begin? just copied this from webif ;-)
            datestring = strftime('%d.%m.%y', localtime(ctime))
            beginstring = strftime('%H:%M', localtime(ctime))
            servicename = ServiceReference(sref).getServiceName().replace(
                '\xc2\x86', '').replace('\xc2\x87', '')
            line = "%d%s%d %s %s %s" % (CODE_OK, '-' if not last else ' ',
                                        counter, datestring, beginstring,
                                        servicename)
            self.sendLine(line)

        list = self.movielist.list[:]
        lastItem = list.pop()
        idx = 1
        for serviceref, info, begin, unknown in list:
            sendMovieLine(serviceref, info, begin, idx)
            idx += 1
        sendMovieLine(lastItem[0], lastItem[1], lastItem[2], idx, last=True)

    def DELR(self, args):
        try:
            movieId = int(args)
        except ValueError:
            payload = "%d argument error" % (CODE_SYNTAX, )
            return self.sendLine(payload)

        sref = self.movielist.list[movieId - 1][0]
        serviceHandler = eServiceCenter.getInstance()
        offline = serviceHandler.offlineOperations(sref)

        if offline is not None:
            if not offline.deleteFromDisk(0):
                payload = '%d Movie "%d" deleted' % (CODE_OK, movieId)
                return self.sendLine(payload)

        payload = "%d data inconsistency error." % (CODE_ERR_LOCAL, )
        self.sendLine(payload)

    def LSTE(self, args):
        args = args.split()
        first = args and args.pop(0)
        #TODO: find out format of "at <time>"
        if not first or first in ('now', 'next',
                                  'at') or args and args[1] == "at":
            # XXX: "parameter not implemented" might be weird to say in case of no parameters, but who cares :-)
            payload = "%d parameter not implemented" % (CODE_IMP_PARAM, )
            return self.sendLine(payload)
        try:
            channelId = int(first) - 1
            service = self.channelList[channelId]
        except ValueError:
            # XXX: add support for sref
            payload = "%d parameter not implemented" % (CODE_IMP_PARAM, )
            return self.sendLine(payload)

        # handle additional parametes "now" and "next"
        type = 0
        time = -1
        endtime = -1
        options = "IBDTSERN"
        if args:
            options = "IBDTSERNX"
            if args[0] == "now":
                type = 0
                endtime = None
            elif args[0] == "next":
                type = 1
                endtime = None

        # fetch data
        epgcache = eEPGCache.getInstance()
        if endtime is None:
            params = (service, type, time)
        else:
            params = (service, type, time, endtime)
        events = epgcache.lookupEvent([options, params])

        # process data
        def sendEventLine(eit, begin, duration, title, description, extended,
                          sref, sname):
            payload = "%d-E %d %d %d 0" % (CODE_EPG, eit, begin, duration)
            self.sendLine(payload)
            payload = "%d-T %s" % (CODE_EPG, title)
            self.sendLine(payload)
            payload = "%d-S %s" % (CODE_EPG, description)
            self.sendLine(payload)
            payload = "%d-D %s" % (CODE_EPG, extended.replace('\xc2\x8a', '|'))
            self.sendLine(payload)
            payload = "%d-e" % (CODE_EPG, )
            self.sendLine(payload)

        lastItem = events.pop()
        payload = "%d-C %s %s" % (CODE_EPG, lastItem[-2], lastItem[-1])
        self.sendLine(payload)
        for event in events:
            sendEventLine(*event)
        sendEventLine(*lastItem)
        payload = "%d-c" % (CODE_EPG, )
        self.sendLine(payload)
        payload = "%d End of EPG data" % (CODE_EPG, )
        self.sendLine(payload)

    def lineReceived(self, data):
        if self.client or not self.transport or not data:
            return

        print("[SVDRP] incoming message:", data)
        list = data.split(' ', 1)
        command = list.pop(0).upper()
        args = list[0] if list else ''

        # still possible: grab, (partially) hitk, (theoretically) movc, next? (dunno what this does), play, stat and completion of existing commands
        funcs = {
            'CHAN': self.CHAN,
            'DELR': self.DELR,
            'DELT': self.DELT,
            'HELP': self.HELP,
            'LSTC': self.LSTC,
            'LSTE': self.LSTE,
            'LSTT': self.LSTT,
            'LSTR': self.LSTR,
            'MESG': self.MESG,
            'MODT': self.MODT,
            'NEWT': self.NEWT,
            'UPDT': self.UPDT,
            'QUIT': self.stop,
            'VOLU': self.VOLU,
        }
        if command == "HELP":
            args = (funcs, args)
        call = funcs.get(command, self.NOT_IMPLEMENTED)

        try:
            call(args)
        except Exception as e:
            import traceback, sys
            traceback.print_exc(file=sys.stdout)
            payload = "%d exception occured: %s" % (CODE_ERR, str(e).replace(
                '\n', ' ').replace('\r', ''))
            self.sendLine(payload)
Beispiel #9
0
def getMovieSearchList(rargs=None, locations=None):
    movieliste = []
    tag = None
    directory = None
    fields = None
    short = None
    extended = None
    searchstr = None

    if rargs:
        searchstr = getUrlArg2(rargs, "find")
        short = getUrlArg2(rargs, "short")
        extended = getUrlArg2(rargs, "extended")

    s = {'title': str(searchstr)}
    if short is not None:
        s['shortDesc'] = str(searchstr)
    if extended is not None:
        s['extDesc'] = str(searchstr)

    movielist = MovieList(None)
    vdir_list = []
    for x in moviedb.searchContent(s, 'ref', query_type="OR",
                                   exactmatch=False):
        vdir_list.append(eServiceReference(x[0]))
    root = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + "/")
    movielist.load(root, None)
    movielist.reload(root=None, vdir=5, vdir_list=vdir_list)

    for (serviceref, info, begin, unknown) in movielist.list:
        if serviceref.flags & eServiceReference.mustDescent:
            continue

        length_minutes = 0
        txtdesc = ""
        filename = '/'.join(serviceref.toString().split("/")[1:])
        filename = '/' + filename
        name, ext = os.path.splitext(filename)

        sourceRef = ServiceReference(
            info.getInfoString(serviceref, iServiceInformation.sServiceref))
        rtime = info.getInfo(serviceref, iServiceInformation.sTimeCreate)

        movie = {
            'filename':
            filename,
            'filename_stripped':
            filename.split("/")[-1],
            'serviceref':
            serviceref.toString(),
            'length':
            "?:??",
            'lastseen':
            0,
            'filesize_readable':
            '',
            'recordingtime':
            rtime,
            'begintime':
            'undefined',
            'eventname':
            ServiceReference(serviceref).getServiceName().replace(
                '\xc2\x86', '').replace('\xc2\x87', ''),
            'servicename':
            sourceRef.getServiceName().replace('\xc2\x86',
                                               '').replace('\xc2\x87', ''),
            'tags':
            info.getInfoString(serviceref, iServiceInformation.sTags),
            'fullname':
            serviceref.toString(),
        }

        if rtime > 0:
            movie['begintime'] = FuzzyTime2(rtime)

        try:
            length_minutes = info.getLength(serviceref)
        except:  # noqa: E722
            pass

        if length_minutes:
            movie['length'] = "%d:%02d" % (length_minutes / 60,
                                           length_minutes % 60)
            #  if fields is None or 'pos' in fields:
            #  	movie['lastseen'] = getPosition(filename + '.cuts', length_minutes)

        if fields is None or 'desc' in fields:
            txtfile = name + '.txt'
            if ext.lower() != '.ts' and os.path.isfile(txtfile):
                with open(txtfile, "rb") as handle:
                    txtdesc = six.ensure_str(b''.join(handle.readlines()))

            event = info.getEvent(serviceref)
            extended_description = event and event.getExtendedDescription(
            ) or ""
            if extended_description == '' and txtdesc != '':
                extended_description = txtdesc
            movie['descriptionExtended'] = ConvertDesc(extended_description)
            desc = info.getInfoString(serviceref,
                                      iServiceInformation.sDescription)
            movie['description'] = ConvertDesc(desc)

        if fields is None or 'size' in fields:
            size = 0
            sz = ''

            try:
                size = os.stat(filename).st_size
                if size > 1073741824:
                    sz = "%.2f %s" % ((size / 1073741824.), _("GB"))
                elif size > 1048576:
                    sz = "%.2f %s" % ((size / 1048576.), _("MB"))
                elif size > 1024:
                    sz = "%.2f %s" % ((size / 1024.), _("kB"))
            except:  # noqa: E722
                pass

            movie['filesize'] = size
            movie['filesize_readable'] = sz

        movieliste.append(movie)

    return {"movies": movieliste, "locations": []}
Beispiel #10
0
def getMovieList(rargs=None, locations=None):
    movieliste = []
    tag = None
    directory = None
    fields = None
    bookmarklist = []

    if rargs:
        tag = getUrlArg2(rargs, "tag")
        directory = getUrlArg2(rargs, "dirname")
        fields = getUrlArg2(rargs, "fields")

    if directory is None:
        directory = defaultMoviePath()
    else:
        if not PY3:
            try:
                directory.decode('utf-8')
            except UnicodeDecodeError:
                try:
                    directory = directory.decode("cp1252").encode("utf-8")
                except UnicodeDecodeError:
                    directory = directory.decode("iso-8859-1").encode("utf-8")

    if not directory:
        directory = MOVIE_LIST_ROOT_FALLBACK

    if directory[-1] != "/":
        directory += "/"

    if not os.path.isdir(directory):
        return {
            "movies": [],
            "locations": [],
            "bookmarks": [],
            "directory": [],
        }

    root = eServiceReference(MOVIE_LIST_SREF_ROOT + directory)

    for item in sorted(os.listdir(directory)):
        abs_p = os.path.join(directory, item)
        if os.path.isdir(abs_p):
            bookmarklist.append(item)

    folders = [root]
    brecursive = False
    if rargs and b"recursive" in list(rargs.keys()):
        brecursive = True
        dirs = []
        locations = []
        if PY3:
            from glob import glob
            for subdirpath in glob(directory + "**/", recursive=True):
                locations.append(subdirpath)
                subdirpath = subdirpath[len(directory):]
                dirs.append(subdirpath)
        else:
            # FIXME SLOW!!!
            for subdirpath in [x[0] for x in os.walk(directory)]:
                locations.append(subdirpath)
                subdirpath = subdirpath[len(directory):]
                dirs.append(subdirpath)

        for f in sorted(dirs):
            if f != '':
                if f[-1] != "/":
                    f += "/"
                ff = eServiceReference(MOVIE_LIST_SREF_ROOT + directory + f)
                folders.append(ff)
    else:
        # get all locations
        if locations is not None:
            folders = []

            for f in locations:
                if f[-1] != "/":
                    f += "/"
                ff = eServiceReference(MOVIE_LIST_SREF_ROOT + f)
                folders.append(ff)

    if config.OpenWebif.parentalenabled.value:
        dir_is_protected = checkParentalProtection(directory)
    else:
        dir_is_protected = False

    if not dir_is_protected:
        movielist = MovieList(None)
        for root in folders:
            if tag is not None:
                movielist.load(root=root, filter_tags=[tag])
            else:
                movielist.load(root=root, filter_tags=None)

            for (serviceref, info, begin, unknown) in movielist.list:
                if serviceref.flags & eServiceReference.mustDescent:
                    continue

                # BAD fix
                _serviceref = serviceref.toString().replace('%25', '%')
                length_minutes = 0
                txtdesc = ""
                filename = '/'.join(_serviceref.split("/")[1:])
                filename = '/' + filename
                name, ext = os.path.splitext(filename)

                sourceRef = ServiceReference(
                    info.getInfoString(serviceref,
                                       iServiceInformation.sServiceref))
                rtime = info.getInfo(serviceref,
                                     iServiceInformation.sTimeCreate)

                movie = {
                    'filename':
                    filename,
                    'filename_stripped':
                    filename.split("/")[-1],
                    'serviceref':
                    _serviceref,
                    'length':
                    "?:??",
                    'lastseen':
                    0,
                    'filesize_readable':
                    '',
                    'recordingtime':
                    rtime,
                    'begintime':
                    'undefined',
                    'eventname':
                    ServiceReference(serviceref).getServiceName().replace(
                        '\xc2\x86', '').replace('\xc2\x87', ''),
                    'servicename':
                    sourceRef.getServiceName().replace('\xc2\x86', '').replace(
                        '\xc2\x87', ''),
                    'tags':
                    info.getInfoString(serviceref, iServiceInformation.sTags),
                    'fullname':
                    _serviceref,
                }

                if rtime > 0:
                    movie['begintime'] = FuzzyTime2(rtime)

                try:
                    length_minutes = info.getLength(serviceref)
                except:  # noqa: E722
                    pass

                if length_minutes:
                    movie['length'] = "%d:%02d" % (length_minutes / 60,
                                                   length_minutes % 60)
                    if fields is None or 'pos' in fields:
                        movie['lastseen'] = _moviePlayState(
                            filename + '.cuts', serviceref,
                            length_minutes) or 0

                if fields is None or 'desc' in fields:
                    txtfile = name + '.txt'
                    if ext.lower() != '.ts' and os.path.isfile(txtfile):
                        with open(txtfile, "rb") as handle:
                            txtdesc = six.ensure_str(b''.join(
                                handle.readlines()))

                    event = info.getEvent(serviceref)
                    extended_description = event and event.getExtendedDescription(
                    ) or ""
                    if extended_description == '' and txtdesc != '':
                        extended_description = txtdesc
                    movie['descriptionExtended'] = ConvertDesc(
                        extended_description)

                    desc = info.getInfoString(serviceref,
                                              iServiceInformation.sDescription)
                    movie['description'] = ConvertDesc(desc)

                if fields is None or 'size' in fields:
                    size = 0
                    sz = ''

                    try:
                        size = os.stat(filename).st_size
                        if size > 1073741824:
                            sz = "%.2f %s" % ((size / 1073741824.), _("GB"))
                        elif size > 1048576:
                            sz = "%.2f %s" % ((size / 1048576.), _("MB"))
                        elif size > 1024:
                            sz = "%.2f %s" % ((size / 1024.), _("kB"))
                    except:  # noqa: E722
                        pass

                    movie['filesize'] = size
                    movie['filesize_readable'] = sz

                movieliste.append(movie)


#		del movielist

    if locations is None:
        return {
            "movies": movieliste,
            "bookmarks": bookmarklist,
            "directory": directory,
            "recursive": brecursive
        }

    if brecursive:
        return {
            "movies": movieliste,
            "locations": locations,
            "directory": directory,
            "bookmarks": bookmarklist,
            "recursive": brecursive
        }
    else:
        return {
            "movies": movieliste,
            "locations": locations,
            "recursive": brecursive
        }
Beispiel #11
0
def getMovieList(directory=None, tag=None, rargs=None, locations=None):
    movieliste = []

    if directory is None:
        directory = MovieSelection.defaultMoviePath()
    if not directory:
        directory = "/media/"
    elif directory[-1] != "/":
        directory += "/"

    root = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + directory)

    bookmarklist = [
        x for x in listdir(directory)
        if (x[0] != '.' and (isdir(join(directory, x)) or (
            islink(join(directory, x)) and exists(join(directory, x)))))
    ]
    bookmarklist.sort()

    folders = []
    folders.append(root)
    if rargs and "recursive" in rargs.keys():
        for f in bookmarklist:
            if f[-1] != "/":
                f += "/"
            ff = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + directory + f)
            folders.append(ff)

    # get all locations
    if locations is not None:
        folders = []
        for f in locations:
            if f[-1] != "/":
                f += "/"
            ff = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + f)
            folders.append(ff)

    if config.ModernWebif.parentalenabled.value:
        dir_is_protected = checkParentalProtection(directory)
    else:
        dir_is_protected = False

    import os

    if not dir_is_protected:
        for root in folders:
            movielist = MovieList(None)
            movielist.load(root, None)

            if tag != None:
                movielist.reload(root=root, filter_tags=[tag])
            #??? loadLength = True

            for (serviceref, info, begin, unknown) in movielist.list:
                if serviceref.flags & eServiceReference.mustDescent:
                    continue

                rtime = info.getInfo(serviceref,
                                     iServiceInformation.sTimeCreate)

                if rtime > 0:
                    t = FuzzyTime(rtime)
                    begin_string = t[0] + ", " + t[1]
                else:
                    begin_string = "undefined"

                try:
                    Len = info.getLength(serviceref)
                except:
                    Len = None

                filename = '/'.join(serviceref.toString().split("/")[1:])
                filename = '/' + filename
                pos = getPosition(filename + '.cuts', Len)

                # get txt
                name, ext = os.path.splitext(filename)
                ext = ext.lower()

                txtdesc = ""

                if ext != 'ts':
                    txtfile = name + '.txt'
                    if fileExists(txtfile):
                        txtlines = open(txtfile).readlines()
                        txtdesc = ""
                        for line in txtlines:
                            txtdesc += line

                if Len > 0:
                    Len = "%d:%02d" % (Len / 60, Len % 60)
                else:
                    Len = "?:??"

                sourceERef = info.getInfoString(
                    serviceref, iServiceInformation.sServiceref)
                sourceRef = ServiceReference(sourceERef)
                event = info.getEvent(serviceref)
                ext = event and event.getExtendedDescription() or ""

                if ext == '' and txtdesc != '':
                    ext = txtdesc

                servicename = ServiceReference(
                    serviceref).getServiceName().replace('\xc2\x86',
                                                         '').replace(
                                                             '\xc2\x87', '')
                movie = {}
                movie['filename'] = filename
                movie['filename_stripped'] = filename.split("/")[-1]
                movie['eventname'] = servicename
                movie['description'] = info.getInfoString(
                    serviceref, iServiceInformation.sDescription)
                movie['begintime'] = begin_string
                movie['serviceref'] = serviceref.toString()
                movie['length'] = Len
                movie['tags'] = info.getInfoString(serviceref,
                                                   iServiceInformation.sTags)
                filename = filename.replace("'", "\'").replace("%", "\%")
                try:
                    movie['filesize'] = os_stat(filename).st_size
                except:
                    movie['filesize'] = 0
                movie['fullname'] = serviceref.toString()
                movie['descriptionExtended'] = ext
                movie['servicename'] = sourceRef.getServiceName().replace(
                    '\xc2\x86', '').replace('\xc2\x87', '')
                movie['recordingtime'] = rtime
                movie['lastseen'] = pos
                movieliste.append(movie)

    if locations == None:
        ml = {
            "movies": movieliste,
            "bookmarks": bookmarklist,
            "directory": directory
        }
    else:
        ml = {"movies": movieliste, "locations": locations}
    return ml
def getMovieList(rargs=None, locations=None):
    movieliste = []

    tag = None
    if rargs and "tag" in rargs.keys():
        tag = rargs["tag"][0]

    directory = None
    if rargs and "dirname" in rargs.keys():
        directory = rargs["dirname"][0]

    fields = None
    if rargs and "fields" in rargs.keys():
        fields = rargs["fields"][0]
    else:
        fields = 'pos,size,desc'

    if directory is None:
        directory = MovieSelection.defaultMoviePath()
    else:
        directory = unquote(directory)
        try:
            directory.decode('utf-8')
        except UnicodeDecodeError:
            try:
                directory = directory.decode("cp1252").encode("utf-8")
            except UnicodeDecodeError:
                directory = directory.decode("iso-8859-1").encode("utf-8")

    if not directory:
        directory = "/media/"
    elif directory[-1] != "/":
        directory += "/"

    root = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + directory)

    bookmarklist = [
        x for x in listdir(directory)
        if (x[0] != '.' and (isdir(join(directory, x)) or (
            islink(join(directory, x)) and exists(join(directory, x)))))
    ]
    bookmarklist.sort()

    folders = []
    folders.append(root)
    if rargs and "recursive" in rargs.keys():
        for f in bookmarklist:
            if f[-1] != "/":
                f += "/"
            ff = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + directory + f)
            folders.append(ff)

    # get all locations
    if locations is not None:
        folders = []
        for f in locations:
            if f[-1] != "/":
                f += "/"
            ff = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + f)
            folders.append(ff)

    if config.OpenWebif.parentalenabled.value:
        dir_is_protected = checkParentalProtection(directory)
    else:
        dir_is_protected = False

    import os

    if not dir_is_protected:
        for root in folders:
            movielist = MovieList(None)
            movielist.load(root, None)

            if tag != None:
                movielist.reload(root=root, filter_tags=[tag])
            #??? loadLength = True

            for (serviceref, info, begin, unknown) in movielist.list:
                if serviceref.flags & eServiceReference.mustDescent:
                    continue

                rtime = info.getInfo(serviceref,
                                     iServiceInformation.sTimeCreate)

                if rtime > 0:
                    t = FuzzyTime(rtime)
                    begin_string = t[0] + ", " + t[1]
                else:
                    begin_string = "undefined"

                try:
                    Len = info.getLength(serviceref)
                except:
                    Len = None

                filename = '/'.join(serviceref.toString().split("/")[1:])
                filename = '/' + filename
                if 'pos' in fields:
                    pos = getPosition(filename + '.cuts', Len)

                # get txt
                name, ext = os.path.splitext(filename)
                ext = ext.lower()

                txtdesc = ""

                if 'desc' in fields and ext != 'ts':
                    txtfile = name + '.txt'
                    if fileExists(txtfile):
                        txtlines = open(txtfile).readlines()
                        txtdesc = ""
                        for line in txtlines:
                            txtdesc += line

                if Len > 0:
                    Len = "%d:%02d" % (Len / 60, Len % 60)
                else:
                    Len = "?:??"

                sourceERef = info.getInfoString(
                    serviceref, iServiceInformation.sServiceref)
                sourceRef = ServiceReference(sourceERef)
                if 'desc' in fields:
                    event = info.getEvent(serviceref)
                    ext = event and event.getExtendedDescription() or ""
                    if ext == '' and txtdesc != '':
                        ext = txtdesc

                if 'desc' in fields:
                    desc = info.getInfoString(serviceref,
                                              iServiceInformation.sDescription)
                servicename = ServiceReference(
                    serviceref).getServiceName().replace('\xc2\x86',
                                                         '').replace(
                                                             '\xc2\x87', '')
                movie = {}
                movie['filename'] = filename
                movie['filename_stripped'] = filename.split("/")[-1]
                movie['eventname'] = servicename
                if 'desc' in fields:
                    movie['description'] = unicode(desc,
                                                   'utf_8',
                                                   errors='ignore').encode(
                                                       'utf_8', 'ignore')
                movie['begintime'] = begin_string
                movie['serviceref'] = serviceref.toString()
                movie['length'] = Len
                movie['tags'] = info.getInfoString(serviceref,
                                                   iServiceInformation.sTags)
                movie['filesize_readable'] = ''
                if 'size' in fields:
                    filename = filename.replace("'", "\'").replace("%", "\%")
                    size = 0
                    try:
                        size = os_stat(filename).st_size
                        sz = ''
                        if size > 1073741824:
                            sz = "%.2f %s" % ((size / 1073741824.), _("GB"))
                        elif size > 1048576:
                            sz = "%.2f %s" % ((size / 1048576.), _("MB"))
                        elif size > 1024:
                            sz = "%.2f %s" % ((size / 1024.), _("kB"))
                    except:
                        size = 0
                    movie['filesize'] = size
                    movie['filesize_readable'] = sz
                movie['fullname'] = serviceref.toString()
                if 'desc' in fields:
                    movie['descriptionExtended'] = unicode(
                        ext, 'utf_8',
                        errors='ignore').encode('utf_8', 'ignore')
                movie['servicename'] = sourceRef.getServiceName().replace(
                    '\xc2\x86', '').replace('\xc2\x87', '')
                movie['recordingtime'] = rtime
                if 'pos' in fields:
                    movie['lastseen'] = pos
                movieliste.append(movie)

    if locations == None:
        ml = {
            "movies": movieliste,
            "bookmarks": bookmarklist,
            "directory": directory
        }
    else:
        ml = {"movies": movieliste, "locations": locations}
    return ml
def getMovieList(directory=None, tag=None, rargs=None):
    movieliste = []

    if directory == None:
        directory = config.usage.default_path.value

    if directory[-1] != "/":
        directory += "/"

    root = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + directory)

    bookmarklist = [
        x for x in walk(directory).next()[1]
        if (x[0] != '.' and not islink(directory + '/' + x))
    ]
    bookmarklist.sort()

    folders = []
    folders.append(root)
    if rargs and "recursive" in rargs.keys():
        for f in bookmarklist:
            if f[-1] != "/":
                f += "/"
            ff = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + directory + f)
            folders.append(ff)

    #??? tagfilter = []

    for root in folders:

        movielist = MovieList(None)
        movielist.load(root, None)

        if tag != None:
            movielist.reload(root=root, filter_tags=[tag])
        #??? loadLength = True

        for (serviceref, info, begin, unknown) in movielist.list:
            if serviceref.flags & eServiceReference.mustDescent:
                continue

            rtime = info.getInfo(serviceref, iServiceInformation.sTimeCreate)

            if rtime > 0:
                t = FuzzyTime(rtime)
                begin_string = t[0] + ", " + t[1]
            else:
                begin_string = "undefined"

            try:
                Len = info.getLength(serviceref)
            except:
                Len = None

            if Len > 0:
                Len = "%d:%02d" % (Len / 60, Len % 60)
            else:
                Len = "?:??"

            sourceERef = info.getInfoString(serviceref,
                                            iServiceInformation.sServiceref)
            sourceRef = ServiceReference(sourceERef)

            event = info.getEvent(serviceref)
            ext = event and event.getExtendedDescription() or ""

            filename = '/'.join(serviceref.toString().split("/")[1:])
            servicename = ServiceReference(
                serviceref).getServiceName().replace('\xc2\x86', '').replace(
                    '\xc2\x87', '')
            movie = {}
            filename = '/' + filename
            movie['filename'] = filename
            movie['filename_stripped'] = filename.split("/")[-1]
            movie['eventname'] = servicename
            movie['description'] = info.getInfoString(
                serviceref, iServiceInformation.sDescription)
            movie['begintime'] = begin_string
            movie['serviceref'] = serviceref.toString()
            movie['length'] = Len
            movie['tags'] = info.getInfoString(serviceref,
                                               iServiceInformation.sTags)
            filename = filename.replace("'", "\'").replace("%", "\%")
            try:
                movie['filesize'] = os_stat(filename).st_size
            except:
                movie['filesize'] = 0
            movie['fullname'] = serviceref.toString()
            movie['descriptionExtended'] = ext
            movie['servicename'] = sourceRef.getServiceName().replace(
                '\xc2\x86', '').replace('\xc2\x87', '')
            movie['recordingtime'] = rtime

            movieliste.append(movie)

    ml = {
        "movies": movieliste,
        "bookmarks": bookmarklist,
        "directory": directory
    }

    if rargs and "zip" in rargs.keys():
        filename = rargs["zip"][0]
        import os
        if not os.path.exists(os.path.dirname(filename)):
            return {"result": False, "message": "zip file path not exist"}
        try:
            import json
            fd = open(filename, 'wb')
            #todo create zip using api
            #fd = gzip.GzipFile(filename=filename, mode='wb', compresslevel=9)
            fd.write(json.dumps(ml))
            fd.close()
            try:
                os.remove('%s.gz' % filename)
            except OSError:
                pass
            os.system('gzip %s' % filename)
        except (IOError, os.error), why:
            return {
                "result": False,
                "message": "create movielist zip error:%s" % why
            }
        return {"result": True, "message": "create movielist zip success"}
Beispiel #14
0
def getMovieList(directory=None, tag=None, rargs=None, locations=None):
	movieliste = []

	if directory is None:
		directory = MovieSelection.defaultMoviePath()
	if not directory:
		directory = "/media/"
	elif directory[-1] != "/":
		directory += "/"

	root = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + directory)

	bookmarklist=[x for x in listdir(directory) if (x[0] != '.' and (isdir(join(directory, x)) or (islink(join(directory, x)) and exists(join(directory, x)))))]
	bookmarklist.sort()

	folders = []
	folders.append(root)
	if rargs and "recursive" in rargs.keys():
		for f in bookmarklist:
			if f[-1] != "/":
				f += "/"
			ff = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + directory + f)
			folders.append(ff)

	# get all locations
	if locations is not None:
		folders = []
		for f in locations:
			if f[-1] != "/":
				f += "/"
			ff = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + f)
			folders.append(ff)

	if config.ModernWebif.parentalenabled.value:
		dir_is_protected = checkParentalProtection(directory)
	else:
		dir_is_protected = False

	import os

	if not dir_is_protected:
		for root in folders:
			movielist = MovieList(None)
			movielist.load(root, None)

			if tag != None:
				movielist.reload(root=root, filter_tags=[tag])
			#??? loadLength = True

			for (serviceref, info, begin, unknown) in movielist.list:
				if serviceref.flags & eServiceReference.mustDescent:
					continue

				rtime = info.getInfo(serviceref, iServiceInformation.sTimeCreate)

				if rtime > 0:
					t = FuzzyTime(rtime)
					begin_string = t[0] + ", " + t[1]
				else:
					begin_string = "undefined"

				try:
					Len = info.getLength(serviceref)
				except:
					Len = None

				filename = '/'.join(serviceref.toString().split("/")[1:])
				filename = '/'+filename
				pos = getPosition(filename + '.cuts', Len)
				
				# get txt
				name, ext = os.path.splitext(filename)
				ext = ext.lower()
				
				txtdesc = ""
				
				if ext != 'ts':
					txtfile = name + '.txt'
					if fileExists(txtfile):
						txtlines = open(txtfile).readlines()
						txtdesc = ""
						for line in txtlines:
							txtdesc += line

				if Len > 0:
					Len = "%d:%02d" % (Len / 60, Len % 60)
				else:
					Len = "?:??"

				sourceERef = info.getInfoString(serviceref, iServiceInformation.sServiceref)
				sourceRef = ServiceReference(sourceERef)
				event = info.getEvent(serviceref)
				ext = event and event.getExtendedDescription() or ""

				if ext == '' and txtdesc != '':
					ext = txtdesc

				servicename = ServiceReference(serviceref).getServiceName().replace('\xc2\x86', '').replace('\xc2\x87', '')
				movie = {}
				movie['filename'] = filename
				movie['filename_stripped'] = filename.split("/")[-1]
				movie['eventname'] = servicename
				movie['description'] = info.getInfoString(serviceref, iServiceInformation.sDescription)
				movie['begintime'] = begin_string
				movie['serviceref'] = serviceref.toString()
				movie['length'] = Len
				movie['tags'] = info.getInfoString(serviceref, iServiceInformation.sTags)
				filename = filename.replace("'","\'").replace("%","\%")
				try:
					movie['filesize'] = os_stat(filename).st_size
				except:
					movie['filesize'] = 0
				movie['fullname'] = serviceref.toString()
				movie['descriptionExtended'] = ext
				movie['servicename'] = sourceRef.getServiceName().replace('\xc2\x86', '').replace('\xc2\x87', '')
				movie['recordingtime'] = rtime
				movie['lastseen'] = pos
				movieliste.append(movie)

	if locations == None:
		ml = { "movies": movieliste, "bookmarks": bookmarklist, "directory": directory }
	else:
		ml = { "movies": movieliste, "locations": locations}
	return ml
Beispiel #15
0
    def __init__(self, session, selectedmovie=None):
        Screen.__init__(self, session)
        HelpableScreen.__init__(self)
        InfoBarBase.__init__(self)  # For ServiceEventTracker

        self.tags = {}
        if selectedmovie:
            self.selected_tags = config.movielist.last_selected_tags.value
        else:
            self.selected_tags = None
        self.selected_tags_ele = None

        self.movemode = False
        self.bouquet_mark_edit = False

        self.delayTimer = eTimer()
        self.delayTimer.callback.append(self.updateHDDData)

        self["waitingtext"] = Label(_("Please wait... Loading list..."))

        # create optional description border and hide immediately
        self["DescriptionBorder"] = Pixmap()
        self["DescriptionBorder"].hide()

        if not os.path.isdir(config.movielist.last_videodir.value):
            config.movielist.last_videodir.value = defaultMoviePath()
            config.movielist.last_videodir.save()
        self.current_ref = eServiceReference(
            "2:0:1:0:0:0:0:0:0:0:" + config.movielist.last_videodir.value)

        self.settings = {\
         "listtype": config.movielist.listtype.value,
         "moviesort": config.movielist.moviesort.value,
         "description": config.movielist.description.value
        }
        self["list"] = MovieList(None,
                                 list_type=self.settings["listtype"],
                                 sort_type=self.settings["moviesort"],
                                 descr_state=self.settings["description"])

        self.list = self["list"]
        self.selectedmovie = selectedmovie

        # Need list for init
        SelectionEventInfo.__init__(self)

        self["key_red"] = Button(_("Delete"))
        self["key_green"] = Button(_("Move"))
        self["key_yellow"] = Button(_("Location"))
        self["key_blue"] = Button(_("Tags"))

        self["freeDiskSpace"] = self.diskinfo = DiskInfo(
            config.movielist.last_videodir.value, DiskInfo.FREE, update=False)

        self["InfobarActions"] = HelpableActionMap(self, "InfobarActions", {
            "showMovies": (self.doPathSelect, _("select the movie path")),
        })

        self["NumberActions"] = HelpableActionMap(
            self, "NumberActions", {
                "1": (self.preview, _("Preview")),
                "2": (self.list.moveToFirst, _("Go to top of list")),
                "5": (self.list.moveToFirstMovie, _("Go to first movie")),
                "8": (self.list.moveToLast, _("Go to last item")),
            })

        self["MovieSelectionActions"] = HelpableActionMap(
            self, "MovieSelectionActions", {
                "contextMenu": (self.doContext, _("menu")),
                "showEventInfo":
                (self.showEventInformation, _("show event details")),
            })

        self["ColorActions"] = HelpableActionMap(
            self, "ColorActions", {
                "red": (self.delete, _("delete...")),
                "green": (self.moveMovie, _("Move to other directory")),
                "yellow": (self.showBookmarks, _("select the movie path")),
                "blue": (self.showTagsSelect, _("show tag menu")),
            })

        self["OkCancelActions"] = HelpableActionMap(
            self, "OkCancelActions", {
                "cancel": (self.abort, _("exit movielist")),
                "ok": (self.itemSelected, _("select movie")),
            })

        self.onShown.append(self.go)
        self.onLayoutFinish.append(self.saveListsize)
        self.list.connectSelChanged(self.updateButtons)
        self.inited = False
        self.onClose.append(self.__onClose)
        NavigationInstance.instance.RecordTimer.on_state_change.append(
            self.list.updateRecordings)
        self.playInBackground = None
        self.__event_tracker = ServiceEventTracker(
            screen=self,
            eventmap={
                #iPlayableService.evSeekableStatusChanged: self.__seekableStatusChanged,
                iPlayableService.evStart:
                self.__serviceStarted,
                iPlayableService.evEOF:
                self.__evEOF,
                #iPlayableService.evSOF: self.__evSOF,
            })
Beispiel #16
0
def getMovieList(directory=None, tag=None, rargs=None, locations=None):
    movieliste = []

    if directory is None:
        directory = MovieSelection.defaultMoviePath()
    if not directory:
        directory = "/media/"
    elif directory[-1] != "/":
        directory += "/"

    root = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + directory)

    bookmarklist = [
        x
        for x in listdir(directory)
        if (x[0] != "." and (isdir(join(directory, x)) or (islink(join(directory, x)) and exists(join(directory, x)))))
    ]
    bookmarklist.sort()

    folders = []
    folders.append(root)
    if rargs and "recursive" in rargs.keys():
        for f in bookmarklist:
            if f[-1] != "/":
                f += "/"
            ff = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + directory + f)
            folders.append(ff)

            # get all locations
    if locations is not None:
        folders = []
        for f in locations:
            if f[-1] != "/":
                f += "/"
            ff = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + f)
            folders.append(ff)

    for root in folders:
        movielist = MovieList(None)
        movielist.load(root, None)

        if tag != None:
            movielist.reload(root=root, filter_tags=[tag])
            # ??? loadLength = True

        for (serviceref, info, begin, unknown) in movielist.list:
            if serviceref.flags & eServiceReference.mustDescent:
                continue

            rtime = info.getInfo(serviceref, iServiceInformation.sTimeCreate)

            if rtime > 0:
                t = FuzzyTime(rtime)
                begin_string = t[0] + ", " + t[1]
            else:
                begin_string = "undefined"

            try:
                Len = info.getLength(serviceref)
            except:
                Len = None

            filename = "/".join(serviceref.toString().split("/")[1:])
            filename = "/" + filename
            pos = getPosition(filename + ".cuts", Len)

            if Len > 0:
                Len = "%d:%02d" % (Len / 60, Len % 60)
            else:
                Len = "?:??"

            sourceERef = info.getInfoString(serviceref, iServiceInformation.sServiceref)
            sourceRef = ServiceReference(sourceERef)
            event = info.getEvent(serviceref)
            ext = event and event.getExtendedDescription() or ""

            servicename = ServiceReference(serviceref).getServiceName().replace("\xc2\x86", "").replace("\xc2\x87", "")
            movie = {}
            movie["filename"] = filename
            movie["filename_stripped"] = filename.split("/")[-1]
            movie["eventname"] = servicename
            movie["description"] = info.getInfoString(serviceref, iServiceInformation.sDescription)
            movie["begintime"] = begin_string
            movie["serviceref"] = serviceref.toString()
            movie["length"] = Len
            movie["tags"] = info.getInfoString(serviceref, iServiceInformation.sTags)
            filename = filename.replace("'", "'").replace("%", "\%")
            try:
                movie["filesize"] = os_stat(filename).st_size
            except:
                movie["filesize"] = 0
            movie["fullname"] = serviceref.toString()
            movie["descriptionExtended"] = ext
            movie["servicename"] = sourceRef.getServiceName().replace("\xc2\x86", "").replace("\xc2\x87", "")
            movie["recordingtime"] = rtime
            movie["lastseen"] = pos
            movieliste.append(movie)

    if locations == None:
        ml = {"movies": movieliste, "bookmarks": bookmarklist, "directory": directory}
    else:
        ml = {"movies": movieliste, "locations": locations}
    return ml
Beispiel #17
0
def getMovieList(directory=None, tag=None):
	movieliste = []
	
	if directory == None:
		directory = config.usage.default_path.value
	
	if directory[-1] != "/":
		directory += "/"
		
	root = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + directory)

	bookmarklist=[x for x in walk(directory).next()[1] if (x[0] != '.' and not islink(directory+'/'+x))]
	bookmarklist.sort()
	
	tagfilter = []
	
	movielist = MovieList(root)
	if tag != None:
		movielist.reload(root=root, filter_tags=[tag])
	loadLength = True

	for (serviceref, info, begin, unknown) in movielist.list:
		if serviceref.flags & eServiceReference.mustDescent:
				continue

		rtime = info.getInfo(serviceref, iServiceInformation.sTimeCreate)

		if rtime > 0:
			t = FuzzyTime(rtime)
			begin_string = t[0] + ", " + t[1]
		else:
			begin_string = "undefined"

		try:
			Len = info.getLength(serviceref)
		except:
			Len = None

		if Len > 0:
			Len = "%d:%02d" % (Len / 60, Len % 60)
		else:
			Len = "?:??"
		
		sourceERef = info.getInfoString(serviceref, iServiceInformation.sServiceref)
		sourceRef = ServiceReference(sourceERef)

		event = info.getEvent(serviceref)
		ext = event and event.getExtendedDescription() or ""

		filename = '/'.join(serviceref.toString().split("/")[1:])
		servicename = ServiceReference(serviceref).getServiceName().replace('\xc2\x86', '').replace('\xc2\x87', '')
		movie = {}
		filename = '/'+filename
		movie['filename'] = filename
		movie['filename_stripped'] = filename.split("/")[-1]
		movie['eventname'] = servicename
		movie['description'] = info.getInfoString(serviceref, iServiceInformation.sDescription)
		movie['begintime'] = begin_string
		movie['serviceref'] = serviceref.toString()
		movie['length'] = Len
		movie['tags'] = info.getInfoString(serviceref, iServiceInformation.sTags)
		filename = filename.replace("'","\'").replace("%","\%")
		try:
			movie['filesize'] = os_stat(filename).st_size
		except:
			movie['filesize'] = 0
		movie['fullname'] = serviceref.toString()
		movie['descriptionExtended'] = ext
		movie['servicename'] = sourceRef.getServiceName().replace('\xc2\x86', '').replace('\xc2\x87', '')
		movie['recordingtime'] = rtime
		
		movieliste.append(movie)
		
	
	return { "movies": movieliste, "bookmarks": bookmarklist, "directory": directory }
def getMovieList(directory=None, tag=None, rargs=None):
	movieliste = []
	
	if directory == None:
		directory = config.usage.default_path.value
	
	if directory[-1] != "/":
		directory += "/"
		
	root = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + directory)

	bookmarklist=[x for x in walk(directory).next()[1] if (x[0] != '.' and not islink(directory+'/'+x))]
	bookmarklist.sort()
	
	folders = []
	folders.append(root)
	if rargs and "recursive" in rargs.keys():
		for f in bookmarklist:
			if f[-1] != "/":
				f += "/"
			ff = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + directory + f)
			folders.append(ff)

	#??? tagfilter = []
	
	for root in folders:
	
		movielist = MovieList(None)
		movielist.load(root, None)
	
		if tag != None:
			movielist.reload(root=root, filter_tags=[tag])
		#??? loadLength = True

		for (serviceref, info, begin, unknown) in movielist.list:
			if serviceref.flags & eServiceReference.mustDescent:
				continue

			rtime = info.getInfo(serviceref, iServiceInformation.sTimeCreate)

			if rtime > 0:
				t = FuzzyTime(rtime)
				begin_string = t[0] + ", " + t[1]
			else:
				begin_string = "undefined"

			try:
				Len = info.getLength(serviceref)
			except:
				Len = None

			if Len > 0:
				Len = "%d:%02d" % (Len / 60, Len % 60)
			else:
				Len = "?:??"
		
			sourceERef = info.getInfoString(serviceref, iServiceInformation.sServiceref)
			sourceRef = ServiceReference(sourceERef)

			event = info.getEvent(serviceref)
			ext = event and event.getExtendedDescription() or ""

			filename = '/'.join(serviceref.toString().split("/")[1:])
			servicename = ServiceReference(serviceref).getServiceName().replace('\xc2\x86', '').replace('\xc2\x87', '')
			movie = {}
			filename = '/'+filename
			movie['filename'] = filename
			movie['filename_stripped'] = filename.split("/")[-1]
			movie['eventname'] = servicename
			movie['description'] = info.getInfoString(serviceref, iServiceInformation.sDescription)
			movie['begintime'] = begin_string
			movie['serviceref'] = serviceref.toString()
			movie['length'] = Len
			movie['tags'] = info.getInfoString(serviceref, iServiceInformation.sTags)
			filename = filename.replace("'","\'").replace("%","\%")
			try:
				movie['filesize'] = os_stat(filename).st_size
			except:
				movie['filesize'] = 0
			movie['fullname'] = serviceref.toString()
			movie['descriptionExtended'] = ext
			movie['servicename'] = sourceRef.getServiceName().replace('\xc2\x86', '').replace('\xc2\x87', '')
			movie['recordingtime'] = rtime
		
			movieliste.append(movie)
		
	ml = { "movies": movieliste, "bookmarks": bookmarklist, "directory": directory }
	
	if rargs and "zip" in rargs.keys():
		filename = rargs["zip"][0]
		import os
		if not os.path.exists(os.path.dirname(filename)):
			return {
				"result": False,
				"message": "zip file path not exist"
			}
		try:
			import json
			fd = open(filename, 'wb')
			#todo create zip using api
			#fd = gzip.GzipFile(filename=filename, mode='wb', compresslevel=9)
			fd.write(json.dumps(ml))
			fd.close()
			try:
				os.remove('%s.gz' % filename)
			except OSError:
				pass
			os.system('gzip %s' % filename)
		except (IOError, os.error), why:
			return {
				"result": False,
				"message": "create movielist zip error:%s" % why
			}
		return {
			"result": True,
			"message": "create movielist zip success"
		}
Beispiel #19
0
    def __init__(self, session, selectedmovie=None):
        Screen.__init__(self, session)
        HelpableScreen.__init__(self)

        self.tags = []
        if selectedmovie:
            self.selected_tags = config.movielist.last_selected_tags.value
        else:
            self.selected_tags = None
        self.selected_tags_ele = None

        self.movemode = False
        self.bouquet_mark_edit = False

        self.delayTimer = eTimer()
        self.delayTimer.callback.append(self.updateHDDData)

        self["waitingtext"] = Label(_("Please wait... Loading list..."))

        # create optional description border and hide immediately
        self["DescriptionBorder"] = Pixmap()
        self["DescriptionBorder"].hide()

        if not fileExists(config.movielist.last_videodir.value):
            config.movielist.last_videodir.value = defaultMoviePath()
            config.movielist.last_videodir.save()
        self.current_ref = eServiceReference(
            "2:0:1:0:0:0:0:0:0:0:" + config.movielist.last_videodir.value)

        self["list"] = MovieList(None, config.movielist.listtype.value,
                                 config.movielist.moviesort.value,
                                 config.movielist.description.value)

        self.list = self["list"]
        self.selectedmovie = selectedmovie

        # Need list for init
        SelectionEventInfo.__init__(self)

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

        self["freeDiskSpace"] = self.diskinfo = DiskInfo(
            config.movielist.last_videodir.value, DiskInfo.FREE, update=False)

        if config.usage.setup_level.index >= 2:  # expert+
            self["InfobarActions"] = HelpableActionMap(
                self, "InfobarActions", {
                    "showMovies":
                    (self.doPathSelect, _("select the movie path")),
                })

        self["MovieSelectionActions"] = HelpableActionMap(
            self, "MovieSelectionActions", {
                "contextMenu": (self.doContext, _("menu")),
                "showEventInfo":
                (self.showEventInformation, _("show event details")),
            })

        self["ColorActions"] = HelpableActionMap(
            self, "ColorActions", {
                "red": (self.showAll, _("show all")),
                "green": (self.showTagsFirst, _("show first selected tag")),
                "yellow": (self.showTagsSecond, _("show second selected tag")),
                "blue": (self.showTagsSelect, _("show tag menu")),
            })

        self["OkCancelActions"] = HelpableActionMap(
            self, "OkCancelActions", {
                "cancel": (self.abort, _("exit movielist")),
                "ok": (self.movieSelected, _("select movie")),
            })

        self.onShown.append(self.go)
        self.onLayoutFinish.append(self.saveListsize)
        self.inited = False
def getMovieList(rargs=None, locations=None):
    movieliste = []
    tag = None
    directory = None
    fields = None
    bookmarklist = []

    if rargs and "tag" in rargs.keys():
        tag = rargs["tag"][0]

    if rargs and "dirname" in rargs.keys():
        directory = rargs["dirname"][0]

    if rargs and "fields" in rargs.keys():
        fields = rargs["fields"][0]

    if directory is None:
        directory = MovieSelection.defaultMoviePath()
    else:
        try:
            directory.decode('utf-8')
        except UnicodeDecodeError:
            try:
                directory = directory.decode("cp1252").encode("utf-8")
            except UnicodeDecodeError:
                directory = directory.decode("iso-8859-1").encode("utf-8")

    if not directory:
        directory = MOVIE_LIST_ROOT_FALLBACK

    if directory[-1] != "/":
        directory += "/"

    if not os.path.isdir(directory):
        return {
            "movies": [],
            "locations": [],
            "bookmarks": [],
            "directory": [],
        }

    root = eServiceReference(MOVIE_LIST_SREF_ROOT + directory)

    for item in sorted(os.listdir(directory)):
        abs_p = os.path.join(directory, item)
        if os.path.isdir(abs_p):
            bookmarklist.append(item)

    folders = [root]
    if rargs and "recursive" in rargs.keys():
        for f in bookmarklist:
            if f[-1] != "/":
                f += "/"
            ff = eServiceReference(MOVIE_LIST_SREF_ROOT + directory + f)
            folders.append(ff)

    # get all locations
    if locations is not None:
        folders = []

        for f in locations:
            if f[-1] != "/":
                f += "/"
            ff = eServiceReference(MOVIE_LIST_SREF_ROOT + f)
            folders.append(ff)

    if config.OpenWebif.parentalenabled.value:
        dir_is_protected = checkParentalProtection(directory)
    else:
        dir_is_protected = False

    if not dir_is_protected:
        for root in folders:
            movielist = MovieList(None)
            movielist.load(root, None)

            if tag is not None:
                movielist.reload(root=root, filter_tags=[tag])

            for (serviceref, info, begin, unknown) in movielist.list:
                if serviceref.flags & eServiceReference.mustDescent:
                    continue

                length_minutes = 0
                txtdesc = ""
                filename = '/'.join(serviceref.toString().split("/")[1:])
                filename = '/' + filename
                name, ext = os.path.splitext(filename)

                sourceRef = ServiceReference(
                    info.getInfoString(serviceref,
                                       iServiceInformation.sServiceref))
                rtime = info.getInfo(serviceref,
                                     iServiceInformation.sTimeCreate)

                movie = {
                    'filename':
                    filename,
                    'filename_stripped':
                    filename.split("/")[-1],
                    'serviceref':
                    serviceref.toString(),
                    'length':
                    "?:??",
                    'lastseen':
                    0,
                    'filesize_readable':
                    '',
                    'recordingtime':
                    rtime,
                    'begintime':
                    'undefined',
                    'eventname':
                    ServiceReference(serviceref).getServiceName().replace(
                        '\xc2\x86', '').replace('\xc2\x87', ''),
                    'servicename':
                    sourceRef.getServiceName().replace('\xc2\x86', '').replace(
                        '\xc2\x87', ''),
                    'tags':
                    info.getInfoString(serviceref, iServiceInformation.sTags),
                    'fullname':
                    serviceref.toString(),
                }

                if rtime > 0:
                    fuzzy_rtime = FuzzyTime(rtime)
                    movie['begintime'] = fuzzy_rtime[0] + ", " + fuzzy_rtime[1]

                try:
                    length_minutes = info.getLength(serviceref)
                except:  # noqa: E722
                    pass

                if length_minutes:
                    movie['length'] = "%d:%02d" % (length_minutes / 60,
                                                   length_minutes % 60)
                    if fields is None or 'pos' in fields:
                        movie['lastseen'] = getPosition(
                            filename + '.cuts', length_minutes)

                if fields is None or 'desc' in fields:
                    txtfile = name + '.txt'
                    if ext.lower() != '.ts' and os.path.isfile(txtfile):
                        with open(txtfile, "rb") as handle:
                            txtdesc = ''.join(handle.readlines())

                    event = info.getEvent(serviceref)
                    extended_description = event and event.getExtendedDescription(
                    ) or ""
                    if extended_description == '' and txtdesc != '':
                        extended_description = txtdesc
                    movie['descriptionExtended'] = unicode(
                        extended_description, 'utf_8',
                        errors='ignore').encode('utf_8', 'ignore')

                    desc = info.getInfoString(serviceref,
                                              iServiceInformation.sDescription)
                    movie['description'] = unicode(desc,
                                                   'utf_8',
                                                   errors='ignore').encode(
                                                       'utf_8', 'ignore')

                if fields is None or 'size' in fields:
                    size = 0
                    sz = ''

                    try:
                        size = os.stat(filename).st_size
                        if size > 1073741824:
                            sz = "%.2f %s" % ((size / 1073741824.), _("GB"))
                        elif size > 1048576:
                            sz = "%.2f %s" % ((size / 1048576.), _("MB"))
                        elif size > 1024:
                            sz = "%.2f %s" % ((size / 1024.), _("kB"))
                    except:  # noqa: E722
                        pass

                    movie['filesize'] = size
                    movie['filesize_readable'] = sz

                movieliste.append(movie)

    if locations is None:
        return {
            "movies": movieliste,
            "bookmarks": bookmarklist,
            "directory": directory
        }

    return {"movies": movieliste, "locations": locations}
Beispiel #21
0
def getMovieList(directory=None, tag=None, rargs=None, locations=None):
    movieliste = []

    if directory is None:
        directory = MovieSelection.defaultMoviePath()
    else:
        directory = unquote(directory)
        try:
            directory.decode("utf-8")
        except UnicodeDecodeError:
            try:
                directory = directory.decode("cp1252").encode("utf-8")
            except UnicodeDecodeError:
                directory = directory.decode("iso-8859-1").encode("utf-8")

    if not directory:
        directory = "/media/"
    elif directory[-1] != "/":
        directory += "/"

    root = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + directory)

    bookmarklist = [
        x
        for x in listdir(directory)
        if (x[0] != "." and (isdir(join(directory, x)) or (islink(join(directory, x)) and exists(join(directory, x)))))
    ]
    bookmarklist.sort()

    folders = []
    folders.append(root)
    if rargs and "recursive" in rargs.keys():
        for f in bookmarklist:
            if f[-1] != "/":
                f += "/"
            ff = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + directory + f)
            folders.append(ff)

            # get all locations
    if locations is not None:
        folders = []
        for f in locations:
            if f[-1] != "/":
                f += "/"
            ff = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + f)
            folders.append(ff)

    if config.OpenWebif.parentalenabled.value:
        dir_is_protected = checkParentalProtection(directory)
    else:
        dir_is_protected = False

    import os

    if not dir_is_protected:
        for root in folders:
            movielist = MovieList(None)
            movielist.load(root, None)

            if tag != None:
                movielist.reload(root=root, filter_tags=[tag])
                # ??? loadLength = True

            for (serviceref, info, begin, unknown) in movielist.list:
                if serviceref.flags & eServiceReference.mustDescent:
                    continue

                rtime = info.getInfo(serviceref, iServiceInformation.sTimeCreate)

                if rtime > 0:
                    t = FuzzyTime(rtime)
                    begin_string = t[0] + ", " + t[1]
                else:
                    begin_string = "undefined"

                try:
                    Len = info.getLength(serviceref)
                except:
                    Len = None

                filename = "/".join(serviceref.toString().split("/")[1:])
                filename = "/" + filename
                pos = getPosition(filename + ".cuts", Len)

                # get txt
                name, ext = os.path.splitext(filename)
                ext = ext.lower()

                txtdesc = ""

                if ext != "ts":
                    txtfile = name + ".txt"
                    if fileExists(txtfile):
                        txtlines = open(txtfile).readlines()
                        txtdesc = ""
                        for line in txtlines:
                            txtdesc += line

                if Len > 0:
                    Len = "%d:%02d" % (Len / 60, Len % 60)
                else:
                    Len = "?:??"

                sourceERef = info.getInfoString(serviceref, iServiceInformation.sServiceref)
                sourceRef = ServiceReference(sourceERef)
                event = info.getEvent(serviceref)
                ext = event and event.getExtendedDescription() or ""

                if ext == "" and txtdesc != "":
                    ext = txtdesc

                desc = info.getInfoString(serviceref, iServiceInformation.sDescription)
                servicename = (
                    ServiceReference(serviceref).getServiceName().replace("\xc2\x86", "").replace("\xc2\x87", "")
                )
                movie = {}
                movie["filename"] = filename
                movie["filename_stripped"] = filename.split("/")[-1]
                movie["eventname"] = servicename
                movie["description"] = unicode(desc, "utf_8", errors="ignore").encode("utf_8", "ignore")
                movie["begintime"] = begin_string
                movie["serviceref"] = serviceref.toString()
                movie["length"] = Len
                movie["tags"] = info.getInfoString(serviceref, iServiceInformation.sTags)
                filename = filename.replace("'", "'").replace("%", "\%")
                try:
                    movie["filesize"] = os_stat(filename).st_size
                except:
                    movie["filesize"] = 0
                movie["fullname"] = serviceref.toString()
                movie["descriptionExtended"] = unicode(ext, "utf_8", errors="ignore").encode("utf_8", "ignore")
                movie["servicename"] = sourceRef.getServiceName().replace("\xc2\x86", "").replace("\xc2\x87", "")
                movie["recordingtime"] = rtime
                movie["lastseen"] = pos
                movieliste.append(movie)

    if locations == None:
        ml = {"movies": movieliste, "bookmarks": bookmarklist, "directory": directory}
    else:
        ml = {"movies": movieliste, "locations": locations}
    return ml
def getMovieList(rargs=None, locations=None):
	movieliste = []
	tag = None
	directory = None
	fields = None
	bookmarklist = []

	if rargs and "tag" in rargs.keys():
		tag = rargs["tag"][0]

	if rargs and "dirname" in rargs.keys():
		directory = rargs["dirname"][0]

	if rargs and "fields" in rargs.keys():
		fields = rargs["fields"][0]

	if directory is None:
		directory = MovieSelection.defaultMoviePath()
	else:
		try:
			directory.decode('utf-8')
		except UnicodeDecodeError:
			try:
				directory = directory.decode("cp1252").encode("utf-8")
			except UnicodeDecodeError:
				directory = directory.decode("iso-8859-1").encode("utf-8")

	if not directory:
		directory = MOVIE_LIST_ROOT_FALLBACK

	if directory[-1] != "/":
		directory += "/"

	if not os.path.isdir(directory):
		return {
			"movies": [],
			"locations": [],
			"bookmarks": [],
			"directory": [],
		}

	root = eServiceReference(MOVIE_LIST_SREF_ROOT + directory)

	for item in sorted(os.listdir(directory)):
		abs_p = os.path.join(directory, item)
		if os.path.isdir(abs_p):
			bookmarklist.append(item)

	folders = [root]
	if rargs and "recursive" in rargs.keys():
		for f in bookmarklist:
			if f[-1] != "/":
				f += "/"
			ff = eServiceReference(MOVIE_LIST_SREF_ROOT + directory + f)
			folders.append(ff)

	# get all locations
	if locations is not None:
		folders = []

		for f in locations:
			if f[-1] != "/":
				f += "/"
			ff = eServiceReference(MOVIE_LIST_SREF_ROOT + f)
			folders.append(ff)

	if config.OpenWebif.parentalenabled.value:
		dir_is_protected = checkParentalProtection(directory)
	else:
		dir_is_protected = False

	if not dir_is_protected:
		movielist = MovieList(None)
		for root in folders:
			if tag is not None:
				movielist.load(root=root, filter_tags=[tag])
			else:
				movielist.load(root=root, filter_tags=None)

			for (serviceref, info, begin, unknown) in movielist.list:
				if serviceref.flags & eServiceReference.mustDescent:
					continue

				length_minutes = 0
				txtdesc = ""
				filename = '/'.join(serviceref.toString().split("/")[1:])
				filename = '/' + filename
				name, ext = os.path.splitext(filename)

				sourceRef = ServiceReference(
					info.getInfoString(
						serviceref, iServiceInformation.sServiceref))
				rtime = info.getInfo(
					serviceref, iServiceInformation.sTimeCreate)

				movie = {
					'filename': filename,
					'filename_stripped': filename.split("/")[-1],
					'serviceref': serviceref.toString(),
					'length': "?:??",
					'lastseen': 0,
					'filesize_readable': '',
					'recordingtime': rtime,
					'begintime': 'undefined',
					'eventname': ServiceReference(serviceref).getServiceName().replace('\xc2\x86', '').replace('\xc2\x87', ''),
					'servicename': sourceRef.getServiceName().replace('\xc2\x86', '').replace('\xc2\x87', ''),
					'tags': info.getInfoString(serviceref, iServiceInformation.sTags),
					'fullname': serviceref.toString(),
				}

				if rtime > 0:
					fuzzy_rtime = FuzzyTime(rtime)
					movie['begintime'] = fuzzy_rtime[0] + ", " + fuzzy_rtime[1]

				try:
					length_minutes = info.getLength(serviceref)
				except:  # noqa: E722
					pass

				if length_minutes:
					movie['length'] = "%d:%02d" % (length_minutes / 60, length_minutes % 60)
					if fields is None or 'pos' in fields:
						movie['lastseen'] = _moviePlayState(filename + '.cuts', serviceref, length_minutes) or 0

				if fields is None or 'desc' in fields:
					txtfile = name + '.txt'
					if ext.lower() != '.ts' and os.path.isfile(txtfile):
						with open(txtfile, "rb") as handle:
							txtdesc = ''.join(handle.readlines())

					event = info.getEvent(serviceref)
					extended_description = event and event.getExtendedDescription() or ""
					if extended_description == '' and txtdesc != '':
						extended_description = txtdesc
					movie['descriptionExtended'] = unicode(extended_description, 'utf_8', errors='ignore').encode('utf_8', 'ignore')

					desc = info.getInfoString(serviceref, iServiceInformation.sDescription)
					movie['description'] = unicode(desc, 'utf_8', errors='ignore').encode('utf_8', 'ignore')

				if fields is None or 'size' in fields:
					size = 0
					sz = ''

					try:
						size = os.stat(filename).st_size
						if size > 1073741824:
							sz = "%.2f %s" % ((size / 1073741824.), _("GB"))
						elif size > 1048576:
							sz = "%.2f %s" % ((size / 1048576.), _("MB"))
						elif size > 1024:
							sz = "%.2f %s" % ((size / 1024.), _("kB"))
					except:  # noqa: E722
						pass

					movie['filesize'] = size
					movie['filesize_readable'] = sz

				movieliste.append(movie)
		del movielist

	if locations is None:
		return {
			"movies": movieliste,
			"bookmarks": bookmarklist,
			"directory": directory
		}

	return {
		"movies": movieliste,
		"locations": locations
	}
Beispiel #23
0
class SimpleVDRProtocol(LineReceiver):
    def __init__(self, client=False):
        self.client = client
        self._channelList = []
        from Components.MovieList import MovieList
        from Tools.Directories import resolveFilename, SCOPE_HDD

        self.movielist = MovieList(eServiceReference("2:0:1:0:0:0:0:0:0:0:" + resolveFilename(SCOPE_HDD)))

    def getChannelList(self):
        if not self._channelList:
            from Components.Sources.ServiceList import ServiceList

            bouquet = eServiceReference('1:7:1:0:0:0:0:0:0:0:FROM BOUQUET "userbouquet.favourites.tv" ORDER BY bouquet')
            slist = ServiceList(bouquet, validate_commands=False)
            services = slist.getServicesAsList(format="S")
            self._channelList = services[:]
        return self._channelList

    def setChannelList(self, channelList):
        self._channelList = channelList

    channelList = property(getChannelList, setChannelList)

    def connectionMade(self):
        self.factory.addClient(self)
        now = strftime("%a %b %d %H:%M:%S %Y", localtime())
        payload = "%d %s SVDRP VideoDiskRecorder (Enigma 2-Plugin %s); %s" % (CODE_HELO, uname()[1], VERSION, now)
        self.sendLine(payload)

    def connectionLost(self, reason):
        self.factory.removeClient(self)

    def stop(self, *args):
        payload = "%d %s closing connection" % (CODE_BYE, uname()[1])
        self.sendLine(payload)
        self.transport.loseConnection()

    def NOT_IMPLEMENTED(self, args):
        print("[SVDRP] command not implemented.")
        payload = "%d command not implemented." % (CODE_IMP_FUNC,)
        self.sendLine(payload)

    def CHAN(self, args):
        # allowed parameters: [ + | - | <number> | <name> | <id> ]
        if args == "+":
            InfoBar.instance.zapDown()
            payload = "%d channel changed" % (CODE_OK,)
        elif args == "-":
            InfoBar.instance.zapUp()
            payload = "%d channel changed" % (CODE_OK,)
        else:
            # can be number, name or id
            payload = "%d parameter not implemented" % (CODE_IMP_PARAM,)

        self.sendLine(payload)

    def LSTC(self, args):
        if args:
            payload = "%d parameter not implemented" % (CODE_IMP_PARAM,)
            return self.sendLine(payload)
        from Components.Sources.ServiceList import ServiceList

        bouquet = eServiceReference('1:7:1:0:0:0:0:0:0:0:FROM BOUQUET "userbouquet.favourites.tv" ORDER BY bouquet')
        slist = ServiceList(bouquet, validate_commands=False)
        services = slist.getServicesAsList(format="SNn")
        if services:

            def getServiceInfoValue(info, sref, what):
                if info is None:
                    return ""
                v = info.getInfo(sref.ref, what)
                if v == -2:
                    return info.getInfoString(sref.ref, what)
                elif v == -1:
                    return "N/A"
                return v

            def sendServiceLine(service, counter, last=False):
                if service[0][:5] == "1:64:":
                    # format for markers:  ":Name"
                    line = "%d%s:%s" % (CODE_OK, "-" if not last else " ", service[1])
                else:
                    # <id> <full name>,<short name>;<provider>:<freq>:<parameters>:<source>:<srate>:<vpid>:<apid>:<tpid>:<conditional access>:<:sid>:<nid>:<tid>:<:rid>
                    # e.g. 5  RTL Television,RTL:12188:h:S19.2E:27500:163:104:105:0:12003:1:1089:0
                    sref = ServiceReference(service[0])
                    info = sref.info()
                    # XXX: how to get this?! o0
                    feinfo = None  # sref.ref.frontendInfo()
                    fedata = feinfo.getAll(True) if feinfo else {}
                    prov = getServiceInfoValue(info, sref, iServiceInformation.sProvider)
                    frequency = fedata.get("frequency", 0) / 1000
                    param = -1
                    source = "-1"
                    srate = -1
                    vpid = "-1"
                    apid = "-1"
                    tpid = -1
                    ca = "-1"
                    sid = -1
                    nid = -1
                    tid = -1
                    rid = -1
                    # TODO: support full format, these are only the important fields ;)
                    line = "%d%s%d %s,%s;%s:%d:%s:%s:%d:%s:%s:%d:%s:%d:%d:%d:%d" % (
                        CODE_OK,
                        "-" if not last else " ",
                        counter,
                        service[1],
                        service[2],
                        prov,
                        frequency,
                        param,
                        source,
                        srate,
                        vpid,
                        apid,
                        tpid,
                        ca,
                        sid,
                        nid,
                        tid,
                        rid,
                    )
                self.sendLine(line)

            self.channelList = [
                x[0] for x in services
            ]  # always refresh cache b/c this is what the user works with from now on
            lastItem = services.pop()
            idx = 1
            for service in services:
                sendServiceLine(service, idx)
                idx += 1
            sendServiceLine(lastItem, idx, last=True)
        else:
            payload = "%d no services found" % (CODE_ERR_LOCAL,)
            self.sendLine(payload)

    def sendTimerLine(self, timer, counter, last=False):
        # <number> <flags>:<channel id>:<YYYY-MM-DD>:<HHMM>:<HHMM>:<priority>:<lifetime>:<name>:<auxiliary>
        flags = 0
        if not timer.disabled:
            flags |= 1
        if timer.state == timer.StateRunning:
            flags |= 8
        try:
            channelid = self.channelList.index(str(timer.service_ref)) + 1
        except ValueError as e:
            # XXX: ignore timers on channels that are not in our favourite bouquet
            return False
        else:
            datestring = strftime("%Y-%m-%d", localtime(timer.begin))
            beginstring = strftime("%H%M", localtime(timer.begin))
            endstring = strftime("%H%M", localtime(timer.end))
            line = "%d%s%d %d:%d:%s:%s:%s:%d:%d:%s:%s" % (
                CODE_OK,
                "-" if not last else " ",
                counter,
                flags,
                channelid,
                datestring,
                beginstring,
                endstring,
                1,
                1,
                timer.name,
                timer.description,
            )
            self.sendLine(line)
            return True

    def getTimerList(self):
        import NavigationInstance

        list = []
        recordTimer = NavigationInstance.instance.RecordTimer
        list.extend(recordTimer.timer_list)
        list.extend(recordTimer.processed_timers)
        list.sort(key=attrgetter("begin"))
        return list

    def LSTT(self, args):
        list = self.getTimerList()
        lastItem = list.pop()
        idx = 1
        for timer in list:
            self.sendTimerLine(timer, idx)
            idx += 1
        if not self.sendTimerLine(lastItem, idx, last=True):
            # send error if last item failed to send, else the other end might get stuck
            payload = "%d data inconsistency error." % (CODE_ERR_LOCAL,)
            self.sendLine(payload)

    def UPDT(self, args):
        # <id> <settings>
        args = args.split(None, 1)
        if len(args) != 2:
            payload = "%d argument error" % (CODE_SYNTAX,)
            return self.sendLine(payload)

        try:
            timerId = int(args[0])
        except ValueError:
            payload = "%d argument error" % (CODE_SYNTAX,)
            return self.sendLine(payload)

        list = self.getTimerList()

        if timerId < 1:
            payload = "%d argument error" % (CODE_SYNTAX,)
            return self.sendLine(payload)

        if len(list) >= timerId:
            oldTimer = list[timerId - 1]
        else:
            oldTimer = None

        try:
            flags, channelid, datestring, beginstring, endstring, priority, lifetime, name, description = args[1].split(
                ":"
            )
            flags = int(flags)
            service_ref = ServiceReference(self.channelList[int(channelid) - 1])
            datestruct = strptime(datestring, "%Y-%m-%d")
            timestruct = strptime(beginstring, "%H%M")
            begin = mktime(
                (
                    datestruct.tm_year,
                    datestruct.tm_mon,
                    datestruct.tm_mday,
                    timestruct.tm_hour,
                    timestruct.tm_min,
                    0,
                    datestruct.tm_wday,
                    datestruct.tm_yday,
                    -1,
                )
            )
            timestruct = strptime(endstring, "%H%M")
            end = mktime(
                (
                    datestruct.tm_year,
                    datestruct.tm_mon,
                    datestruct.tm_mday,
                    timestruct.tm_hour,
                    timestruct.tm_min,
                    0,
                    datestruct.tm_wday,
                    datestruct.tm_yday,
                    -1,
                )
            )
            del datestruct, timestruct
        except ValueError as e:
            payload = "%d argument error" % (CODE_SYNTAX,)
            return self.sendLine(payload)
        except KeyError as e:
            payload = "%d argument error" % (CODE_SYNTAX,)
            return self.sendLine(payload)

        if end < begin:
            end += 86400  # Add 1 day, beware - this is evil and might not work correctly due to dst
        timer = RecordTimerEntry(service_ref, begin, end, name, description, 0, disabled=flags & 1 == 0)
        if oldTimer:
            recordTimer.removeEntry(oldTimer)
            timer.justplay = oldTimer.justplay
            timer.afterEvent = oldTimer.afterEvent
            timer.dirname = oldTimer.dirname
            timer.tags = oldTimer.tags
            timer.log_entries = oldTimer.log_entries

        conflict = recordTimer.record(timer)
        if conflict is None:
            return self.sendTimerLine(timer, timerId, last=True)
        else:
            payload = "%d timer conflict detected, original timer lost." % (CODE_ERR_LOCAL,)
            return self.sendLine(payload)

    def NEWT(self, args):
        self.UPDT("999999999 " + args)

    def MODT(self, args):
        # <id> on | off | <settings>
        args = args.split(None, 1)
        if len(args) != 2:
            payload = "%d argument error" % (CODE_SYNTAX,)
            return self.sendLine(payload)

        if args[1] in ("on", "off"):
            try:
                timerId = int(args[0])
            except ValueError:
                payload = "%d argument error" % (CODE_SYNTAX,)
                return self.sendLine(payload)

            list = self.getTimerList()

            if timerId < 1 or len(list) < timerId:
                payload = "%d argument error" % (CODE_SYNTAX,)
                return self.sendLine(payload)

            timer = list[timerId - 1]
            disable = args[1] == "off"
            if disable and timer.isRunning():
                payload = "%d timer is running, not disabling." % (CODE_ERR_LOCAL,)
                return self.sendLine(payload)
            else:
                if timer.disabled and not disable:
                    timer.enable()
                    tsc = TimerSanityCheck(recordTimer.timer_list, timer)
                    if not timersanitycheck.check():
                        timer.disable()
                        payload = "%d timer conflict detected, aborting." % (CODE_ERR_LOCAL,)
                        return self.sendLine(payload)
                    else:
                        if timersanitycheck.doubleCheck():
                            timer.disable()
                elif not timer.disabled and disable:
                    timer.disable()
                recordTimer.timeChanged(timer)
                sef.sendTimerLine(timer, timerId, last=True)
        else:
            self.UPDT(" ".join(args))

    def DELT(self, args):
        try:
            timerId = int(args)
        except ValueError:
            payload = "%d argument error" % (CODE_SYNTAX,)
            return self.sendLine(payload)

        list = self.getTimerList()

        if timerId < 1 or len(list) < timerId:
            payload = "%d argument error" % (CODE_SYNTAX,)
            return self.sendLine(payload)

        timer = list[timerId - 1]
        recordTimer.removeEntry(timer)
        payload = '%d Timer "%d" deleted' % (CODE_OK, timerId)
        self.sendLine(payload)

    def MESG(self, data):
        if not data:
            payload = "%d parameter not implemented" % (CODE_IMP_PARAM,)
            return self.sendLine(payload)

        Notifications.AddNotificationWithID(
            NOTIFICATIONID, MessageBox, text=data, type=MessageBox.TYPE_INFO, timeout=5, close_on_any_key=True
        )
        payload = "%d Message queued" % (CODE_OK,)
        self.sendLine(payload)

    def VOLU(self, args):
        volctrl = eDVBVolumecontrol.getInstance()
        if args == "mute":
            from Components.VolumeControl import VolumeControl

            VolumeControl.instance.volMute()
        elif args == "+":
            from Components.VolumeControl import VolumeControl

            VolumeControl.instance.volUp()
        elif args == "-":
            from Components.VolumeControl import VolumeControl

            VolumeControl.instance.volDown()
        elif args:
            try:
                num = int(args) / 2.55
            except ValueError:
                payload = "%d %s" % (CODE_SYNTAX, str(e).replace("\n", " ").replace("\r", ""))
                return self.sendLine(payload)
            else:
                volctr.setVolume(num, num)

        if volctrl.isMuted():
            payload = "%d Audio is mute" % (CODE_OK,)
        else:
            payload = "%d Audio volume is %d." % (CODE_OK, volctrl.getVolume() * 2.55)
        self.sendLine(payload)

    def HELP(self, args):
        if not len(args) == 2:
            payload = "%d data inconsistency error." % (CODE_ERR_LOCAL,)
            return self.sendLine(payload)
        funcs, args = args
        if not args:
            funcnames = sorted(funcs.keys())
            payload = "%d-This is Enigma2 VDR-Plugin version %s" % (CODE_HELP, VERSION)
            self.sendLine(payload)
            payload = "%d-Topics:" % (CODE_HELP,)
            x = 5
            for func in funcnames:
                if x == 5:
                    self.sendLine(payload)
                    payload = "%d-    %s" % (CODE_HELP, func)
                    x = 1
                else:
                    payload += "      %s" % (func,)
                    x += 1
            self.sendLine(payload)
            payload = "%d-To report bugs in the implementation send email to" % (CODE_HELP,)
            self.sendLine(payload)
            payload = "%d-    svdrp AT ritzmo DOT de" % (CODE_HELP,)
            self.sendLine(payload)
            payload = "%d End of HELP info" % (CODE_HELP,)
            self.sendLine(payload)
        else:
            payload = "%d parameter not implemented" % (CODE_IMP_PARAM,)
            return self.sendLine(payload)

    def LSTR(self, args):
        if args:
            payload = "%d parameter not implemented" % (CODE_IMP_PARAM,)
            return self.sendLine(payload)

        self.movielist.reload()

        def sendMovieLine(sref, info, begin, counter, last=False):
            # <number> <date> <begin> <name>
            ctime = info.getInfo(
                serviceref, iServiceInformation.sTimeCreate
            )  # XXX: difference to begin? just copied this from webif ;-)
            datestring = strftime("%d.%m.%y", localtime(ctime))
            beginstring = strftime("%H:%M", localtime(ctime))
            servicename = ServiceReference(sref).getServiceName().replace("\xc2\x86", "").replace("\xc2\x87", "")
            line = "%d%s%d %s %s %s" % (
                CODE_OK,
                "-" if not last else " ",
                counter,
                datestring,
                beginstring,
                servicename,
            )
            self.sendLine(line)

        list = self.movielist.list[:]
        lastItem = list.pop()
        idx = 1
        for serviceref, info, begin, unknown in list:
            sendMovieLine(serviceref, info, begin, idx)
            idx += 1
        sendMovieLine(lastItem[0], lastItem[1], lastItem[2], idx, last=True)

    def DELR(self, args):
        try:
            movieId = int(args)
        except ValueError:
            payload = "%d argument error" % (CODE_SYNTAX,)
            return self.sendLine(payload)

        sref = self.movielist.list[movieId - 1][0]
        serviceHandler = eServiceCenter.getInstance()
        offline = serviceHandler.offlineOperations(sref)

        if offline is not None:
            if not offline.deleteFromDisk(0):
                payload = '%d Movie "%d" deleted' % (CODE_OK, movieId)
                return self.sendLine(payload)

        payload = "%d data inconsistency error." % (CODE_ERR_LOCAL,)
        self.sendLine(payload)

    def LSTE(self, args):
        args = args.split()
        first = args and args.pop(0)
        # TODO: find out format of "at <time>"
        if not first or first in ("now", "next", "at") or args and args[1] == "at":
            # XXX: "parameter not implemented" might be weird to say in case of no parameters, but who cares :-)
            payload = "%d parameter not implemented" % (CODE_IMP_PARAM,)
            return self.sendLine(payload)
        try:
            channelId = int(first) - 1
            service = self.channelList[channelId]
        except ValueError:
            # XXX: add support for sref
            payload = "%d parameter not implemented" % (CODE_IMP_PARAM,)
            return self.sendLine(payload)

            # handle additional parametes "now" and "next"
        type = 0
        time = -1
        endtime = -1
        options = "IBDTSERN"
        if args:
            options = "IBDTSERNX"
            if args[0] == "now":
                type = 0
                endtime = None
            elif args[0] == "next":
                type = 1
                endtime = None

                # fetch data
        epgcache = eEPGCache.getInstance()
        if endtime is None:
            params = (service, type, time)
        else:
            params = (service, type, time, endtime)
        events = epgcache.lookupEvent([options, params])

        # process data
        def sendEventLine(eit, begin, duration, title, description, extended, sref, sname):
            payload = "%d-E %d %d %d 0" % (CODE_EPG, eit, begin, duration)
            self.sendLine(payload)
            payload = "%d-T %s" % (CODE_EPG, title)
            self.sendLine(payload)
            payload = "%d-S %s" % (CODE_EPG, description)
            self.sendLine(payload)
            payload = "%d-D %s" % (CODE_EPG, extended.replace("\xc2\x8a", "|"))
            self.sendLine(payload)
            payload = "%d-e" % (CODE_EPG,)
            self.sendLine(payload)

        lastItem = events.pop()
        payload = "%d-C %s %s" % (CODE_EPG, lastItem[-2], lastItem[-1])
        self.sendLine(payload)
        for event in events:
            sendEventLine(*event)
        sendEventLine(*lastItem)
        payload = "%d-c" % (CODE_EPG,)
        self.sendLine(payload)
        payload = "%d End of EPG data" % (CODE_EPG,)
        self.sendLine(payload)

    def lineReceived(self, data):
        if self.client or not self.transport or not data:
            return

        print("[SVDRP] incoming message:", data)
        list = data.split(" ", 1)
        command = list.pop(0).upper()
        args = list[0] if list else ""

        # still possible: grab, (partially) hitk, (theoretically) movc, next? (dunno what this does), play, stat and completion of existing commands
        funcs = {
            "CHAN": self.CHAN,
            "DELR": self.DELR,
            "DELT": self.DELT,
            "HELP": self.HELP,
            "LSTC": self.LSTC,
            "LSTE": self.LSTE,
            "LSTT": self.LSTT,
            "LSTR": self.LSTR,
            "MESG": self.MESG,
            "MODT": self.MODT,
            "NEWT": self.NEWT,
            "UPDT": self.UPDT,
            "QUIT": self.stop,
            "VOLU": self.VOLU,
        }
        if command == "HELP":
            args = (funcs, args)
        call = funcs.get(command, self.NOT_IMPLEMENTED)

        try:
            call(args)
        except Exception as e:
            import traceback, sys

            traceback.print_exc(file=sys.stdout)
            payload = "%d exception occured: %s" % (CODE_ERR, str(e).replace("\n", " ").replace("\r", ""))
            self.sendLine(payload)