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())
示例#2
0
def index():
    """ Show the profile selection, or go to the main menu. """
    auth = Auth(kodiutils.get_tokens_path())
    tokens = auth.get_tokens()

    if tokens:
        select_profile()
    else:
        show_login_menu()
    def verify_credentials():
        """ Verify if the user has credentials and if they are valid. """
        retry = False
        while True:

            # Check if the user has credentials
            if retry or not kodiutils.get_setting(
                    'username') or not kodiutils.get_setting('password'):

                # Ask user to fill in his credentials
                if not kodiutils.yesno_dialog(message=kodiutils.localize(
                        30701)):  # You need to configure your credentials...
                    # The user doesn't want to do this. Abort to Home screen.
                    return False

                kodiutils.open_settings()

            try:
                # Create Auth object so we actually do a login.
                Auth(kodiutils.get_setting('username'),
                     kodiutils.get_setting('password'),
                     kodiutils.get_setting('loginprovider'),
                     kodiutils.get_setting('profile'),
                     kodiutils.get_tokens_path())
                return True

            except InvalidLoginException:
                kodiutils.ok_dialog(message=kodiutils.localize(
                    30203))  # Your credentials are not valid!
                retry = True

            except NoStreamzSubscriptionException:
                kodiutils.ok_dialog(message=kodiutils.localize(
                    30201))  # Your Streamz account has no valid subscription!
                retry = True

            except NoTelenetSubscriptionException:
                kodiutils.ok_dialog(message=kodiutils.localize(
                    30202))  # Your Telenet account has no valid subscription!
                retry = True

            except LoginErrorException as exc:
                kodiutils.ok_dialog(message=kodiutils.localize(
                    30702,
                    code=exc.code))  # Unknown error while logging in: {code}
                return False

            except HTTPError as exc:
                kodiutils.ok_dialog(message=kodiutils.localize(
                    30702, code='HTTP %d' % exc.response.status_code)
                                    )  # Unknown error while logging in: {code}
                return False
示例#4
0
 def __init__(self):
     """ Initialise object """
     self._auth = Auth(kodiutils.get_tokens_path())
示例#5
0
class Menu:
    """ Menu code """

    def __init__(self):
        """ Initialise object """
        self._auth = Auth(kodiutils.get_tokens_path())

    def show_mainmenu(self):
        """ Show the main menu. """
        listing = []

        account = self._auth.get_tokens()

        if account.product == PRODUCT_STREAMZ:
            listing.append(TitleItem(
                title=kodiutils.localize(30015),  # Recommendations
                path=kodiutils.url_for('show_recommendations', storefront=STOREFRONT_MAIN),
                art_dict=dict(
                    icon='DefaultFavourites.png',
                    fanart=kodiutils.get_addon_info('fanart'),
                ),
                info_dict=dict(
                    plot=kodiutils.localize(30016),
                ),
            ))

            listing.append(TitleItem(
                title=kodiutils.localize(30003),  # Movies
                path=kodiutils.url_for('show_recommendations', storefront=STOREFRONT_MOVIES),
                art_dict=dict(
                    icon='DefaultMovies.png',
                    fanart=kodiutils.get_addon_info('fanart'),
                ),
                info_dict=dict(
                    plot=kodiutils.localize(30004),
                ),
            ))

            listing.append(TitleItem(
                title=kodiutils.localize(30005),  # Series
                path=kodiutils.url_for('show_recommendations', storefront=STOREFRONT_SERIES),
                art_dict=dict(
                    icon='DefaultTVShows.png',
                    fanart=kodiutils.get_addon_info('fanart'),
                ),
                info_dict=dict(
                    plot=kodiutils.localize(30006),
                ),
            ))

            listing.append(TitleItem(
                title=kodiutils.localize(30021),  # Kids
                path=kodiutils.url_for('show_recommendations', storefront=STOREFRONT_KIDS),
                art_dict=dict(
                    icon='DefaultFavourites.png',
                    fanart=kodiutils.get_addon_info('fanart'),
                ),
                info_dict=dict(
                    plot=kodiutils.localize(30022),
                ),
            ))

        elif account.product == PRODUCT_STREAMZ_KIDS:
            listing.append(TitleItem(
                title=kodiutils.localize(30015),  # Recommendations
                path=kodiutils.url_for('show_recommendations', storefront=STOREFRONT_MAIN_KIDS),
                art_dict=dict(
                    icon='DefaultFavourites.png',
                    fanart=kodiutils.get_addon_info('fanart'),
                ),
                info_dict=dict(
                    plot=kodiutils.localize(30016),
                ),
            ))
        if kodiutils.get_setting_bool('interface_show_mylist'):
            listing.append(TitleItem(
                title=kodiutils.localize(30017),  # My List
                path=kodiutils.url_for('show_mylist'),
                art_dict=dict(
                    icon='DefaultPlaylist.png',
                    fanart=kodiutils.get_addon_info('fanart'),
                ),
                info_dict=dict(
                    plot=kodiutils.localize(30018),
                ),
            ))

        if kodiutils.get_setting_bool('interface_show_continuewatching'):
            listing.append(TitleItem(
                title=kodiutils.localize(30019),  # Continue watching
                path=kodiutils.url_for('show_continuewatching'),
                art_dict=dict(
                    icon='DefaultInProgressShows.png',
                    fanart=kodiutils.get_addon_info('fanart'),
                ),
                info_dict=dict(
                    plot=kodiutils.localize(30020),
                ),
            ))

        listing.append(TitleItem(
            title=kodiutils.localize(30009),  # Search
            path=kodiutils.url_for('show_search'),
            art_dict=dict(
                icon='DefaultAddonsSearch.png',
                fanart=kodiutils.get_addon_info('fanart'),
            ),
            info_dict=dict(
                plot=kodiutils.localize(30010),
            ),
        ))

        kodiutils.show_listing(listing, sort=['unsorted'])

    @staticmethod
    def format_plot(obj):
        """ Format the plot for a item.

        :type obj: object
        :rtype str
        """
        plot = ''

        # Add geo-blocked message
        if hasattr(obj, 'available') and not obj.available:
            plot += kodiutils.localize(30206)  # Available in Streamz+
            plot += '\n'

        # Add remaining
        if hasattr(obj, 'remaining') and obj.remaining is not None:
            if obj.remaining == 0:
                plot += '» ' + kodiutils.localize(30208) + "\n"  # Available until midnight
            elif obj.remaining == 1:
                plot += '» ' + kodiutils.localize(30209) + "\n"  # One more day remaining
            elif obj.remaining / 365 > 5:
                pass  # If it is available for more than 5 years, do not show
            elif obj.remaining / 365 > 2:
                plot += '» ' + kodiutils.localize(30210, years=int(obj.remaining / 365)) + "\n"  # X years remaining
            elif obj.remaining / 30.5 > 3:
                plot += '» ' + kodiutils.localize(30211, months=int(obj.remaining / 30.5)) + "\n"  # X months remaining
            else:
                plot += '» ' + kodiutils.localize(30212, days=obj.remaining) + "\n"  # X days remaining
            plot += '\n'

        # Add geo-blocked message
        if hasattr(obj, 'geoblocked') and obj.geoblocked:
            plot += kodiutils.localize(30207)  # Geo-blocked
            plot += '\n'

        if hasattr(obj, 'description'):
            plot += obj.description
            plot += '\n\n'

        return plot.rstrip()

    @classmethod
    def generate_titleitem(cls, item, progress=False):
        """ Generate a TitleItem based on a Movie, Program or Episode.

        :type item: Union[Movie, Program, Episode]
        :type progress: bool
        :rtype TitleItem
        """
        art_dict = {
            'poster': item.poster,
            'landscape': item.thumb,
            'thumb': item.thumb,
            'fanart': item.fanart,
        }
        info_dict = {
            'title': item.name,
            'plot': cls.format_plot(item),
            # 'studio': CHANNELS.get(item.channel, {}).get('studio_icon'),
            'mpaa': ', '.join(item.legal) if hasattr(item, 'legal') and item.legal else kodiutils.localize(30216),  # All ages
        }
        prop_dict = {}

        #
        # Movie
        #
        if isinstance(item, Movie):
            if item.my_list:
                context_menu = [(
                    kodiutils.localize(30101),  # Remove from My List
                    'Container.Update(%s)' %
                    kodiutils.url_for('mylist_del', video_type=CONTENT_TYPE_MOVIE, content_id=item.movie_id)
                )]
            else:
                context_menu = [(
                    kodiutils.localize(30100),  # Add to My List
                    'Container.Update(%s)' %
                    kodiutils.url_for('mylist_add', video_type=CONTENT_TYPE_MOVIE, content_id=item.movie_id)
                )]

            info_dict.update({
                'mediatype': 'movie',
                'duration': item.duration,
                'year': item.year,
                'aired': item.aired,
            })
            stream_dict = {
                'codec': 'h264',
                'duration': item.duration,
                'height': 1080,
                'width': 1920,
            }

            if item.available:
                title = item.name
            else:
                title = item.name + ' [COLOR=red](S+)[/COLOR]'
                info_dict.update({
                    'title': title,
                })

            return TitleItem(
                title=title,
                path=kodiutils.url_for('play', category='movies', item=item.movie_id),
                art_dict=art_dict,
                info_dict=info_dict,
                stream_dict=stream_dict,
                prop_dict=prop_dict,
                context_menu=context_menu,
                is_playable=True,
            )

        #
        # Program
        #
        if isinstance(item, Program):
            if item.my_list:
                context_menu = [(
                    kodiutils.localize(30101),  # Remove from My List
                    'Container.Update(%s)' %
                    kodiutils.url_for('mylist_del', video_type=CONTENT_TYPE_PROGRAM, content_id=item.program_id)
                )]
            else:
                context_menu = [(
                    kodiutils.localize(30100),  # Add to My List
                    'Container.Update(%s)' %
                    kodiutils.url_for('mylist_add', video_type=CONTENT_TYPE_PROGRAM, content_id=item.program_id)
                )]

            info_dict.update({
                'mediatype': 'tvshow',
                'season': len(item.seasons),
            })

            return TitleItem(
                title=item.name,
                path=kodiutils.url_for('show_catalog_program', program=item.program_id),
                art_dict=art_dict,
                info_dict=info_dict,
                prop_dict=prop_dict,
                context_menu=context_menu,
            )

        #
        # Episode
        #
        if isinstance(item, Episode):
            context_menu = []
            if item.program_id:
                context_menu = [(
                    kodiutils.localize(30102),  # Go to Program
                    'Container.Update(%s)' %
                    kodiutils.url_for('show_catalog_program', program=item.program_id)
                )]

            info_dict.update({
                'mediatype': 'episode',
                'tvshowtitle': item.program_name,
                'duration': item.duration,
                'season': item.season,
                'episode': item.number,
                'set': item.program_name,
                'aired': item.aired,
            })
            if progress and item.watched:
                info_dict.update({
                    'playcount': 1,
                })

            stream_dict = {
                'codec': 'h264',
                'duration': item.duration,
                'height': 1080,
                'width': 1920,
            }

            # Add progress info
            if progress and not item.watched and item.progress:
                prop_dict.update({
                    'ResumeTime': item.progress,
                    'TotalTime': item.progress + 1,
                })

            return TitleItem(
                title=info_dict['title'],
                path=kodiutils.url_for('play', category='episodes', item=item.episode_id),
                art_dict=art_dict,
                info_dict=info_dict,
                stream_dict=stream_dict,
                prop_dict=prop_dict,
                context_menu=context_menu,
                is_playable=True,
            )

        raise Exception('Unknown video_type')
示例#6
0
class Authentication:
    """ Code responsible for the Authentication """
    def __init__(self):
        """ Initialise object """
        self._auth = Auth(kodiutils.get_tokens_path())

    def login(self):
        """ Start the authorisation flow. """
        auth_info = self._auth.authorize()

        # Show the authorization message
        progress_dialog = kodiutils.progress(
            message=kodiutils.localize(30701,
                                       url=auth_info.get('verification_uri'),
                                       code=auth_info.get('user_code')))
        progress_dialog.update(0)

        # Check the authorization until it succeeds or the user cancels.
        delay = auth_info.get('interval')
        expiry = auth_info.get('expires_in')
        time_start = datetime.now()
        time_end = time_start + timedelta(seconds=expiry)
        while datetime.now() < time_end:
            # Update progress
            progress_dialog.update(
                int((datetime.now() - time_start).seconds * 100 / expiry))

            # Check if the users has cancelled the login flow
            if progress_dialog.iscanceled():
                progress_dialog.close()
                return

            # Check if we are authorized now
            check = self._auth.authorize_check()
            if check:
                progress_dialog.close()
                kodiutils.notification(kodiutils.localize(30702))
                kodiutils.redirect(kodiutils.url_for('show_main_menu'))
                return

            # Sleep a bit
            sleep(delay)

        # Close progress indicator
        progress_dialog.close()

        kodiutils.ok_dialog(message=kodiutils.localize(30703))

    def select_profile(self, key=None):
        """ Show your profiles.
        :type key: str
        """
        profiles = self._auth.get_profiles()

        # Show warning when you have no profiles
        if not profiles:
            # Your account has no profiles defined. Please login on www.streamz.be/streamz and create a profile.
            kodiutils.ok_dialog(message=kodiutils.localize(30704))
            kodiutils.end_of_directory()
            return

        # Select the first profile when you only have one
        if len(profiles) == 1:
            key = profiles[0].key

        # Save the selected profile
        if key:
            profile = [x for x in profiles if x.key == key][0]
            _LOGGER.debug('Setting profile to %s', profile)
            self._auth.set_profile(profile.key, profile.product)

            kodiutils.redirect(kodiutils.url_for('show_main_menu'))
            return

        # Show profile selection when you have multiple profiles
        listing = [
            TitleItem(
                title=self._get_profile_name(p),
                path=kodiutils.url_for('select_profile', key=p.key),
                art_dict=dict(icon='DefaultUser.png'),
                info_dict=dict(plot=p.name, ),
            ) for p in profiles
        ]

        kodiutils.show_listing(listing, sort=['unsorted'],
                               category=30057)  # Select Profile

    @staticmethod
    def _get_profile_name(profile):
        """ Get a descriptive string of the profile.
        :type profile: resources.lib.streamz.Profile
        """
        title = profile.name

        # Convert the Streamz Profile color to a matching Kodi color
        color_map = {
            '#F20D3A': 'red',
            '#FF0A5A': 'crimson',
            '#FF4B00': 'darkorange',
            '#FED71F': 'gold',
            '#5EFF74': 'palegreen',
            '#0DF2E8': 'turquoise',
            '#226DFF': 'dodgerblue',
            '#6900CC': 'blueviolet',
        }
        if color_map.get(profile.color.upper()):
            title = '[COLOR %s]%s[/COLOR]' % (color_map.get(
                profile.color.upper()), kodiutils.to_unicode(title))

        # Append (Kids)
        if profile.product == PRODUCT_STREAMZ_KIDS:
            title = "%s (Kids)" % title

        return title

    def clear_tokens(self):
        """ Clear the authentication tokens """
        self._auth.logout()
        kodiutils.notification(message=kodiutils.localize(30706))
示例#7
0
 def __init__(self, ):
     """ Initialise object """
     auth = Auth(kodiutils.get_tokens_path())
     self._api = Api(auth.get_tokens())
class Authentication:
    """ Code responsible for the Authentication """
    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)

    @staticmethod
    def verify_credentials():
        """ Verify if the user has credentials and if they are valid. """
        retry = False
        while True:

            # Check if the user has credentials
            if retry or not kodiutils.get_setting(
                    'username') or not kodiutils.get_setting('password'):

                # Ask user to fill in his credentials
                if not kodiutils.yesno_dialog(message=kodiutils.localize(
                        30701)):  # You need to configure your credentials...
                    # The user doesn't want to do this. Abort to Home screen.
                    return False

                kodiutils.open_settings()

            try:
                # Create Auth object so we actually do a login.
                Auth(kodiutils.get_setting('username'),
                     kodiutils.get_setting('password'),
                     kodiutils.get_setting('loginprovider'),
                     kodiutils.get_setting('profile'),
                     kodiutils.get_tokens_path())
                return True

            except InvalidLoginException:
                kodiutils.ok_dialog(message=kodiutils.localize(
                    30203))  # Your credentials are not valid!
                retry = True

            except NoStreamzSubscriptionException:
                kodiutils.ok_dialog(message=kodiutils.localize(
                    30201))  # Your Streamz account has no valid subscription!
                retry = True

            except NoTelenetSubscriptionException:
                kodiutils.ok_dialog(message=kodiutils.localize(
                    30202))  # Your Telenet account has no valid subscription!
                retry = True

            except LoginErrorException as exc:
                kodiutils.ok_dialog(message=kodiutils.localize(
                    30702,
                    code=exc.code))  # Unknown error while logging in: {code}
                return False

            except HTTPError as exc:
                kodiutils.ok_dialog(message=kodiutils.localize(
                    30702, code='HTTP %d' % exc.response.status_code)
                                    )  # Unknown error while logging in: {code}
                return False

    def select_profile(self, key=None):
        """ Show your profiles.

        :type key: str
        """
        profiles = self._auth.get_profiles()

        # Show warning when you have no profiles
        if not profiles:
            # Your account has no profiles defined. Please login on www.streamz.be/streamz and create a profile.
            kodiutils.ok_dialog(message=kodiutils.localize(30703))
            kodiutils.end_of_directory()
            return

        # Select the first profile when you only have one
        if len(profiles) == 1:
            key = profiles[0].key

        # Save the selected profile
        if key:
            profile = [x for x in profiles if x.key == key][0]
            _LOGGER.debug('Setting profile to %s', profile)
            kodiutils.set_setting('profile',
                                  '%s:%s' % (profile.key, profile.product))
            kodiutils.set_setting('profile_name', profile.name)

            kodiutils.redirect(kodiutils.url_for('show_main_menu'))
            return

        # Show profile selection when you have multiple profiles
        listing = [
            TitleItem(
                title=self._get_profile_name(p),
                path=kodiutils.url_for('select_profile', key=p.key),
                art_dict=dict(icon='DefaultUser.png'),
                info_dict=dict(plot=p.name, ),
            ) for p in profiles
        ]

        kodiutils.show_listing(listing, sort=['unsorted'],
                               category=30057)  # Select Profile

    @staticmethod
    def _get_profile_name(profile):
        """ Get a descriptive string of the profile.

        :type profile: resources.lib.streamz.Profile
        """
        title = profile.name

        # Convert the Streamz Profile color to a matching Kodi color
        color_map = {
            '#F20D3A': 'red',
            '#FF0A5A': 'crimson',
            '#FF4B00': 'darkorange',
            '#FED71F': 'gold',
            '#5EFF74': 'palegreen',
            '#0DF2E8': 'turquoise',
            '#226DFF': 'dodgerblue',
            '#6900CC': 'blueviolet',
        }
        if color_map.get(profile.color.upper()):
            title = '[COLOR %s]%s[/COLOR]' % (color_map.get(
                profile.color.upper()), kodiutils.to_unicode(title))

        # Append (Kids)
        if profile.product == 'STREAMZ_KIDS':
            title = "%s (Kids)" % title

        return title
class Authentication:
    """ Code responsible for the Authentication """
    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 select_profile(self, key=None):
        """ Show your profiles
        :type key: str
        """
        profiles = self._auth.get_profiles()

        # Show warning when you have no profiles
        if not profiles:
            # Your account has no profiles defined. Please login on www.streamz.be/streamz and create a profile.
            kodiutils.ok_dialog(message=kodiutils.localize(30703))
            kodiutils.end_of_directory()
            return

        # Select the first profile when you only have one
        if len(profiles) == 1:
            key = profiles[0].key

        # Save the selected profile
        if key:
            profile = [x for x in profiles if x.key == key][0]
            _LOGGER.debug('Setting profile to %s', profile)
            kodiutils.set_setting('profile',
                                  '%s:%s' % (profile.key, profile.product))
            kodiutils.set_setting('profile_name', profile.name)

            kodiutils.redirect(kodiutils.url_for('show_main_menu'))
            return

        # Show profile selection when you have multiple profiles
        listing = [
            TitleItem(
                title=self._get_profile_name(p),
                path=kodiutils.url_for('select_profile', key=p.key),
                art_dict=dict(icon='DefaultUser.png'),
                info_dict=dict(plot=p.name, ),
            ) for p in profiles
        ]

        kodiutils.show_listing(listing, sort=['unsorted'],
                               category=30057)  # Select Profile

    @staticmethod
    def _get_profile_name(profile):
        """ Get a descriptive string of the profile
        :type profile: resources.lib.streamz.Profile
        """
        title = profile.name

        # Convert the Streamz Profile color to a matching Kodi color
        color_map = {
            '#F20D3A': 'red',
            '#FF0A5A': 'crimson',
            '#FF4B00': 'darkorange',
            '#FED71F': 'gold',
            '#5EFF74': 'palegreen',
            '#0DF2E8': 'turquoise',
            '#226DFF': 'dodgerblue',
            '#6900CC': 'blueviolet',
        }
        if color_map.get(profile.color.upper()):
            title = '[COLOR %s]%s[/COLOR]' % (color_map.get(
                profile.color.upper()), kodiutils.to_unicode(title))

        # Append (Kids)
        if profile.product == 'STREAMZ_KIDS':
            title = "%s (Kids)" % title

        return title