class Metadata:
    """ Code responsible for the refreshing of the metadata """
    def __init__(self):
        """ Initialise object """
        self._auth = Auth(kodiutils.get_setting('username'),
                          kodiutils.get_setting('password'),
                          kodiutils.get_setting('loginprovider'),
                          kodiutils.get_setting('profile'),
                          kodiutils.get_tokens_path())
        self._api = Api(self._auth)

    def update(self):
        """ Update the metadata with a foreground progress indicator """
        # Create progress indicator
        progress = kodiutils.progress(
            message=kodiutils.localize(30715))  # Updating metadata

        def update_status(i, total):
            """ Update the progress indicator """
            progress.update(
                int(((i + 1) / total) * 100),
                kodiutils.localize(
                    30716, index=i + 1,
                    total=total))  # Updating metadata ({index}/{total})
            return progress.iscanceled()

        self.fetch_metadata(callback=update_status)

        # Close progress indicator
        progress.close()

    def fetch_metadata(self, callback=None):
        """ Fetch the metadata for all the items in the catalog
        :type callback: callable
        """
        # Fetch all items from the catalog
        items = self._api.get_items()
        count = len(items)

        # Loop over all of them and download the metadata
        for index, item in enumerate(items):
            if isinstance(item, Movie):
                self._api.get_movie(item.movie_id)
            elif isinstance(item, Program):
                self._api.get_program(item.program_id)

            # Run callback after every item
            if callback and callback(index, count):
                # Stop when callback returns False
                return False

        return True

    @staticmethod
    def clean():
        """ Clear metadata (called from settings) """
        kodiutils.invalidate_cache()
        kodiutils.set_setting('metadata_last_updated', '0')
        kodiutils.ok_dialog(
            message=kodiutils.localize(30714))  # Local metadata is cleared
 def __init__(self):
     """ Initialise object """
     self._auth = Auth(kodiutils.get_setting('username'),
                       kodiutils.get_setting('password'),
                       kodiutils.get_setting('loginprovider'),
                       kodiutils.get_setting('profile'),
                       kodiutils.get_tokens_path())
     self._api = Api(self._auth)
class Search:
    """ Menu code related to search """

    def __init__(self,):
        """ Initialise object """
        self._auth = Auth(kodiutils.get_setting('username'),
                          kodiutils.get_setting('password'),
                          kodiutils.get_setting('loginprovider'),
                          kodiutils.get_setting('profile'),
                          kodiutils.get_tokens_path())
        self._api = Api(self._auth)

    def show_search(self, query=None):
        """ Shows the search dialog.

        :type query: str
        """
        if not query:
            # Ask for query
            query = kodiutils.get_search_string(heading=kodiutils.localize(30009))  # Search Streamz
            if not query:
                kodiutils.end_of_directory()
                return

        # Do search
        try:
            items = self._api.do_search(query)
        except Exception as ex:  # pylint: disable=broad-except
            kodiutils.notification(message=str(ex))
            kodiutils.end_of_directory()
            return

        # Display results
        listing = []
        for item in items:
            listing.append(Menu.generate_titleitem(item))

        # Sort like we get our results back.
        kodiutils.show_listing(listing, 30009, content='tvshows')
示例#4
0
 def __init__(self, ):
     """ Initialise object """
     auth = Auth(kodiutils.get_tokens_path())
     self._api = Api(auth.get_tokens())
示例#5
0
class Catalog:
    """ Menu code related to the catalog """
    def __init__(self):
        """ Initialise object """
        auth = Auth(kodiutils.get_tokens_path())
        self._api = Api(auth.get_tokens())

    def show_program(self, program):
        """ Show a program from the catalog.

        :type program: str
         """
        try:
            program_obj = self._api.get_program(
                program, cache=CACHE_PREVENT
            )  # Use CACHE_PREVENT since we want fresh data
        except UnavailableException:
            kodiutils.ok_dialog(
                message=kodiutils.localize(30712)
            )  # The video is unavailable and can't be played right now.
            kodiutils.end_of_directory()
            return

        # Go directly to the season when we have only one season
        if len(program_obj.seasons) == 1:
            self.show_program_season(
                program,
                list(program_obj.seasons.values())[0].number)
            return

        # studio = CHANNELS.get(program_obj.channel, {}).get('studio_icon')

        listing = []

        # Add an '* All seasons' entry when configured in Kodi
        if kodiutils.get_global_setting('videolibrary.showallitems') is True:
            listing.append(
                TitleItem(
                    title='* %s' % kodiutils.localize(30204),  # * All seasons
                    path=kodiutils.url_for('show_catalog_program_season',
                                           program=program,
                                           season=-1),
                    art_dict=dict(
                        poster=program_obj.poster,
                        thumb=program_obj.thumb,
                        landscape=program_obj.thumb,
                        fanart=program_obj.fanart,
                    ),
                    info_dict=dict(
                        mediatype='season',
                        tvshowtitle=program_obj.name,
                        title=kodiutils.localize(30204),  # All seasons
                        tagline=program_obj.description,
                        set=program_obj.name,
                        # studio=studio,
                        mpaa=', '.join(program_obj.legal)
                        if hasattr(program_obj, 'legal') and program_obj.legal
                        else kodiutils.localize(30216),  # All ages
                    ),
                ))

        # Add the seasons
        for season in list(program_obj.seasons.values()):
            listing.append(
                TitleItem(
                    title=kodiutils.localize(
                        30205, season=season.number),  # Season {season}
                    path=kodiutils.url_for('show_catalog_program_season',
                                           program=program,
                                           season=season.number),
                    art_dict=dict(
                        poster=program_obj.poster,
                        thumb=program_obj.thumb,
                        landscape=program_obj.thumb,
                        fanart=program_obj.fanart,
                    ),
                    info_dict=dict(
                        mediatype='season',
                        tvshowtitle=program_obj.name,
                        title=kodiutils.localize(
                            30205, season=season.number),  # Season {season}
                        tagline=program_obj.description,
                        set=program_obj.name,
                        # studio=studio,
                        mpaa=', '.join(program_obj.legal)
                        if hasattr(program_obj, 'legal') and program_obj.legal
                        else kodiutils.localize(30216),  # All ages
                    ),
                ))

        # Sort by label. Some programs return seasons unordered.
        kodiutils.show_listing(listing,
                               program_obj.name,
                               content='tvshows',
                               sort=['label'])

    def show_program_season(self, program, season):
        """ Show the episodes of a program from the catalog.

        :type program: str
        :type season: int
        """
        try:
            program_obj = self._api.get_program(
                program
            )  # Use CACHE_AUTO since the data is just refreshed in show_program
        except UnavailableException:
            kodiutils.ok_dialog(
                message=kodiutils.localize(30712)
            )  # The video is unavailable and can't be played right now.
            kodiutils.end_of_directory()
            return

        if season == -1:
            # Show all seasons
            seasons = list(program_obj.seasons.values())
        else:
            # Show the season that was selected
            seasons = [program_obj.seasons[season]]

        listing = [
            Menu.generate_titleitem(e) for s in seasons
            for e in list(s.episodes.values())
        ]

        # Sort by episode number by default. Takes seasons into account.
        kodiutils.show_listing(listing,
                               program_obj.name,
                               content='episodes',
                               sort=['episode', 'duration'])

    def show_recommendations(self, storefront):
        """ Show the recommendations.

        :type storefront: str
        """
        results = self._api.get_storefront(storefront)
        show_unavailable = kodiutils.get_setting_bool(
            'interface_show_unavailable')

        listing = []
        for item in results:
            if isinstance(item, Category):
                listing.append(
                    TitleItem(
                        title=item.title,
                        path=kodiutils.url_for('show_recommendations_category',
                                               storefront=storefront,
                                               category=item.category_id),
                        info_dict=dict(plot='[B]{category}[/B]'.format(
                            category=item.title), ),
                    ))
            else:
                if show_unavailable or item.available:
                    listing.append(Menu.generate_titleitem(item))

        if storefront == STOREFRONT_SERIES:
            label = 30005  # Series
        elif storefront == STOREFRONT_MOVIES:
            label = 30003  # Movies
        else:
            label = 30015  # Recommendations

        kodiutils.show_listing(listing, label, content='files')

    def show_recommendations_category(self, storefront, category):
        """ Show the items in a recommendations category.

        :type storefront: str
        :type category: str
        """
        result = self._api.get_storefront_category(storefront, category)
        show_unavailable = kodiutils.get_setting_bool(
            'interface_show_unavailable')

        listing = []
        for item in result.content:
            if show_unavailable or item.available:
                listing.append(Menu.generate_titleitem(item))

        if storefront == STOREFRONT_SERIES:
            content = 'tvshows'
        elif storefront == STOREFRONT_MOVIES:
            content = 'movies'
        else:
            content = 'tvshows'  # Fallback to a list of tvshows

        kodiutils.show_listing(listing,
                               result.title,
                               content=content,
                               sort=['unsorted', 'label', 'year', 'duration'])

    def show_mylist(self):
        """ Show the items in "My List". """
        mylist = self._api.get_mylist()

        listing = []
        for item in mylist:
            item.my_list = True
            listing.append(Menu.generate_titleitem(item))

        # Sort categories by default like in Streamz.
        kodiutils.show_listing(listing,
                               30017,
                               content='files',
                               sort=['unsorted', 'label', 'year', 'duration'])

    def mylist_add(self, video_type, content_id):
        """ Add an item to "My List".

        :type video_type: str
        :type content_id: str
         """
        self._api.add_mylist(video_type, content_id)
        kodiutils.end_of_directory()

    def mylist_del(self, video_type, content_id):
        """ Remove an item from "My List".

        :type video_type: str
        :type content_id: str
        """
        self._api.del_mylist(video_type, content_id)
        kodiutils.end_of_directory()

    def show_continuewatching(self):
        """ Show the items in "Continue Watching". """
        category = self._api.get_storefront_category(
            STOREFRONT_MAIN, STOREFRONT_PAGE_CONTINUE_WATCHING)

        listing = []
        for item in category.content:
            titleitem = Menu.generate_titleitem(item, progress=True)

            # Add Program Name to title since this list contains episodes from multiple programs
            title = '%s - %s' % (titleitem.info_dict.get('tvshowtitle'),
                                 titleitem.info_dict.get('title'))
            titleitem.info_dict['title'] = title
            listing.append(titleitem)

        # Sort categories by default like in Streamz.
        kodiutils.show_listing(listing,
                               30019,
                               content='episodes',
                               sort='label')
示例#6
0
class Catalog:
    """ Menu code related to the catalog """

    def __init__(self):
        """ Initialise object """
        self._auth = Auth(kodiutils.get_setting('username'),
                          kodiutils.get_setting('password'),
                          kodiutils.get_setting('loginprovider'),
                          kodiutils.get_setting('profile'),
                          kodiutils.get_tokens_path())
        self._api = Api(self._auth)

    def show_catalog(self):
        """ Show the catalog. """
        categories = self._api.get_categories()

        listing = []
        for cat in categories:
            listing.append(TitleItem(
                title=cat.title,
                path=kodiutils.url_for('show_catalog_category', category=cat.category_id),
                info_dict=dict(
                    plot='[B]{category}[/B]'.format(category=cat.title),
                ),
            ))

        # Sort categories by default like in Streamz.
        kodiutils.show_listing(listing, 30003, content='files')

    def show_catalog_category(self, category=None):
        """ Show a category in the catalog.

        :type category: str
        """
        items = self._api.get_items(category)

        listing = []
        for item in items:
            listing.append(Menu.generate_titleitem(item))

        # Sort items by label, but don't put folders at the top.
        # Used for A-Z listing or when movies and episodes are mixed.
        kodiutils.show_listing(listing, 30003, content='movies' if category == 'films' else 'tvshows', sort=['label', 'year', 'duration'])

    def show_program(self, program):
        """ Show a program from the catalog.

        :type program: str
         """
        try:
            program_obj = self._api.get_program(program, cache=CACHE_PREVENT)  # Use CACHE_PREVENT since we want fresh data
        except UnavailableException:
            kodiutils.ok_dialog(message=kodiutils.localize(30712))  # The video is unavailable and can't be played right now.
            kodiutils.end_of_directory()
            return

        # Go directly to the season when we have only one season
        if len(program_obj.seasons) == 1:
            self.show_program_season(program, list(program_obj.seasons.values())[0].number)
            return

        # studio = CHANNELS.get(program_obj.channel, {}).get('studio_icon')

        listing = []

        # Add an '* All seasons' entry when configured in Kodi
        if kodiutils.get_global_setting('videolibrary.showallitems') is True:
            listing.append(TitleItem(
                title='* %s' % kodiutils.localize(30204),  # * All seasons
                path=kodiutils.url_for('show_catalog_program_season', program=program, season=-1),
                art_dict=dict(
                    thumb=program_obj.cover,
                    fanart=program_obj.cover,
                ),
                info_dict=dict(
                    tvshowtitle=program_obj.name,
                    title=kodiutils.localize(30204),  # All seasons
                    tagline=program_obj.description,
                    set=program_obj.name,
                    # studio=studio,
                    mpaa=', '.join(program_obj.legal) if hasattr(program_obj, 'legal') and program_obj.legal else kodiutils.localize(30216),  # All ages
                ),
            ))

        # Add the seasons
        for season in list(program_obj.seasons.values()):
            listing.append(TitleItem(
                title=kodiutils.localize(30205, season=season.number),  # Season {season}
                path=kodiutils.url_for('show_catalog_program_season', program=program, season=season.number),
                art_dict=dict(
                    thumb=season.cover,
                    fanart=program_obj.cover,
                ),
                info_dict=dict(
                    tvshowtitle=program_obj.name,
                    title=kodiutils.localize(30205, season=season.number),  # Season {season}
                    tagline=program_obj.description,
                    set=program_obj.name,
                    # studio=studio,
                    mpaa=', '.join(program_obj.legal) if hasattr(program_obj, 'legal') and program_obj.legal else kodiutils.localize(30216),  # All ages
                ),
            ))

        # Sort by label. Some programs return seasons unordered.
        kodiutils.show_listing(listing, 30003, content='tvshows', sort=['label'])

    def show_program_season(self, program, season):
        """ Show the episodes of a program from the catalog.

        :type program: str
        :type season: int
        """
        try:
            program_obj = self._api.get_program(program)  # Use CACHE_AUTO since the data is just refreshed in show_program
        except UnavailableException:
            kodiutils.ok_dialog(message=kodiutils.localize(30712))  # The video is unavailable and can't be played right now.
            kodiutils.end_of_directory()
            return

        if season == -1:
            # Show all seasons
            seasons = list(program_obj.seasons.values())
        else:
            # Show the season that was selected
            seasons = [program_obj.seasons[season]]

        listing = [Menu.generate_titleitem(e) for s in seasons for e in list(s.episodes.values())]

        # Sort by episode number by default. Takes seasons into account.
        kodiutils.show_listing(listing, 30003, content='episodes', sort=['episode', 'duration'])

    def show_recommendations(self, storefront):
        """ Show the recommendations.

        :type storefront: str
        """
        recommendations = self._api.get_recommendations(storefront)

        listing = []
        for cat in recommendations:
            listing.append(TitleItem(
                title=cat.title,
                path=kodiutils.url_for('show_recommendations_category', storefront=storefront, category=cat.category_id),
                info_dict=dict(
                    plot='[B]{category}[/B]'.format(category=cat.title),
                ),
            ))

        # Sort categories by default like in Streamz.
        kodiutils.show_listing(listing, 30015, content='files')

    def show_recommendations_category(self, storefront, category):
        """ Show the items in a recommendations category.

        :type storefront: str
        :type category: str
        """
        recommendations = self._api.get_recommendations(storefront)

        listing = []
        for cat in recommendations:
            # Only show the requested category
            if cat.category_id != category:
                continue

            for item in cat.content:
                listing.append(Menu.generate_titleitem(item))

        # Sort categories by default like in Streamz.
        kodiutils.show_listing(listing, 30015, content='tvshows', sort=['unsorted', 'label', 'year', 'duration'])

    def show_mylist(self):
        """ Show the items in "My List". """
        mylist = self._api.get_swimlane('my-list')

        listing = []
        for item in mylist:
            item.my_list = True
            listing.append(Menu.generate_titleitem(item))

        # Sort categories by default like in Streamz.
        kodiutils.show_listing(listing, 30017, content='tvshows', sort=['unsorted', 'label', 'year', 'duration'])

    def mylist_add(self, video_type, content_id):
        """ Add an item to "My List".

        :type video_type: str
        :type content_id: str
         """
        self._api.add_mylist(video_type, content_id)
        kodiutils.end_of_directory()

    def mylist_del(self, video_type, content_id):
        """ Remove an item from "My List".

        :type video_type: str
        :type content_id: str
        """
        self._api.del_mylist(video_type, content_id)
        kodiutils.end_of_directory()

    def show_continuewatching(self):
        """ Show the items in "Continue Watching". """
        mylist = self._api.get_swimlane('continue-watching')

        listing = []
        for item in mylist:
            titleitem = Menu.generate_titleitem(item, progress=True)

            # Add Program Name to title since this list contains episodes from multiple programs
            title = '%s - %s' % (
                titleitem.info_dict.get('tvshowtitle'),
                titleitem.info_dict.get('title'))
            titleitem.info_dict['title'] = title
            listing.append(titleitem)

        # Sort categories by default like in Streamz.
        kodiutils.show_listing(listing, 30019, content='episodes', sort='label')
class Library:
    """ Menu code related to the catalog """

    def __init__(self):
        """ Initialise object """
        self._auth = Auth(kodiutils.get_setting('username'),
                          kodiutils.get_setting('password'),
                          kodiutils.get_setting('loginprovider'),
                          kodiutils.get_setting('profile'),
                          kodiutils.get_tokens_path())
        self._api = Api(self._auth)

    def show_library_movies(self, movie=None):
        """ Return a list of the movies that should be exported. """
        if movie is None:
            if kodiutils.get_setting_int('library_movies') == LIBRARY_FULL_CATALOG:
                # Full catalog
                # Use cache if available, fetch from api otherwise so we get rich metadata for new content
                items = self._api.get_items(content_filter=Movie, cache=CACHE_AUTO)
            else:
                # Only favourites, use cache if available, fetch from api otherwise
                items = self._api.get_swimlane('my-list', content_filter=Movie)
        else:
            items = [self._api.get_movie(movie)]

        listing = []
        for item in items:
            title_item = Menu.generate_titleitem(item)
            # title_item.path = kodiutils.url_for('library_movies', movie=item.movie_id)  # We need a trailing /
            title_item.path = 'plugin://plugin.video.streamz/library/movies/?movie=%s' % item.movie_id
            listing.append(title_item)

        kodiutils.show_listing(listing, 30003, content='movies', sort=['label', 'year', 'duration'])

    def show_library_tvshows(self, program=None):
        """ Return a list of the series that should be exported. """
        if program is None:
            if kodiutils.get_setting_int('library_tvshows') == LIBRARY_FULL_CATALOG:
                # Full catalog
                # Use cache if available, fetch from api otherwise so we get rich metadata for new content
                # NOTE: We should probably use CACHE_PREVENT here, so we can pick up new episodes, but we can't since that would
                #       require a massive amount of API calls for each update. We do this only for programs in 'My list'.
                items = self._api.get_items(content_filter=Program, cache=CACHE_AUTO)
            else:
                # Only favourites, don't use cache, fetch from api
                # If we use CACHE_AUTO, we will miss updates until the user manually opens the program in the Add-on
                items = self._api.get_swimlane('my-list', content_filter=Program, cache=CACHE_PREVENT)
        else:
            # Fetch only a single program
            items = [self._api.get_program(program, cache=CACHE_PREVENT)]

        listing = []
        for item in items:
            title_item = Menu.generate_titleitem(item)
            # title_item.path = kodiutils.url_for('library_tvshows', program=item.program_id)  # We need a trailing /
            title_item.path = 'plugin://plugin.video.streamz/library/tvshows/?program={program_id}'.format(program_id=item.program_id)
            listing.append(title_item)

        kodiutils.show_listing(listing, 30003, content='tvshows', sort=['label', 'year', 'duration'])

    def show_library_tvshows_program(self, program):
        """ Return a list of the episodes that should be exported. """
        program_obj = self._api.get_program(program)

        listing = []
        for season in list(program_obj.seasons.values()):
            for item in list(season.episodes.values()):
                title_item = Menu.generate_titleitem(item)
                # title_item.path = kodiutils.url_for('library_tvshows', program=item.program_id, episode=item.episode_id)
                title_item.path = 'plugin://plugin.video.streamz/library/tvshows/?program={program_id}&episode={episode_id}'.format(program_id=item.program_id,
                                                                                                                                    episode_id=item.episode_id)
                listing.append(title_item)

        # Sort by episode number by default. Takes seasons into account.
        kodiutils.show_listing(listing, 30003, content='episodes', sort=['episode', 'duration'])

    def check_library_movie(self, movie):
        """ Check if the given movie is still available. """
        _LOGGER.debug('Checking if movie %s is still available', movie)

        # Our parent path always exists
        if movie is None:
            kodiutils.library_return_status(True)
            return

        if kodiutils.get_setting_int('library_movies') == LIBRARY_FULL_CATALOG:
            id_list = self._api.get_catalog_ids()
        else:
            id_list = self._api.get_mylist_ids()

        kodiutils.library_return_status(movie in id_list)

    def check_library_tvshow(self, program):
        """ Check if the given program is still available. """
        _LOGGER.debug('Checking if program %s is still available', program)

        # Our parent path always exists
        if program is None:
            kodiutils.library_return_status(True)
            return

        if kodiutils.get_setting_int('library_tvshows') == LIBRARY_FULL_CATALOG:
            id_list = self._api.get_catalog_ids()
        else:
            id_list = self._api.get_mylist_ids()

        kodiutils.library_return_status(program in id_list)

    @staticmethod
    def mylist_added(video_type, content_id):
        """ Something has been added to My List. We want to index this. """
        if video_type == CONTENT_TYPE_MOVIE:
            if kodiutils.get_setting_int('library_movies') != LIBRARY_ONLY_MYLIST:
                return
            # This unfortunately adds the movie to the database with the wrong parent path:
            # Library().update('plugin://plugin.video.streamz/library/movies/?movie=%s&kodi_action=refresh_info' % content_id)
            Library().update('plugin://plugin.video.streamz/library/movies/')

        elif video_type == CONTENT_TYPE_PROGRAM:
            if kodiutils.get_setting_int('library_tvshows') != LIBRARY_ONLY_MYLIST:
                return
            Library().update('plugin://plugin.video.streamz/library/tvshows/?program=%s&kodi_action=refresh_info' % content_id)

    @staticmethod
    def mylist_removed(video_type, content_id):
        """ Something has been removed from My List. We want to de-index this. """
        if video_type == CONTENT_TYPE_MOVIE:
            if kodiutils.get_setting_int('library_movies') != LIBRARY_ONLY_MYLIST:
                return
            Library().clean('plugin://plugin.video.streamz/library/movies/?movie=%s' % content_id)

        elif video_type == CONTENT_TYPE_PROGRAM:
            if kodiutils.get_setting_int('library_tvshows') != LIBRARY_ONLY_MYLIST:
                return
            Library().clean('plugin://plugin.video.streamz/library/tvshows/?program=%s' % content_id)

    @staticmethod
    def configure():
        """ Configure the library integration. """
        # There seems to be no way to add sources automatically.
        # * https://forum.kodi.tv/showthread.php?tid=228840

        # Open the sources view
        kodiutils.execute_builtin('ActivateWindow(Videos,sources://video/)')

    @staticmethod
    def update(path=None):
        """ Update the library integration. """
        _LOGGER.debug('Scanning %s', path)
        if path:
            # We can use this to instantly add something to the library when we've added it to 'My List'.
            kodiutils.jsonrpc(method='VideoLibrary.Scan', params=dict(
                directory=path,
                showdialogs=False,
            ))
        else:
            kodiutils.jsonrpc(method='VideoLibrary.Scan')

    @staticmethod
    def clean(path=None):
        """ Cleanup the library integration. """
        _LOGGER.debug('Cleaning %s', path)
        if path:
            # We can use this to instantly remove something from the library when we've removed it from 'My List'.
            # This only works from Kodi 19 however. See https://github.com/xbmc/xbmc/pull/18562
            if kodiutils.kodi_version_major() > 18:
                kodiutils.jsonrpc(method='VideoLibrary.Clean', params=dict(
                    directory=path,
                    showdialogs=False,
                ))
            else:
                kodiutils.jsonrpc(method='VideoLibrary.Clean', params=dict(
                    showdialogs=False,
                ))
        else:
            kodiutils.jsonrpc(method='VideoLibrary.Clean')
示例#8
0
class Player:
    """ Code responsible for playing media """
    def __init__(self):
        """ Initialise object """
        auth = Auth(kodiutils.get_tokens_path())
        self._api = Api(auth.get_tokens())
        self._stream = Stream(auth.get_tokens())

    def play(self, category, item):
        """ Play the requested item.

        :type category: string
        :type item: string
        """
        # Check if inputstreamhelper is correctly installed
        if not self._check_inputstream():
            kodiutils.end_of_directory()
            return

        try:
            # Get stream information
            resolved_stream = self._stream.get_stream(category, item)

        except UnavailableException:
            kodiutils.ok_dialog(message=kodiutils.localize(
                30712))  # The video is unavailable...
            kodiutils.end_of_directory()
            return

        except LimitReachedException:
            kodiutils.ok_dialog(
                message=kodiutils.localize(30713)
            )  # You have reached the maximum amount of concurrent streams...
            kodiutils.end_of_directory()
            return

        info_dict = {
            'tvshowtitle': resolved_stream.program,
            'title': resolved_stream.title,
            'duration': resolved_stream.duration,
        }

        prop_dict = {}

        stream_dict = {
            'duration': resolved_stream.duration,
        }

        upnext_data = None

        # Lookup metadata
        try:
            if category in ['movies', 'oneoffs']:
                info_dict.update({'mediatype': 'movie'})

                # Get details
                movie_details = self._api.get_movie(item)
                if movie_details:
                    info_dict.update({
                        'plot': movie_details.description,
                        'year': movie_details.year,
                        'aired': movie_details.aired,
                    })

            elif category == 'episodes':
                info_dict.update({'mediatype': 'episode'})

                # There is no direct API to get episode details, so we go trough the cached program details
                program = self._api.get_program(resolved_stream.program_id)
                if program:
                    episode_details = self._api.get_episode_from_program(
                        program, item)
                    if episode_details:
                        info_dict.update({
                            'plot': episode_details.description,
                            'season': episode_details.season,
                            'episode': episode_details.number,
                        })

                        # Lookup the next episode
                        next_episode_details = self._api.get_next_episode_from_program(
                            program, episode_details.season,
                            episode_details.number)

                        # Create the data for Up Next
                        if next_episode_details:
                            upnext_data = self.generate_upnext(
                                episode_details, next_episode_details)

            else:
                _LOGGER.warning('Unknown category %s', category)

        except UnavailableException:
            # We continue without details.
            # This allows to play some programs that don't have metadata (yet).
            pass

        # If we have enabled the Manifest proxy, route the call trough that.
        if kodiutils.get_setting_bool('manifest_proxy'):
            try:  # Python 3
                from urllib.parse import urlencode
            except ImportError:  # Python 2
                from urllib import urlencode

            port = kodiutils.get_setting_int('manifest_proxy_port')
            if not port:
                kodiutils.notification(message=kodiutils.localize(30718),
                                       icon='error')
                kodiutils.end_of_directory()
                return

            url = 'http://127.0.0.1:{port}/manifest?{path}'.format(
                port=port, path=urlencode({'path': resolved_stream.url}))
        else:
            url = resolved_stream.url

        license_key = self._stream.create_license_key(
            resolved_stream.license_url)

        # Play this item
        kodiutils.play(url,
                       license_key,
                       resolved_stream.title, {},
                       info_dict,
                       prop_dict,
                       stream_dict,
                       subtitles=resolved_stream.subtitles)

        # Wait for playback to start
        kodi_player = KodiPlayer()
        if not kodi_player.waitForPlayBack(url=url):
            # Playback didn't start
            return

        # Send Up Next data
        if upnext_data and kodiutils.get_setting_bool('useupnext'):
            _LOGGER.debug("Sending Up Next data: %s", upnext_data)
            self.send_upnext(upnext_data)

    @staticmethod
    def _check_inputstream():
        """ Check if inputstreamhelper and inputstream.adaptive are fine.

        :rtype boolean
        """
        try:
            from inputstreamhelper import Helper
            is_helper = Helper('mpd', drm='com.widevine.alpha')
            if not is_helper.check_inputstream():
                # inputstreamhelper has already shown an error
                return False

        except ImportError:
            kodiutils.ok_dialog(
                message=kodiutils.localize(30708))  # Please reboot Kodi
            return False

        return True

    @staticmethod
    def generate_upnext(current_episode, next_episode):
        """ Construct the data for Up Next.

        :type current_episode: resources.lib.streamz.api.Episode
        :type next_episode: resources.lib.streamz.api.Episode
        """
        upnext_info = dict(
            current_episode=dict(
                episodeid=current_episode.episode_id,
                tvshowid=current_episode.program_id,
                title=current_episode.name,
                art={
                    'poster': current_episode.poster,
                    'landscape': current_episode.thumb,
                    'fanart': current_episode.fanart,
                },
                season=current_episode.season,
                episode=current_episode.number,
                showtitle=current_episode.program_name,
                plot=current_episode.description,
                playcount=None,
                rating=None,
                firstaired=current_episode.aired[:10]
                if current_episode.aired else '',
                runtime=current_episode.duration,
            ),
            next_episode=dict(
                episodeid=next_episode.episode_id,
                tvshowid=next_episode.program_id,
                title=next_episode.name,
                art={
                    'poster': next_episode.poster,
                    'landscape': next_episode.thumb,
                    'fanart': next_episode.fanart,
                },
                season=next_episode.season,
                episode=next_episode.number,
                showtitle=next_episode.program_name,
                plot=next_episode.description,
                playcount=None,
                rating=None,
                firstaired=next_episode.aired[:10]
                if next_episode.aired else '',
                runtime=next_episode.duration,
            ),
            play_url='plugin://plugin.video.streamz/play/catalog/episodes/%s' %
            next_episode.episode_id,
        )

        return upnext_info

    @staticmethod
    def send_upnext(upnext_info):
        """ Send a message to Up Next with information about the next Episode.

        :type upnext_info: object
        """
        from base64 import b64encode
        from json import dumps
        data = [kodiutils.to_unicode(b64encode(dumps(upnext_info).encode()))]
        sender = '{addon_id}.SIGNAL'.format(addon_id='plugin.video.streamz')
        kodiutils.notify(sender=sender, message='upnext_data', data=data)
示例#9
0
class Player:
    """ Code responsible for playing media """
    def __init__(self):
        """ Initialise object """
        self._auth = Auth(kodiutils.get_setting('username'),
                          kodiutils.get_setting('password'),
                          kodiutils.get_setting('loginprovider'),
                          kodiutils.get_setting('profile'),
                          kodiutils.get_tokens_path())
        self._api = Api(self._auth)
        self._stream = Stream(self._auth)

    def play(self, category, item):
        """ Play the requested item.
        :type category: string
        :type item: string
        """
        # Check if inputstreamhelper is correctly installed
        if not self._check_inputstream():
            kodiutils.end_of_directory()
            return

        try:
            # Get stream information
            resolved_stream = self._stream.get_stream(category, item)

        except StreamGeoblockedException:
            kodiutils.ok_dialog(heading=kodiutils.localize(30709),
                                message=kodiutils.localize(
                                    30710))  # This video is geo-blocked...
            kodiutils.end_of_directory()
            return

        except StreamUnavailableException:
            kodiutils.ok_dialog(heading=kodiutils.localize(30711),
                                message=kodiutils.localize(
                                    30712))  # The video is unavailable...
            kodiutils.end_of_directory()
            return

        info_dict = {
            'tvshowtitle': resolved_stream.program,
            'title': resolved_stream.title,
            'duration': resolved_stream.duration,
        }

        prop_dict = {}

        stream_dict = {
            'duration': resolved_stream.duration,
        }

        upnext_data = None

        # Lookup metadata
        try:
            if category in ['movies', 'oneoffs']:
                info_dict.update({'mediatype': 'movie'})

                # Get details
                movie_details = self._api.get_movie(item)
                if movie_details:
                    info_dict.update({
                        'plot': movie_details.description,
                        'year': movie_details.year,
                        'aired': movie_details.aired,
                    })

            elif category == 'episodes':
                info_dict.update({'mediatype': 'episode'})

                # There is no direct API to get episode details, so we go trough the cached program details
                program = self._api.get_program(resolved_stream.program_id)
                if program:
                    episode_details = self._api.get_episode_from_program(
                        program, item)
                    if episode_details:
                        info_dict.update({
                            'plot': episode_details.description,
                            'season': episode_details.season,
                            'episode': episode_details.number,
                        })

                        # Lookup the next episode
                        next_episode_details = self._api.get_next_episode_from_program(
                            program, episode_details.season,
                            episode_details.number)

                        # Create the data for Up Next
                        if next_episode_details:
                            upnext_data = self.generate_upnext(
                                episode_details, next_episode_details)

            elif category == 'channels':
                info_dict.update({'mediatype': 'episode'})

                # For live channels, we need to keep on updating the manifest
                # This might not be needed, and could be done with the Location-tag updates if inputstream.adaptive supports it
                # See https://github.com/peak3d/inputstream.adaptive/pull/298#issuecomment-524206935
                prop_dict.update({
                    'inputstream.adaptive.manifest_update_parameter':
                    'full',
                })

            else:
                _LOGGER.warning('Unknown category %s', category)

        except UnavailableException:
            # We continue without details.
            # This allows to play some programs that don't have metadata (yet).
            pass

        license_key = self._stream.create_license_key(
            resolved_stream.license_url)

        # Play this item
        kodiutils.play(resolved_stream.url, license_key, resolved_stream.title,
                       {}, info_dict, prop_dict, stream_dict)

        # Wait for playback to start
        kodi_player = KodiPlayer()
        if not kodi_player.waitForPlayBack(url=resolved_stream.url):
            # Playback didn't start
            return

        # Send Up Next data
        if upnext_data and kodiutils.get_setting_bool('useupnext'):
            _LOGGER.debug("Sending Up Next data: %s", upnext_data)
            self.send_upnext(upnext_data)

    @staticmethod
    def _check_inputstream():
        """ Check if inputstreamhelper and inputstream.adaptive are fine.
        :rtype boolean
        """
        try:
            from inputstreamhelper import Helper
            is_helper = Helper('mpd', drm='com.widevine.alpha')
            if not is_helper.check_inputstream():
                # inputstreamhelper has already shown an error
                return False

        except ImportError:
            kodiutils.ok_dialog(
                message=kodiutils.localize(30708))  # Please reboot Kodi
            return False

        return True

    @staticmethod
    def generate_upnext(current_episode, next_episode):
        """ Construct the data for Up Next.
        :type current_episode: resources.lib.streamz.api.Episode
        :type next_episode: resources.lib.streamz.api.Episode
        """
        upnext_info = dict(
            current_episode=dict(
                episodeid=current_episode.episode_id,
                tvshowid=current_episode.program_id,
                title=current_episode.name,
                art={
                    'thumb': current_episode.cover,
                },
                season=current_episode.season,
                episode=current_episode.number,
                showtitle=current_episode.program_name,
                plot=current_episode.description,
                playcount=None,
                rating=None,
                firstaired=current_episode.aired[:10]
                if current_episode.aired else '',
                runtime=current_episode.duration,
            ),
            next_episode=dict(
                episodeid=next_episode.episode_id,
                tvshowid=next_episode.program_id,
                title=next_episode.name,
                art={
                    'thumb': next_episode.cover,
                },
                season=next_episode.season,
                episode=next_episode.number,
                showtitle=next_episode.program_name,
                plot=next_episode.description,
                playcount=None,
                rating=None,
                firstaired=next_episode.aired[:10]
                if next_episode.aired else '',
                runtime=next_episode.duration,
            ),
            play_url='plugin://plugin.video.streamz/play/catalog/episodes/%s' %
            next_episode.episode_id,
        )

        return upnext_info

    @staticmethod
    def send_upnext(upnext_info):
        """ Send a message to Up Next with information about the next Episode.
        :type upnext_info: object
        """
        from base64 import b64encode
        from json import dumps
        data = [kodiutils.to_unicode(b64encode(dumps(upnext_info).encode()))]
        sender = '{addon_id}.SIGNAL'.format(addon_id='plugin.video.streamz')
        kodiutils.notify(sender=sender, message='upnext_data', data=data)