def get_epg_data(self):
        """Return EPG data"""
        now = datetime.now(dateutil.tz.tzlocal())

        epg_data = {}
        for date in ['yesterday', 'today', 'tomorrow']:
            epg = self.parse(date, now)
            epg_url = epg.strftime(self.VRT_TVGUIDE)
            schedule = get_url_json(url=epg_url, fail={})
            for channel_id, episodes in list(schedule.items()):
                channel = find_entry(CHANNELS, 'id', channel_id)
                epg_id = channel.get('epg_id')
                if epg_id not in epg_data:
                    epg_data[epg_id] = []
                for episode in episodes:
                    if episode.get('url') and episode.get('vrt.whatson-id'):
                        path = url_for(
                            'play_whatson_id',
                            whatson_id=episode.get('vrt.whatson-id'))
                    else:
                        path = None
                    epg_data[epg_id].append(
                        dict(
                            start=episode.get('startTime'),
                            stop=episode.get('endTime'),
                            image=add_https_proto(episode.get('image', '')),
                            title=episode.get('title'),
                            subtitle=html_to_kodi(episode.get('subtitle', '')),
                            description=html_to_kodi(
                                episode.get('description', '')),
                            stream=path,
                        ))
        return epg_data
    def get_plotoutline(api_data, season=False):
        """Get plotoutline string from single item json api data"""
        # VRT NU Search API
        if api_data.get('type') == 'episode':
            if season is not False:
                plotoutline = html_to_kodi(
                    api_data.get('programDescription', ''))
                return plotoutline

            if api_data.get('displayOptions', {}).get('showShortDescription'):
                plotoutline = html_to_kodi(api_data.get(
                    'shortDescription', ''))
                return plotoutline

            plotoutline = html_to_kodi(api_data.get('subtitle'))
            return plotoutline

        # VRT NU Suggest API
        if api_data.get('type') == 'program':
            return ''

        # VRT NU Schedule API (some are missing vrt.whatson-id)
        if api_data.get('vrt.whatson-id') or api_data.get('startTime'):
            return html_to_kodi(
                api_data.get('shortDescription', '')
                or api_data.get('subtitle', ''))

        # Not Found
        return ''
    def get_title(api_data, season=False):
        """Get an appropriate video title"""

        if season is not False:
            title = '%s %s' % (localize(30131), season)  # Season X
            return title

        # VRT NU Search API
        if api_data.get('type') == 'episode':
            title = html_to_kodi(
                api_data.get('title')
                or api_data.get('shortDescription', '???'))

        # VRT NU Suggest API
        elif api_data.get('type') == 'program':
            title = api_data.get('title', '???')

        # VRT NU Schedule API (some are missing vrt.whatson-id)
        elif api_data.get('vrt.whatson-id') or api_data.get('startTime'):
            title = html_to_kodi(api_data.get('subtitle', '???'))

        return title
Esempio n. 4
0
    def __map_episodes(self,
                       episodes,
                       titletype=None,
                       season=None,
                       use_favorites=False,
                       cache_file=None):
        """Construct a list of TV show episodes TitleItems based on Search API query and filtered by favorites"""
        episode_items = []
        sort = 'episode'
        ascending = True
        content = 'episodes'

        if use_favorites:
            favorite_programs = self._favorites.programs()

        for episode in episodes:
            # VRT API workaround: seasonTitle facet behaves as a partial match regex,
            # so we have to filter out the episodes from seasons that don't exactly match.
            if season and season != 'allseasons' and episode.get(
                    'seasonTitle') != season:
                continue

            program = url_to_program(episode.get('programUrl'))
            if use_favorites and program not in favorite_programs:
                continue

            # Support search highlights
            highlight = episode.get('highlight')
            if highlight:
                for key in highlight:
                    episode[key] = html_to_kodi(highlight.get(key)[0])

            list_item, sort, ascending = self.episode_to_listitem(
                episode, program, cache_file, titletype)
            episode_items.append(list_item)

        return episode_items, sort, ascending, content
Esempio n. 5
0
 def get_epg_data(self):
     """Return EPG data"""
     epg_data = dict()
     epg_url = self.WEEK_SCHEDULE
     schedule = get_url_json(
         url=epg_url,
         headers=dict(
             accept='application/vnd.epg.vrt.be.schedule_3.1+json'),
         fail={})
     for event in schedule.get('events', []):
         channel_id = event.get('channel', dict(code=None)).get('code')
         if channel_id is None:
             log(2,
                 'No channel code found in EPG event: {event}',
                 event=event)
             continue
         channel = find_entry(CHANNELS, 'id', channel_id)
         if channel is None:
             log(2, 'No channel found using code: {code}', code=channel_id)
             continue
         epg_id = channel.get('epg_id')
         if epg_id not in epg_data:
             epg_data[epg_id] = []
         if event.get('images'):
             image = event.get('images')[0].get('url')
         else:
             image = None
         epg_data[epg_id].append(
             dict(
                 start=event.get('startTime'),
                 stop=event.get('endTime'),
                 image=image,
                 title=event.get('title'),
                 description=html_to_kodi(event.get('description', '')),
             ))
     return epg_data
    def get_label(api_data, titletype=None, return_sort=False):
        """Get an appropriate label string matching the type of listing and VRT NU provided displayOptions from single item json api data"""

        # VRT NU Search API
        if api_data.get('type') == 'episode':
            display_options = api_data.get('displayOptions', {})

            # NOTE: Hard-code showing seasons because it is unreliable (i.e; Thuis or Down the Road have it disabled)
            display_options['showSeason'] = True

            program_type = api_data.get('programType')
            if not titletype:
                titletype = program_type

            if display_options.get('showEpisodeTitle'):
                label = html_to_kodi(
                    api_data.get('title', '')
                    or api_data.get('shortDescription', ''))
            elif display_options.get('showShortDescription'):
                label = html_to_kodi(
                    api_data.get('shortDescription', '')
                    or api_data.get('title', ''))
            else:
                label = html_to_kodi(
                    api_data.get('title', '')
                    or api_data.get('shortDescription', ''))

            sort = 'unsorted'
            ascending = True

            if titletype in ('continue', 'offline', 'recent', 'watchlater'):
                ascending = False
                label = '[B]%s[/B] - %s' % (api_data.get('program'), label)
                sort = 'dateadded'

            elif titletype in ('reeksaflopend', 'reeksoplopend'):

                if titletype == 'reeksaflopend':
                    ascending = False

                # NOTE: This is disable on purpose as 'showSeason' is not reliable
                if (display_options.get('showSeason') is False
                        and display_options.get('showEpisodeNumber')
                        and api_data.get('seasonName')
                        and api_data.get('episodeNumber')):
                    try:
                        label = 'S%02dE%02d: %s' % (
                            int(api_data.get('seasonName')),
                            int(api_data.get('episodeNumber')), label)
                    except ValueError:
                        # Season may not always be a perfect number
                        sort = 'episode'
                    else:
                        sort = 'dateadded'
                elif display_options.get('showEpisodeNumber') and api_data.get(
                        'episodeNumber') and ascending:
                    # NOTE: Do not prefix with "Episode X" when sorting by episode
                    # label = '%s %s: %s' % (localize(30132), api_data.get('episodeNumber'), label)
                    sort = 'episode'
                elif display_options.get('showBroadcastDate') and api_data.get(
                        'formattedBroadcastShortDate'):
                    label = '%s - %s' % (
                        api_data.get('formattedBroadcastShortDate'), label)
                    sort = 'dateadded'
                else:
                    sort = 'dateadded'

            elif titletype == 'daily':
                ascending = False
                label = '%s - %s' % (
                    api_data.get('formattedBroadcastShortDate'), label)
                sort = 'dateadded'

            elif titletype == 'oneoff':
                label = api_data.get('program', label)
                sort = 'label'

        # VRT NU Suggest API
        elif api_data.get('type') == 'program':
            label = api_data.get('title', '???')

        # VRT NU Schedule API (some are missing vrt.whatson-id)
        elif api_data.get('vrt.whatson-id') or api_data.get('startTime'):
            title = html_to_kodi(
                api_data.get('subtitle', '')
                or api_data.get('shortDescription', ''))
            label = '{start} - [B]{program}[/B]{title}'.format(
                start=api_data.get('start'),
                program=api_data.get('title'),
                title=' - ' + title if title else '',
            )

        # Not Found
        else:
            label = ''

        if return_sort:
            return colour(label), sort, ascending

        return colour(label)
    def get_plot(self, api_data, season=False, date=None):
        """Get plot string from single item json api data"""
        from datetime import datetime
        import dateutil.parser
        import dateutil.tz

        # VRT NU Search API
        if api_data.get('type') == 'episode':
            if season is not False:
                plot = html_to_kodi(api_data.get('programDescription', ''))

                # Add additional metadata to plot
                plot_meta = ''
                if api_data.get('allowedRegion') == 'BE':
                    plot_meta += localize(30201) + '\n\n'  # Geo-blocked
                plot = '%s[B]%s[/B]\n%s' % (plot_meta, api_data.get('program'),
                                            plot)
                return colour(plot)

            # Add additional metadata to plot
            plot_meta = ''
            # Only display when a video disappears if it is within the next 3 months
            if api_data.get('assetOffTime'):
                offtime = dateutil.parser.parse(api_data.get('assetOffTime'))

                # Show the remaining days/hours the episode is still available
                if offtime:
                    now = datetime.now(dateutil.tz.tzlocal())
                    remaining = offtime - now
                    if remaining.days / 365 > 5:
                        pass  # If it is available for more than 5 years, do not show
                    elif remaining.days / 365 > 2:
                        plot_meta += localize(
                            30202, years=int(remaining.days /
                                             365))  # X years remaining
                    elif remaining.days / 30.5 > 3:
                        plot_meta += localize(
                            30203, months=int(remaining.days /
                                              30.5))  # X months remaining
                    elif remaining.days > 1:
                        plot_meta += localize(
                            30204, days=remaining.days)  # X days to go
                    elif remaining.days == 1:
                        plot_meta += localize(30205)  # 1 day to go
                    elif remaining.seconds // 3600 > 1:
                        plot_meta += localize(30206,
                                              hours=remaining.seconds //
                                              3600)  # X hours to go
                    elif remaining.seconds // 3600 == 1:
                        plot_meta += localize(30207)  # 1 hour to go
                    else:
                        plot_meta += localize(30208,
                                              minutes=remaining.seconds //
                                              60)  # X minutes to go

            if api_data.get('allowedRegion') == 'BE':
                if plot_meta:
                    plot_meta += '  '
                plot_meta += localize(30201)  # Geo-blocked

            # Add product placement
            if api_data.get('productPlacement') is True:
                if plot_meta:
                    plot_meta += '  '
                plot_meta += '[B]PP[/B]'

            # Add film rating
            rating = self.get_mpaa(api_data)
            if rating:
                if plot_meta:
                    plot_meta += '  '
                plot_meta += '[B]%s[/B]' % rating

            plot = html_to_kodi(api_data.get('description', ''))

            if plot_meta:
                plot = '%s\n\n%s' % (plot_meta, plot)

            permalink = shorten_link(
                api_data.get('permalink')) or api_data.get('externalPermalink')
            if permalink and get_setting_bool('showpermalink', default=False):
                plot = '%s\n\n[COLOR={highlighted}]%s[/COLOR]' % (plot,
                                                                  permalink)
            return colour(plot)

        # VRT NU Suggest API
        if api_data.get('type') == 'program':
            plot = unescape(api_data.get('description', '???'))
            # permalink = shorten_link(api_data.get('programUrl'))
            # if permalink and get_setting_bool('showpermalink', default=False):
            #     plot = '%s\n\n[COLOR={highlighted}]%s[/COLOR]' % (plot, permalink)
            return colour(plot)

        # VRT NU Schedule API (some are missing vrt.whatson-id)
        if api_data.get('vrt.whatson-id') or api_data.get('startTime'):
            now = datetime.now(dateutil.tz.tzlocal())
            epg = self.parse(date, now)
            plot = '[B]{datelong}[/B]\n{start} - {end}\n\n{description}'.format(
                datelong=localize_datelong(epg),
                start=api_data.get('start'),
                end=api_data.get('end'),
                description=html_to_kodi(api_data.get('description', '')),
            )
            return colour(plot)

        # Not Found
        return ''