Exemple #1
0
class MythXML(XMLConnection):
    """
    Provides convenient methods to access the backend XML server.
    Parameter 'backend' is either a hostname from 'settings',
    an ip address or a hostname in ip-notation.
    """
    def __init__(self, backend=None, port=None, db=None):
        if backend and port:
            XMLConnection.__init__(self, backend, port)
            self.db = db
            return

        self.db = DBCache(db)
        self.log = MythLog('Python XML Connection')
        if backend is None:
            # use master backend
            backend = self.db.getMasterBackend()

        # assume hostname from settings
        host = self.db._getpreferredaddr(backend)
        if host:
            port = int(self.db.settings[backend].BackendStatusPort)
        else:
            # assume ip address
            hostname = self.db._gethostfromaddr(backend)
            host = backend
            port = int(self.db.settings[hostname].BackendStatusPort)

        # resolve ip address from name
        reshost, resport = resolve_ip(host, port)
        if not reshost:
            raise MythDBError(MythError.DB_SETTING,
                              backend + ': BackendServerAddr')
        if not resport:
            raise MythDBError(MythError.DB_SETTING,
                              backend + ': BackendStatusPort')
        self.host = host
        self.port = port

    def getHosts(self):
        """Returns a list of unique hostnames found in the settings table."""
        return self._request('Myth/GetHosts')\
                                        .readJSON()['StringList']

    def getKeys(self):
        """Returns a list of unique keys found in the settings table."""
        return self._request('Myth/GetKeys')\
                                        .readJSON()['StringList']

    def getSetting(self, key, hostname=None, default=None):
        """Retrieves a setting from the backend."""
        args = {'Key': key}
        if hostname:
            args['HostName'] = hostname
        if default:
            args['Default'] = default
        return self._request('Myth/GetSetting', **args)\
                                        .readJSON()['String']

    def getProgramGuide(self, starttime, endtime, startchan, numchan=None):
        """
        Returns a list of Guide objects corresponding to the given time period.
        """
        starttime = datetime.duck(starttime)
        endtime = datetime.duck(endtime)
        args = {
            'StartTime': starttime.utcisoformat().rsplit('.', 1)[0],
            'EndTime': endtime.utcisoformat().rsplit('.', 1)[0],
            'StartChanId': startchan,
            'Details': '1'
        }
        if numchan:
            args['NumOfChannels'] = numchan
        else:
            args['NumOfChannels'] = '1'

        dat = self._request('Guide/GetProgramGuide', **args).readJSON()
        for chan in dat['ProgramGuide']['Channels']:
            for prog in chan['Programs']:
                prog['ChanId'] = chan['ChanId']
                yield Guide.fromJSON(prog, self.db)

    def getProgramDetails(self, chanid, starttime):
        """
        Returns a Program object for the matching show.
        """
        starttime = datetime.duck(starttime)
        args = {'ChanId': chanid, 'StartTime': starttime.utcisoformat()}
        return Program.fromJSON(
                self._request('Guide/GetProgramDetails', **args)\
                    .readJSON()['Program'],
                db=self.db)

    def getChannelIcon(self, chanid):
        """Returns channel icon as a data string"""
        return self._request('Guide/GetChannelIcon', ChanId=chanid).read()

    def getRecorded(self, descending=True):
        """
        Returns a list of Program objects for recorded shows on the backend.
        """
        descendingstr = 'true' if descending else 'false'
        for prog in self._request('Dvr/GetRecordedList', Descending=descendingstr)\
                    .readJSON()['ProgramList']['Programs']:
            yield Program.fromJSON(prog, self.db)

    def getExpiring(self):
        """
        Returns a list of Program objects for expiring shows on the backend.
        """
        for prog in self._request('Dvr/GetExpiringList')\
                    .readJSON()['ProgramList']['Programs']:
            yield Program.fromJSON(prog, self.db)


#    def getInternetSources(self):
#        for grabber in self._queryTree('GetInternetSources').\
#                        find('InternetContent').findall('grabber'):
#            yield InternetSource.fromEtree(grabber, self)

    def getInternetContentUrl(self, grabber, videocode):
        return "mythflash://%s:%s/InternetContent/GetInternetContent?Grabber=%s&videocode=%s" \
            % (self.host, self.port, grabber, videocode)

    def getPreviewImage(self, chanid, starttime, width=None, \
                                                 height=None, secsin=None):
        starttime = datetime.duck(starttime)
        args = {'ChanId': chanid, 'StartTime': starttime.utcisoformat()}
        if width: args['Width'] = width
        if height: args['Height'] = height
        if secsin: args['SecsIn'] = secsin

        return self._request('Content/GetPreviewImage', **args).read()
Exemple #2
0
class BECache( object ):
    """
    BECache(backend=None, noshutdown=False, db=None)
                                            -> MythBackend connection object

    Basic class for mythbackend socket connections.
    Offers connection caching to prevent multiple connections.

    'backend' allows a hostname or IP address to connect to. If not provided,
                connect will be made to the master backend. Port is always
                taken from the database.
    'db' allows an existing database object to be supplied.
    'noshutdown' specified whether the backend will be allowed to go into
                automatic shutdown while the connection is alive.

    Available methods:
        backendCommand()    - Sends a formatted command to the backend
                              and returns the response.
    """

    class _ConnHolder( object ):
        blockshutdown = 0
        command = None
        event = None

    logmodule = 'Python Backend Connection'
    _shared = weakref.WeakValueDictionary()
    _reip = re.compile(r'(?:\d{1,3}\.){3}\d{1,3}')

    def __repr__(self):
        return "<%s 'myth://%s:%d/' at %s>" % \
                (str(self.__class__).split("'")[1].split(".")[-1],
                 self.hostname, self.port, hex(id(self)))

    def __init__(self, backend=None, blockshutdown=False, events=False, db=None):
        self.db = DBCache(db)
        self.log = MythLog(self.logmodule, db=self.db)
        self.hostname = None

        self.sendcommands = True
        self.blockshutdown = blockshutdown
        self.receiveevents = events

        if backend is None:
            # use master backend
            backend = self.db.getMasterBackend()
        else:
            backend = backend.strip('[]')

        # assume backend is hostname from settings
        host = self.db._getpreferredaddr(backend)
        if host:
            port = int(self.db.settings[backend].BackendServerPort)
            self.hostname = backend
        else:
            # assume ip address
            self.hostname = self.db._gethostfromaddr(backend)
            host = backend
            port = int(self.db.settings[self.hostname].BackendServerPort)

        # resolve ip address from name
        reshost, resport = resolve_ip(host,port)
        if not reshost:
            raise MythDBError(MythError.DB_SETTING,
                                backend+': BackendServerAddr')
        if not resport:
            raise MythDBError(MythError.DB_SETTING,
                                backend+': BackendServerPort')

        self.host = host
        self.port = port

        self._ident = '%s:%d' % (self.host, self.port)
        if self._ident in self._shared:
            # existing connection found
            self._conn = self._shared[self._ident]
            if self.sendcommands:
                if self._conn.command is None:
                    self._conn.command = self._newcmdconn()
                elif self.blockshutdown:
                    # upref block of shutdown
                    # issue command to backend if needed
                    self._conn.blockshutdown += 1
                    if self._conn.blockshutdown == 1:
                        self._conn.command.blockShutdown()
            if self.receiveevents:
                if self._conn.event is None:
                    self._conn.event = self._neweventconn()
        else:
            # no existing connection, create new
            self._conn = self._ConnHolder()

            if self.sendcommands:
                self._conn.command = self._newcmdconn()
                if self.blockshutdown:
                    self._conn.blockshutdown = 1
            if self.receiveevents:
                self._conn.event = self._neweventconn()

            self._shared[self._ident] = self._conn

        self._events = self._listhandlers()
        for func in self._events:
            self.registerevent(func)

    def __del__(self):
        # downref block of shutdown
        # issue command to backend if needed
        #print 'destructing BECache'
        if self.blockshutdown:
            self._conn.blockshutdown -= 1
            if not self._conn.blockshutdown:
                self._conn.command.unblockShutdown()

    def _newcmdconn(self):
        return BEConnection(self.host, self.port, self.db.gethostname(),
                            self.blockshutdown)

    def _neweventconn(self):
        return BEEventConnection(self.host, self.port, self.db.gethostname())

    def backendCommand(self, data):
        """
        obj.backendCommand(data) -> response string

        Sends a formatted command via a socket to the mythbackend.
        """
        if self._conn.command is None:
            return ""
        return self._conn.command.backendCommand(data)

    def _listhandlers(self):
        return []

    def registerevent(self, func, regex=None):
        if self._conn.event is None:
            return
        if regex is None:
            regex = func()
        self._conn.event.registerevent(regex, func)

    def clearevents(self):
        self._events = []