Ejemplo n.º 1
0
def detect_channels():
    """
    Auto detect a list of possible channels in the xmltv file
    """
    import codecs
    import cPickle, pickle

    file = XMLTV_FILE
    path = FREEVO_CACHEDIR
    pfile = 'xmltv_channels.pickle'

    pname = os.path.join(path, pfile)

    if not os.path.isfile(file):
        if not HELPER:
            print
            print 'Error: can\'t find %s' % file
            print 'Use xmltv to create this file or when you don\'t want to use the tv'
            print 'module at all, add TV_CHANNELS = [] and plugin.remove(\'tv\') to your'
            print 'local_conf.py. TVguide is deactivated now.'
            print
        return []

    elif os.path.isfile(pname) and (os.path.getmtime(pname) >
                                    os.path.getmtime(file)):
        try:
            f = open(pname, 'r')
            try:
                data = cPickle.load(f)
            except:
                data = pickle.load(f)
            f.close()
            return data
        except:
            print 'Error: unable to read cachefile %s' % pname
            return []

    else:
        from tv import xmltv
        input = open(file, 'r')
        tmp = open('/tmp/xmltv_parser', 'w')
        while (1):
            line = input.readline()
            if not line:
                break
            if line.find('<programme') > 0:
                tmp.write('</tv>\n')
                break
            tmp.write(line)

        input.close()
        tmp.close()

        tmp = open('/tmp/xmltv_parser', 'r')
        xmltv_channels = xmltv.read_channels(tmp)
        tmp.close()

        xmltv_channels = sortchannels(xmltv_channels, 'display-name')
        chanlist = []

        for a in xmltv_channels:
            if (a['display-name'][1][0][0].isdigit()):
                display_name = a['display-name'][0][0].encode(LOCALE, 'ignore')
                tunerid = string.split(a['display-name'][1][0].encode(
                    LOCALE, 'ignore'))[0]
            else:
                display_name = a['display-name'][1][0].encode(LOCALE, 'ignore')
                tunerid = string.split(a['display-name'][0][0].encode(
                    LOCALE, 'ignore'))[0]
            id = a['id'].encode(LOCALE, 'ignore')

            chanlist += [(id, display_name, tunerid)]

        f = lambda a, b: cmp(int(a[2]), int(b[2]))
        chanlist.sort(f)

        try:
            if os.path.isfile(pname):
                os.unlink(pname)
            f = open(pname, 'w')
            cPickle.dump(chanlist, f, 1)
            f.close()
        except IOError:
            print 'Error: unable to save to cachefile %s' % pname

        for c in chanlist:
            if c[2] == 0:
                print_list = 1
                if not HELPER:
                    print
                    print 'Error: XMLTV auto detection failed'
                    print 'Some channels in the channel list have no station id. Please add'
                    print 'it by putting the list in your local_conf.py. Start '
                    print '\'freevo tv_grab --help\' for more informations'
                    print
                break
        else:
            print 'XMTV: Auto-detected channel list'

        return chanlist
Ejemplo n.º 2
0
import urllib2
import cStringIO
import kaa.imlib2 as imlib2

import config
from tv import xmltv

# Check if the logos directory exists, if not, make it before
# proceeding

if not os.path.isdir(config.TV_LOGOS):
    print "Logo directory does not exist\n"
    print "Creating: %s\n" % (config.TV_LOGOS)
    os.mkdir(config.TV_LOGOS)

x = xmltv.read_channels(open(config.XMLTV_FILE))

for i in x:
    try:
        imgsrc = i['icon'][0]['src']
    except KeyError:
        imgsrc = None
    channel = i['id']
    #print '%s - %s' % (imgsrc, channel)
    if imgsrc:
        try:
            img = imlib2.open_from_memory(urllib2.urlopen(str(imgsrc)).read())
            # Convert the image into a PNG and save to logos directory
            output_file = config.TV_LOGOS + '/' + channel + '.png'
            try:
                img.save(output_file)
Ejemplo n.º 3
0
import urllib2
import cStringIO
import kaa.imlib2 as imlib2

import config
from tv import xmltv

# Check if the logos directory exists, if not, make it before
# proceeding

if not os.path.isdir(config.TV_LOGOS):
    print "Logo directory does not exist\n"
    print "Creating: %s\n" % (config.TV_LOGOS)
    os.mkdir(config.TV_LOGOS)

x = xmltv.read_channels(open(config.XMLTV_FILE))

for i in x:
    try:
        imgsrc = i['icon'][0]['src']
    except KeyError:
        imgsrc = None
    channel = i['id']
    #print '%s - %s' % (imgsrc, channel)
    if imgsrc:
        try:
            img = imlib2.open_from_memory(urllib2.urlopen(str(imgsrc)).read())
            # Convert the image into a PNG and save to logos directory
            output_file = config.TV_LOGOS + '/' + channel + '.png'
            try:
                img.save(output_file)
Ejemplo n.º 4
0
def load_guide(XMLTV_FILE=None, popup_dialog=None):
    """
    Load a guide from the raw XMLTV file using the xmltv.py support lib.
    Returns a TvGuide or None if an error occurred
    """
    if not XMLTV_FILE:
        XMLTV_FILE = config.XMLTV_FILE

    # Create a new guide
    guide = TvGuide()

    # Is there a file to read from?
    if os.path.isfile(XMLTV_FILE):
        gotfile = 1
        guide.timestamp = os.path.getmtime(XMLTV_FILE)
    else:
        logger.debug('XMLTV file (%s) missing!', XMLTV_FILE)
        gotfile = 0
    if popup_dialog:
        popup_dialog.update_progress(_('Reading channels'), 0.0)
    # Add the channels that are in the config list, or all if the
    # list is empty
    if config.TV_CHANNELS:
        logger.debug('Only adding channels in TV_CHANNELS to TvGuide')

        for data in config.TV_CHANNELS:
            (id, displayname, tunerid) = data[:3]
            c = TvChannel(id, displayname, tunerid)

            # Handle the optional time-dependent station info
            c.times = []
            if len(data) > 3 and len(data[3:4]) == 3:
                for (days, start_time, stop_time) in data[3:4]:
                    c.times.append((days, int(start_time), int(stop_time)))
            guide.add_channel(c)


    else: # Add all channels in the XMLTV file
        logger.debug('Adding all channels to TvGuide')

        xmltv_channels = None
        if gotfile:
            # Don't read the channel info unless we have to, takes a long time!
            xmltv_channels = xmltv.read_channels(util.gzopen(XMLTV_FILE))

        # Was the guide read successfully?
        if not xmltv_channels:
            return None     # No

        for chan in xmltv_channels:
            id = chan['id'].encode(config.LOCALE, 'ignore')
            if ' ' in id:
                # Assume the format is "TUNERID CHANNELNAME"
                tunerid = id.split()[0]       # XXX Educated guess
                displayname = id.split()[1]   # XXX Educated guess
            else:
                display_name = chan['display-name'][0][0]
                if ' ' in display_name:
                    tunerid = display_name.split()[0]
                    displayname = display_name.split()[1]
                else:
                    tunerid = _('REPLACE WITH TUNERID FOR %s') % display_name
                    displayname = display_name

            c = TvChannel(id, displayname, tunerid)
            guide.add_channel(c)

    if popup_dialog:
        popup_dialog.update_progress(_('Reading programmes'), 0.25)

    xmltv_programs = None
    if gotfile:
        logger.debug('reading \"%s\" xmltv data', XMLTV_FILE)
        f = util.gzopen(XMLTV_FILE)
        xmltv_programs = xmltv.read_programmes(f)
        f.close()

    # Was the guide read successfully?
    if not xmltv_programs:
        return guide    # Return the guide, it has the channels at least...

    needed_ids = []
    for chan in guide.chan_dict:
        needed_ids.append(chan)

    logger.debug('creating guide for %s', needed_ids)
    if popup_dialog:
        popup_dialog.update_progress(_('Processing programmes'), 0.50)
    for p in xmltv_programs:
        if not p['channel'] in needed_ids:
            continue
        try:
            channel_id = p['channel']
            date = 'date' in p and Unicode(p['date']) or ''
            start = ''
            pdc_start = ''
            stop = ''
            title = Unicode(p['title'][0][0])
            desc = 'desc' in p and Unicode(util.format_text(p['desc'][0][0])) or ''
            sub_title = 'sub-title' in p and Unicode(p['sub-title'][0][0]) or ''
            categories = 'category' in p and [ cat[0] for cat in p['category'] ] or ''
            advisories = []
            ratings = {}

            # Add credits to the description
            if 'credits' in p:
                desc += Unicode('\n\n')
                desc += _('Credits :\n')
                credits = p['credits']
                if 'actor' in credits:
                    desc += Unicode('\n')
                    desc += _('Actors :\n')
                    for actor in credits['actor']:
                        desc += Unicode(actor + '\n')
                if 'director' in credits:
                    desc += Unicode('\n')
                    directors = credits['director']
                    if len(directors) == 1:
                        desc += _('Director : %s') % directors[0]
                    else:
                        desc += _('Directors :\n')
                        for d in directors:
                            desc += Unicode(d + '\n')

            if 'rating' in p:
                for r in p['rating']:
                    if r.get('system') == 'advisory':
                        advisories.append(String(r.get('value')))
                        continue
                    ratings[String(r.get('system'))] = String(r.get('value'))
            try:
                start = timestr2secs_utc(p['start'])
                pdc_start = 'pdc_start' in p and timestr2secs_utc(p['pdc_start']) or start
                try:
                    stop = timestr2secs_utc(p['stop'])
                except:
                    # Fudging end time
                    stop = timestr2secs_utc(p['start'][0:8] + '235900' + p['start'][14:18])
            except EpgException, why:
                logger.warning('EpgException: %s', why)
                continue

            # fix bad German titles to make favorites work
            if title.endswith('. Teil'):
                title = title[:-6]
                if title.rfind(' ') > 0:
                    try:
                        part = int(title[title.rfind(' ')+1:])
                        title = title[:title.rfind(' ')].rstrip()
                        if sub_title:
                            sub_title = u'Teil %s: %s' % (part, sub_title)
                        else:
                            sub_title = u'Teil %s' % part
                    except Exception, e:
                        print 'Teil:', e

            prog = TvProgram(channel_id, start, pdc_start, stop, title, sub_title, desc, categories, ratings)
            prog.advisories = advisories
            prog.date = date
            guide.add_program(prog)
Ejemplo n.º 5
0
def load_guide(verbose=True, XMLTV_FILE=None):
    """
    Load a guide from the raw XMLTV file using the xmltv.py support lib.
    Returns a TvGuide or None if an error occurred
    """
    if not XMLTV_FILE:
        XMLTV_FILE = config.XMLTV_FILE

    # Create a new guide
    guide = epg_types.TvGuide()

    # Is there a file to read from?
    if os.path.isfile(XMLTV_FILE):
        gotfile = 1
        guide.timestamp = os.path.getmtime(XMLTV_FILE)
    else:
        _debug_('XMLTV file (%s) missing!' % XMLTV_FILE)
        gotfile = 0

    # Add the channels that are in the config list, or all if the
    # list is empty
    if config.TV_CHANNELS:
        if verbose:
            _debug_('epg_xmltv.py: Only adding channels in list')

        for data in config.TV_CHANNELS:
            (id, disp, tunerid) = data[:3]
            c = epg_types.TvChannel()
            c.id = id
            c.displayname = disp
            c.tunerid = tunerid

            # Handle the optional time-dependent station info
            c.times = []
            if len(data) > 3 and len(data[3:4]) == 3:
                for (days, start_time, stop_time) in data[3:4]:
                    c.times.append((days, int(start_time), int(stop_time)))
            guide.AddChannel(c)

    else:  # Add all channels in the XMLTV file
        if verbose:
            _debug_('epg_xmltv.py: Adding all channels')
        xmltv_channels = None
        if gotfile:
            # Don't read the channel info unless we have to, takes a long time!
            xmltv_channels = xmltv.read_channels(util.gzopen(XMLTV_FILE))

        # Was the guide read successfully?
        if not xmltv_channels:
            return None  # No

        for chan in xmltv_channels:
            id = chan['id'].encode(config.LOCALE, 'ignore')
            c = epg_types.TvChannel()
            c.id = id
            if ' ' in id:
                # Assume the format is "TUNERID CHANNELNAME"
                c.displayname = id.split()[1]  # XXX Educated guess
                c.tunerid = id.split()[0]  # XXX Educated guess
            else:
                displayname = chan['display-name'][0][0]
                if ' ' in displayname:
                    c.displayname = displayname.split()[1]
                    c.tunerid = displayname.split()[0]
                else:
                    c.displayname = displayname
                    c.tunerid = _('REPLACE WITH TUNERID FOR %s') % displayname

            guide.AddChannel(c)

    xmltv_programs = None
    if gotfile:
        if verbose:
            _debug_('reading \"%s\" xmltv data' % XMLTV_FILE)
        f = util.gzopen(XMLTV_FILE)
        xmltv_programs = xmltv.read_programmes(f)
        f.close()

    # Was the guide read successfully?
    if not xmltv_programs:
        return guide  # Return the guide, it has the channels at least...

    needed_ids = []
    for chan in guide.chan_dict:
        needed_ids.append(chan)

    if verbose:
        _debug_('creating guide for %s' % needed_ids)

    for p in xmltv_programs:
        if not p['channel'] in needed_ids:
            continue
        try:
            prog = epg_types.TvProgram()
            prog.channel_id = p['channel']
            prog.title = Unicode(p['title'][0][0])
            if p.has_key('date'):
                prog.date = Unicode(p['date'])
            if p.has_key('category'):
                prog.categories = [cat[0] for cat in p['category']]
            if p.has_key('rating'):
                for r in p['rating']:
                    if r.get('system') == 'advisory':
                        prog.advisories.append(String(r.get('value')))
                        continue
                    prog.ratings[String(r.get('system'))] = String(
                        r.get('value'))
            if p.has_key('desc'):
                prog.desc = Unicode(util.format_text(p['desc'][0][0]))
            if p.has_key('sub-title'):
                prog.sub_title = p['sub-title'][0][0]
            try:
                prog.start = timestr2secs_utc(p['start'])
                if p.has_key('pdc_start'):
                    prog.pdc_start = timestr2secs_utc(p['pdc_start'])
                else:
                    prog.pdc_start = prog.start
                try:
                    prog.stop = timestr2secs_utc(p['stop'])
                except:
                    # Fudging end time
                    prog.stop = timestr2secs_utc(p['start'][0:8] + '235900' + \
                                                 p['start'][14:18])
            except EPG_TIME_EXC:
                continue
            # fix bad German titles to make favorites working
            if prog.title.endswith('. Teil'):
                prog.title = prog.title[:-6]
                if prog.title.rfind(' ') > 0:
                    try:
                        part = int(prog.title[prog.title.rfind(' ') + 1:])
                        prog.title = prog.title[:prog.title.rfind(' ')].rstrip(
                        )
                        if prog.sub_title:
                            prog.sub_title = u'Teil %s: %s' % (part,
                                                               prog.sub_title)
                        else:
                            prog.sub_title = u'Teil %s' % part
                    except Exception, e:
                        print 'Teil:', e

            guide.AddProgram(prog)
        except: