def create_episode_item(self, result_set):
        """ Creates a new MediaItem for an episode.

        This method creates a new MediaItem from the Regular Expression or Json
        results <result_set>. The method should be implemented by derived classes
        and are specific to the channel.

        :param list[str]|dict[str,str] result_set: The result_set of the self.episodeItemRegex

        :return: A new MediaItem of type 'folder'.
        :rtype: MediaItem|None

        """

        item = MediaItem(result_set[1],
                         "%s%s?page=1" % (self.baseUrl, result_set[0]))
        item.complete = True
        return item
    def create_api_program_type(self, result_set):
        """ Creates a new MediaItem for an program.

        This method creates a new MediaItem from the Regular Expression or Json
        results <result_set>. The method should be implemented by derived classes
        and are specific to the channel.

        :param dict result_set: The result_set of the self.episodeItemRegex

        :return: A new MediaItem of type 'folder'.
        :rtype: MediaItem|None

        """

        title = result_set["title"]
        if title is None:
            return None

        seasons = result_set["seriesTvSeasons"]
        if len(seasons) == 0:
            return None

        if len(seasons) == 1:
            # List the videos in that season
            season_id = seasons[0]["id"].rsplit("/", 1)[-1]
            url = self.__get_api_query_url(
                query='programs(tvSeasonId:"{}",programTypes:EPISODE,skip:0,limit:100)'.format(season_id),
                fields=self.__video_fields)
        else:
            # Fetch the season information
            url = self.__get_api_query_url(
                query='programs(guid:"{}")'.format(result_set["guid"]),
                fields="{items{seriesTvSeasons{id,title,seasonNumber,__typename}}}"
            )

        item = MediaItem(result_set["title"], url)
        item.thumb = self.__get_thumb(result_set.get("imageMedia"))
        item.description = result_set.get("description")

        # In the mainlist we should set the fanart too
        if self.parentItem is None:
            item.fanart = item.thumb

        return item
Пример #3
0
    def create_folder_item(self, result_set):
        """ Creates a MediaItem of type 'folder' using the result_set from the regex.

        This method creates a new MediaItem from the Regular Expression or Json
        results <result_set>. The method should be implemented by derived classes
        and are specific to the channel.

        :param list[str]|dict[str,str] result_set: The result_set of the self.episodeItemRegex

        :return: A new MediaItem of type 'folder'.
        :rtype: MediaItem|None

        """

        Logger.trace(result_set)

        # Validate the input and raise errors
        if not isinstance(result_set, dict):
            Logger.critical(
                "No Dictionary as a result_set. Implement a custom create_video_item"
            )
            raise NotImplementedError(
                "No Dictionary as a result_set. Implement a custom create_video_item"
            )

        elif "title" not in result_set or "url" not in result_set:
            Logger.warning("No ?P<title> or ?P<url> in result_set")
            raise LookupError("No ?P<title> or ?P<url> in result_set")

        # The URL
        url = self._prefix_urls(result_set["url"])

        # The title
        title = result_set["title"]
        if title.isupper():
            title = title.title()

        item = MediaItem(title, url)
        item.description = result_set.get("description", "")
        item.thumb = result_set.get("thumburl", "")
        item.type = 'folder'
        item.HttpHeaders = self.httpHeaders
        item.complete = True
        return item
Пример #4
0
    def create_clip_item_json(self, result_set):
        """ Creates a MediaItem of type 'video' using the result_set from the regex.

        This method creates a new MediaItem from the Regular Expression or Json
        results <result_set>. The method should be implemented by derived classes
        and are specific to the channel.

        If the item is completely processed an no further data needs to be fetched
        the self.complete property should be set to True. If not set to True, the
        self.update_video_item method is called if the item is focussed or selected
        for playback.

        :param dict result_set: The result_set of the self.episodeItemRegex

        :return: A new MediaItem of type 'video' or 'audio' (despite the method's name).
        :rtype: MediaItem|None

        """

        Logger.trace(result_set)

        # get the title
        title = result_set["title"]
        mgid = result_set["id"]

        url = "https://media-utils.mtvnservices.com/services/MediaGenerator/" \
              "mgid:arc:video:{}:{}" \
              "?arcStage=live&format=json&acceptMethods=hls&clang=nl" \
              "&https=true".format(self.__country_id, mgid)

        item = MediaItem(title, url)
        item.type = "video"

        if "images" in result_set:
            item.thumb = result_set["images"]["url"]

        if "airDate" not in result_set:
            return item

        air_date = int(result_set["airDate"])
        date_stamp = DateHelper.get_date_from_posix(air_date, self.__timezone_utc)
        item.set_date(date_stamp.year, date_stamp.month, date_stamp.day)

        return item
Пример #5
0
    def create_video_item_old(self, result_set):
        """ Creates a MediaItem of type 'video' using the result_set from the regex.

        This method creates a new MediaItem from the Regular Expression or Json
        results <result_set>. The method should be implemented by derived classes
        and are specific to the channel.

        If the item is completely processed an no further data needs to be fetched
        the self.complete property should be set to True. If not set to True, the
        self.update_video_item method is called if the item is focussed or selected
        for playback.

        :param list[str]|dict[str,str] result_set: The result_set of the self.episodeItemRegex

        :return: A new MediaItem of type 'video' or 'audio' (despite the method's name).
        :rtype: MediaItem|None

        """

        Logger.trace(result_set)

        thumb_url = result_set[1]
        url = "%s%s" % (self.baseUrl, result_set[2])
        title = result_set[6]

        item = MediaItem(title, url)
        item.thumb = self.noImage
        if thumb_url:
            item.thumb = thumb_url
        item.icon = self.icon
        item.type = 'video'

        if result_set[3]:
            # set date
            day = result_set[3]
            month = result_set[4]
            year = result_set[5]
            Logger.trace("%s-%s-%s", year, month, day)
            month = datehelper.DateHelper.get_month_from_name(
                month, "nl", True)
            item.set_date(year, month, day)

        item.complete = False
        return item
Пример #6
0
    def create_api_clip_type(self, result_set):
        """ Creates a MediaItem of type 'video' using the result_set from the API.

        This method creates a new MediaItem from the Regular Expression or Json
        results <result_set>. The method should be implemented by derived classes
        and are specific to the channel.

        If the item is completely processed an no further data needs to be fetched
        the self.complete property should be set to True. If not set to True, the
        self.update_video_item method is called if the item is focussed or selected
        for playback.

        :param list[str]|dict result_set: The result_set of the self.episodeItemRegex

        :return: A new MediaItem of type 'video' or 'audio' (despite the method's name).
        :rtype: MediaItem|None

        This works for:
            __typename=Episode

        """

        title = result_set['name']
        svt_video_id = result_set.get("videoSvtId", result_set.get("svtId", None))
        if svt_video_id:
            # API style
            url = "https://api.svt.se/videoplayer-api/video/{}".format(svt_video_id)
        else:
            # HTML style
            url = "{}{}".format(self.baseUrl, result_set['urls']['svtplay'])

        item = MediaItem(title, url)
        item.type = "video"
        item.description = result_set.get('longDescription')
        item.isGeoLocked = result_set['restrictions']['onlyAvailableInSweden']

        image_info = result_set.get("image")
        if image_info:
            item.thumb = self.__get_thumb(image_info)

        duration = int(result_set.get("duration", 0))
        item.set_info_label("duration", duration)

        return item
Пример #7
0
    def add_clips(self, data):
        """ Add an items that lists clips.

        The return values should always be instantiated in at least ("", []).

        :param str data: The retrieve data that was loaded for the current item and URL.

        :return: A tuple of the data and a list of MediaItems that were generated.
        :rtype: tuple[str|JsonHelper,list[MediaItem]]

        """

        Logger.info("Adding Clips Pre-Processing")
        items = []

        # if the main list was retrieve using json, are the current data is json, just determine
        # the clip URL
        clip_url = None
        if data.lstrip().startswith("{"):
            if self.parentItem.url.endswith("type=program"):
                # http://playapi.mtgx.tv/v3/videos?format=6723&order=-airdate&type=program
                # http://playapi.mtgx.tv/v3/videos?format=6723&order=-updated&type=clip" % (data_id,)
                clip_url = self.parentItem.url.replace("type=program",
                                                       "type=clip")
        else:
            # now we determine the ID and load the json data
            data_id = Regexer.do_regex(r'data-format-id="(\d+)"', data)[-1]
            Logger.debug("Found FormatId = %s", data_id)
            program_url = \
                "http://playapi.mtgx.tv/v3/videos?format=%s&order=-airdate&type=program" % (data_id,)
            data = UriHandler.open(program_url, proxy=self.proxy)
            clip_url = \
                "http://playapi.mtgx.tv/v3/videos?format=%s&order=-updated&type=clip" % (data_id,)

        if clip_url is not None:
            clip_title = LanguageHelper.get_localized_string(
                LanguageHelper.Clips)
            clip_item = MediaItem("\a.: %s :." % (clip_title, ), clip_url)
            clip_item.thumb = self.parentItem.thumb
            clip_item.fanart = self.parentItem.fanart
            items.append(clip_item)

        Logger.debug("Pre-Processing finished")
        return data, items
    def create_json_video_item(self, result_set):
        """ Creates a MediaItem of type 'video' using the result_set from the regex.

        This method creates a new MediaItem from the Regular Expression or Json
        results <result_set>. The method should be implemented by derived classes
        and are specific to the channel.

        If the item is completely processed an no further data needs to be fetched
        the self.complete property should be set to True. If not set to True, the
        self.update_video_item method is called if the item is focussed or selected
        for playback.

        :param dict result_set: The result_set of the self.episodeItemRegex

        :return: A new MediaItem of type 'video' or 'audio' (despite the method's name).
        :rtype: MediaItem|None

        """

        Logger.trace(result_set)
        meta = result_set["meta"]
        name = meta["header"]["title"]
        if isinstance(name, dict):
            name = name["text"]

        sub_heading = meta.get("subHeader")
        if sub_heading:
            name = "{} - {}".format(name, sub_heading)

        url = "{}{}".format(self.baseUrl, result_set["url"])
        item = MediaItem(name, url)
        item.type = "video"
        item.description = meta.get("description")
        item.thumb = result_set.get("media", {}).get("image", {}).get("url")
        item.isGeoLocked = True

        date_value = meta["date"]
        if "." in date_value:
            date = DateHelper.get_date_from_string(date_value, date_format="%d.%m.%Y")
        else:
            date = DateHelper.get_date_from_string(date_value, date_format="%d/%m/%Y")
        item.set_date(*date[0:6])

        return item
Пример #9
0
    def create_series_video_item(self, result_set):
        """ Creates a MediaItem of type 'video' using the result_set from the regex.

        This method creates a new MediaItem from the Regular Expression or Json
        results <result_set>. The method should be implemented by derived classes
        and are specific to the channel.

        If the item is completely processed an no further data needs to be fetched
        the self.complete property should be set to True. If not set to True, the
        self.update_video_item method is called if the item is focussed or selected
        for playback.

        :param list[str]|dict result_set: The result_set of the self.episodeItemRegex

        :return: A new MediaItem of type 'video' or 'audio' (despite the method's name).
        :rtype: MediaItem|None

        """

        title = result_set["title"]
        sub_title = result_set.get("episodeTitle", None)
        if sub_title:
            title = "{} - {}".format(title, sub_title)

        if not result_set["usageRights"].get("hasRightsNow", True):
            Logger.debug("Found '%s' without 'usageRights'", title)
            return None

        url = "https://psapi.nrk.no/programs/{}?apiKey={}".format(
            result_set["id"], self.__api_key)
        item = MediaItem(title, url)
        item.type = 'video'

        # noinspection PyTypeChecker
        item.thumb = self.__get_image(result_set["image"]["webImages"],
                                      "pixelWidth", "imageUrl")
        item.description = result_set.get("longDescription", "")
        if not item.description:
            item.description = result_set.get("shortDescription", "")

        item.isGeoLocked = result_set.get("usageRights",
                                          {}).get("isGeoBlocked", False)
        self.__set_date(result_set, item)
        return item
Пример #10
0
    def create_video_item_json(self, result_set):
        """ Creates a MediaItem of type 'video' using the result_set from the regex.

        This method creates a new MediaItem from the Regular Expression or Json
        results <result_set>. The method should be implemented by derived classes
        and are specific to the channel.

        If the item is completely processed an no further data needs to be fetched
        the self.complete property should be set to True. If not set to True, the
        self.update_video_item method is called if the item is focussed or selected
        for playback.

        :param dict result_set: The result_set of the self.episodeItemRegex

        :return: A new MediaItem of type 'video' or 'audio' (despite the method's name).
        :rtype: MediaItem|None

        """

        Logger.trace(result_set)

        image_data = result_set.get("media", [])
        thumb = None
        for image in image_data:
            thumb = image.get("imageHigh", image["image"])

        video_info = result_set.get("video")
        if video_info:
            url = video_info["externalId"]
        else:
            return None

        item = MediaItem(result_set["title"], url)
        item.type = "video"
        item.thumb = thumb or self.noImage
        item.description = HtmlHelper.to_text(result_set.get("text"))

        # Let's not do the time now
        time_stamp = result_set["created"]
        date_time = DateHelper.get_date_from_posix(time_stamp)
        item.set_date(date_time.year, date_time.month, date_time.day,
                      date_time.hour, date_time.minute, date_time.second)
        return item
    def add_days(self, data):
        """ Performs pre-process actions for data processing.

        Accepts an data from the process_folder_list method, BEFORE the items are
        processed. Allows setting of parameters (like title etc) for the channel.
        Inside this method the <data> could be changed and additional items can
        be created.

        The return values should always be instantiated in at least ("", []).

        :param str data: The retrieve data that was loaded for the current item and URL.

        :return: A tuple of the data and a list of MediaItems that were generated.
        :rtype: tuple[str|JsonHelper,list[MediaItem]]

        """

        items = []

        now = datetime.datetime.now()
        from_date = now - datetime.timedelta(6)
        Logger.debug(
            "Showing dates starting from %02d%02d%02d to %02d%02d%02d",
            from_date.year, from_date.month, from_date.day, now.year,
            now.month, now.day)

        current = from_date
        while current <= now:
            url = "https://api.538.nl/api/v1/schedule/station/radio-538" \
                  "?since=%s-%s-%sT00%%3A00%%3A00%%2B01%%3A00" \
                  "&until=%s-%s-%sT23%%3A59%%3A59%%2B01%%3A00" % \
                  (current.year, current.month, current.day,
                   current.year, current.month, current.day)

            # "&_=1483280915489%%02d%%02d%%02d"
            title = "Afleveringen van %02d-%02d-%02d" % (
                current.year, current.month, current.day)
            date_item = MediaItem(title, url)
            date_item.complete = True
            items.append(date_item)
            current = current + datetime.timedelta(1)

        return data, items
Пример #12
0
    def add_page_items(self, data):
        """ Performs pre-process actions for data processing.

        Accepts an data from the process_folder_list method, BEFORE the items are
        processed. Allows setting of parameters (like title etc) for the channel.
        Inside this method the <data> could be changed and additional items can
        be created.

        The return values should always be instantiated in at least ("", []).

        :param str data: The retrieve data that was loaded for the current item and URL.

        :return: A tuple of the data and a list of MediaItems that were generated.
        :rtype: tuple[str|JsonHelper,list[MediaItem]]

        """

        Logger.info("Performing Pre-Processing")
        items = []
        json = JsonHelper(data)
        total_results = json.get_value("totalResults")
        from_value = json.get_value("from")
        size_value = json.get_value("size")

        if from_value + size_value < total_results:
            more_pages = LanguageHelper.get_localized_string(
                LanguageHelper.MorePages)
            url = self.parentItem.url.split('?')[0]
            url = "%s?size=%s&from=%s&sort=Nieuwste" % (
                url, size_value, from_value + size_value)
            Logger.debug("Adding next-page item from %s to %s",
                         from_value + size_value,
                         from_value + size_value + size_value)

            next_page = MediaItem(more_pages, url)
            next_page.icon = self.parentItem.icon
            next_page.fanart = self.parentItem.fanart
            next_page.thumb = self.parentItem.thumb
            next_page.dontGroup = True
            items.append(next_page)

        Logger.debug("Pre-Processing finished")
        return json, items
Пример #13
0
    def extract_json(self, data):
        """ Extracts JSON data from pages

        :param str data: The retrieve data that was loaded for the current item and URL.

        :return: A tuple of the data and a list of MediaItems that were generated.
        :rtype: tuple[str|JsonHelper,list[MediaItem]]

        """

        items = []
        recent = MediaItem("\a .: Recent :.", "https://www.een.be/deze-week")
        recent.type = "folder"
        recent.complete = True
        recent.dontGroup = True
        items.append(recent)

        data = Regexer.do_regex(r'epgAZ\W+({"data"[\w\W]+?);<', data)[0]
        return data, items
Пример #14
0
    def __show_empty_information(self, items, favs=False):
        """ Adds an empty item to a list or just shows a message.
        @type favs: boolean
        @param items:

        :param list[MediaItem] items:   The list of items.
        :param bool favs:               Indicating that we are dealing with favourites.

        :return: boolean indicating to report the listing as succes or not.
        :rtype: ok

        """

        if favs:
            title = LanguageHelper.get_localized_string(LanguageHelper.NoFavsId)
        else:
            title = LanguageHelper.get_localized_string(LanguageHelper.ErrorNoEpisodes)

        behaviour = AddonSettings.get_empty_list_behaviour()

        Logger.debug("Showing empty info for mode (favs=%s): [%s]", favs, behaviour)
        if behaviour == "error":
            # show error
            ok = False
        elif behaviour == "dummy" and not favs:
            # We should add a dummy items, but not for favs
            empty_list_item = MediaItem("- %s -" % (title.strip("."), ), "", type='video')
            empty_list_item.dontGroup = True
            empty_list_item.complete = True
            # add funny stream here?
            # part = empty_list_item.create_new_empty_media_part()
            # for s, b in YouTube.get_streams_from_you_tube("", self.channelObject.proxy):
            #     part.append_media_stream(s, b)

            # if we add one, set OK to True
            ok = True
            items.append(empty_list_item)
        else:
            ok = True

        XbmcWrapper.show_notification(LanguageHelper.get_localized_string(LanguageHelper.ErrorId),
                                      title, XbmcWrapper.Error, 2500)
        return ok
    def list_dates(self, data):
        """ Generates a list of the past week days.

        Accepts an data from the process_folder_list method, BEFORE the items are
        processed. Allows setting of parameters (like title etc) for the channel.
        Inside this method the <data> could be changed and additional items can
        be created.

        The return values should always be instantiated in at least ("", []).

        :param str data: The retrieve data that was loaded for the current item and URL.

        :return: A tuple of the data and a list of MediaItems that were generated.
        :rtype: tuple[str|JsonHelper,list[MediaItem]]

        """

        items = []

        # https://api.kijk.nl/v2/templates/page/missed/all/20180201
        days = ["Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrijdag", "Zaterdag", "Zondag"]
        for i in range(0, 7):
            date = datetime.datetime.now() - datetime.timedelta(days=i)
            # https://api.kijk.nl/v2/templates/page/missed/all/20180626
            # url = "https://api.kijk.nl/v2/templates/page/missed/all/{0}{1:02d}{2:02d}".format(date.year, date.month, date.day)
            # https://api.kijk.nl/v1/default/sections/missed-all-20180619
            url = "https://api.kijk.nl/v1/default/sections/missed-all-{0}{1:02d}{2:02d}".format(date.year, date.month, date.day)
            if i == 0:
                title = LanguageHelper.get_localized_string(LanguageHelper.Today)
            elif i == 1:
                title = LanguageHelper.get_localized_string(LanguageHelper.Yesterday)
            elif i == 2:
                title = LanguageHelper.get_localized_string(LanguageHelper.DayBeforeYesterday)
            else:
                day_name = days[date.weekday()]
                title = day_name

            date_item = MediaItem(title, url)
            date_item.set_date(date.year, date.month, date.day)
            items.append(date_item)

        Logger.debug("Pre-Processing finished")
        return data, items
Пример #16
0
    def create_json_episode_item(self, result_set):
        """ Creates a new MediaItem for an episode.

        This method creates a new MediaItem from the Regular Expression or Json
        results <result_set>. The method should be implemented by derived classes
        and are specific to the channel.

        :param list[str]|dict result_set: The result_set of the self.episodeItemRegex

        :return: A new MediaItem of type 'folder'.
        :rtype: MediaItem|None

        """

        Logger.trace(result_set)

        channel_id = result_set["channel"]
        if self.__channelId and channel_id != self.__channelId:
            return None

        title = result_set["title"]

        use_season = False
        if use_season:
            url = "https://api.kijk.nl/v2/templates/page/format/{}".format(
                result_set["id"])
        else:
            url = "https://api.kijk.nl/v1/default/sections/series-%(id)s_Episodes-season-0?limit=100&offset=0" % result_set

        item = MediaItem(title, url)
        item.description = result_set.get("synopsis", None)

        if "retina_image_pdp_header" in result_set["images"]:
            # noinspection PyTypeChecker
            item.fanart = result_set["images"]["retina_image_pdp_header"]
        if "retina_image" in result_set["images"]:
            # noinspection PyTypeChecker
            item.thumb = result_set["images"]["retina_image"]
        elif "nonretina_image" in result_set["images"]:
            # noinspection PyTypeChecker
            item.thumb = result_set["images"]["nonretina_image"]

        return item
Пример #17
0
    def add_recent_items(self, data):
        """ Performs pre-process actions for data processing.

        Accepts an data from the process_folder_list method, BEFORE the items are
        processed. Allows setting of parameters (like title etc) for the channel.
        Inside this method the <data> could be changed and additional items can
        be created.

        The return values should always be instantiated in at least ("", []).

        :param str data: The retrieve data that was loaded for the current item and URL.

        :return: A tuple of the data and a list of MediaItems that were generated.
        :rtype: tuple[str|JsonHelper,list[MediaItem]]

        """

        items = []
        today = datetime.datetime.now()
        days = LanguageHelper.get_days_list()
        for d in range(0, 7, 1):
            air_date = today - datetime.timedelta(d)
            Logger.trace("Adding item for: %s", air_date)

            # Determine a nice display date
            day = days[air_date.weekday()]
            if d == 0:
                day = LanguageHelper.get_localized_string(LanguageHelper.Today)
            elif d == 1:
                day = LanguageHelper.get_localized_string(LanguageHelper.Yesterday)

            title = "%04d-%02d-%02d - %s" % (air_date.year, air_date.month, air_date.day, day)
            url = "https://www.goplay.be/api/epg/{}/{:04d}-{:02d}-{:02d}".\
                format(self.__channel_brand, air_date.year, air_date.month, air_date.day)

            extra = MediaItem(title, url)
            extra.complete = True
            extra.dontGroup = True
            extra.set_date(air_date.year, air_date.month, air_date.day, text="")
            extra.content_type = contenttype.VIDEOS
            items.append(extra)

        return data, items
Пример #18
0
    def get_categories(self, data):
        """ Performs pre-process actions for data processing.

        Accepts an data from the process_folder_list method, BEFORE the items are
        processed. Allows setting of parameters (like title etc) for the channel.
        Inside this method the <data> could be changed and additional items can
        be created.

        The return values should always be instantiated in at least ("", []).

        :param str data: The retrieve data that was loaded for the current item and URL.

        :return: A tuple of the data and a list of MediaItems that were generated.
        :rtype: tuple[str|JsonHelper,list[MediaItem]]

        """

        Logger.info("Creating categories")
        items = []

        cats = {
            "Meest Bekeken":
            "https://api.nos.nl/mobile/videos/most-viewed/phone.json",
            "Nieuws":
            "https://api.nos.nl/nosapp/v3/items?mainCategories=nieuws&types=video&limit={0}"
            .format(self.__pageSize),
            "Sport":
            "https://api.nos.nl/nosapp/v3/items?mainCategories=sport&types=video&limit={0}"
            .format(self.__pageSize),
            "Alles":
            "https://api.nos.nl/nosapp/v3/items?types=video&limit={0}".format(
                self.__pageSize),
        }

        for cat in cats:
            item = MediaItem(cat, cats[cat])
            item.thumb = self.noImage
            item.icon = self.icon
            item.complete = True
            items.append(item)

        Logger.debug("Creating categories finished")
        return data, items
    def create_api_videopanel_type(self, result_set):
        """ Creates a new MediaItem for a folder listing

        This method creates a new MediaItem from the Regular Expression or Json
        results <result_set>. The method should be implemented by derived classes
        and are specific to the channel.

        :param dict result_set: The result_set of the self.episodeItemRegex

        :return: A new MediaItem of type 'folder'.
        :rtype: MediaItem|None

        """

        title = result_set["name"]
        folder_id = result_set["id"]
        url = self.__get_api_folder_url(folder_id)
        item = MediaItem(title, url)
        return item
Пример #20
0
    def create_api_single_type(self, result_set):
        """ Creates a MediaItem of type 'video' using the result_set from the API.

        This method creates a new MediaItem from the Regular Expression or Json
        results <result_set>. The method should be implemented by derived classes
        and are specific to the channel.

        If the item is completely processed an no further data needs to be fetched
        the self.complete property should be set to True. If not set to True, the
        self.update_video_item method is called if the item is focussed or selected
        for playback.

        :param dict result_set: The result_set of the self.episodeItemRegex

        :return: A new MediaItem of type 'video' or 'audio' (despite the method's name).
        :rtype: MediaItem|None

        This works for:
            __typename=Episode

        """

        if not self.__show_videos:
            return None

        title = result_set['name']
        url = '{}{}'.format(self.baseUrl, result_set['urls']['svtplay'])

        item = MediaItem(title, url)
        item.type = "video"
        item.description = result_set.get('longDescription')

        image_info = result_set.get("image")
        if image_info:
            item.thumb = self.__get_thumb(image_info, width=720)
            item.fanart = self.__get_thumb(image_info)
        item.isGeoLocked = result_set['restrictions']['onlyAvailableInSweden']

        duration = int(result_set.get("duration", 0))
        if duration > 0:
            item.set_info_label("duration", duration)
        return item
Пример #21
0
    def create_episode_item(self, result_set):
        """ Creates a new MediaItem for an episode.

        This method creates a new MediaItem from the Regular Expression or Json
        results <result_set>. The method should be implemented by derived classes
        and are specific to the channel.

        :param dict[str,Any] result_set: The result_set of the self.episodeItemRegex

        :return: A new MediaItem of type 'folder'.
        :rtype: MediaItem|None

        """

        Logger.trace(result_set)
        title = result_set["title"]
        date = result_set["trailers"][0]["postdate"]
        url = result_set["trailers"][0]["url"]
        thumb_url = result_set["poster"]
        if "http:" not in thumb_url:
            thumb_url = "%s%s" % (self.baseUrl, thumb_url)
        fanart = thumb_url.replace("poster.jpg", "background.jpg")

        # get the url that shows all trailers/clips. Because the json
        # only shows the most recent one.
        url = "%s%s" % (self.baseUrl, url)

        # Logger.Trace(date)
        dates = date.split(" ")
        # Logger.Trace(dates)
        day = dates[1]
        month = datehelper.DateHelper.get_month_from_name(dates[2], "en")
        year = dates[3]

        # dummy class
        item = MediaItem(title, url)
        item.icon = self.icon
        item.thumb = thumb_url.replace("poster.jpg", "poster-xlarge.jpg")
        item.fanart = fanart
        item.set_date(year, month, day)
        item.complete = True
        return item
Пример #22
0
    def create_program_items(self, result_set):
        """ Creates a new list of MediaItems for a alpha char listing.

        This method creates a new MediaItem from the Regular Expression or Json
        results <result_set>. The method should be implemented by derived classes
        and are specific to the channel.

        :param list[str]|dict result_set: The result_set of the self.episodeItemRegex

        :return: A new MediaItem of type 'folder'.
        :rtype: list[MediaItem]|MediaItem|None

        """

        Logger.trace(result_set)

        items = []
        for result in result_set["value"]:
            title = result["title"]
            item_id = result["itemId"]

            url = "{}/feeds/intl_m112/V8_0_0/{}/{}" \
                .format(self.baseUrl, self.__show_list_id, item_id)

            item = MediaItem(title, url)
            item.description = result.get("description", None)
            item.metaData["guid"] = item_id
            item.complete = True
            item.thumb = "http://mtv-intl.mtvnimages.com/uri/mgid:arc:content:{}:{}?" \
                         "ep={}&stage=live&format=jpg&quality=0.8&quality=0.85" \
                         "&width=590&height=332&crop=true"\
                .format(self.__country_id, item_id, self.__country_id)
            item.fanart = "http://mtv-intl.mtvnimages.com/uri/mgid:arc:content:{}:{}?" \
                          "ep={}&stage=live&format=jpg&quality=0.8&quality=0.85" \
                          "&width=1280&height=720&crop=true"\
                .format(self.__country_id, item_id, self.__country_id)
            item.poster = "http://mtv-intl.mtvnimages.com/uri/mgid:arc:content:{}:{}?" \
                          "ep={}&stage=live&format=jpg&quality=0.8&quality=0.85" \
                          "&width=500&height=750&crop=true"\
                .format(self.__country_id, item_id, self.__country_id)
            items.append(item)
        return items
Пример #23
0
    def create_main_list(self, data):
        """ Performs pre-process actions for data processing and creates the main menu list

        Accepts an data from the process_folder_list method, BEFORE the items are
        processed. Allows setting of parameters (like title etc) for the channel.
        Inside this method the <data> could be changed and additional items can
        be created.

        The return values should always be instantiated in at least ("", []).

        :param str data: The retrieve data that was loaded for the current item and URL.

        :return: A tuple of the data and a list of MediaItems that were generated.
        :rtype: tuple[str|JsonHelper,list[MediaItem]]

        """

        Logger.info("Performing Pre-Processing")
        items = []

        live = LanguageHelper.get_localized_string(LanguageHelper.LiveStreamTitleId)
        live_tv = "{} - TV".format(live)
        live_radio = "{} - Radio".format(live)

        links = {
            live_tv: "https://psapi.nrk.no/tv/live?apiKey={}".format(self.__api_key),
            live_radio: "https://psapi.nrk.no/radio/live?apiKey={}".format(self.__api_key),
            "Recommended": "https://psapi.nrk.no/medium/tv/recommendedprograms?maxnumber=100&startRow=0&apiKey={}".format(self.__api_key),
            "Popular": "https://psapi.nrk.no/medium/tv/popularprograms/week?maxnumber=100&startRow=0&apiKey={}".format(self.__api_key),
            "Recent": "https://psapi.nrk.no/medium/tv/recentlysentprograms?maxnumber=100&startRow=0&apiKey={}".format(self.__api_key),
            "Categories": "https://psapi.nrk.no/medium/tv/categories?apiKey={}".format(self.__api_key),
            "A - Å": "https://psapi.nrk.no/medium/tv/letters?apiKey={}".format(self.__api_key),
            "S&oslash;k": "#searchSite"
        }
        for name, url in links.items():
            item = MediaItem(name, url)
            item.complete = True
            item.HttpHeaders = self.httpHeaders
            items.append(item)

        Logger.debug("Pre-Processing finished")
        return data, items
Пример #24
0
    def create_episode_item(self, result_set):
        """ Creates a new MediaItem for an episode.

        This method creates a new MediaItem from the Regular Expression or Json
        results <result_set>. The method should be implemented by derived classes
        and are specific to the channel.

        :param list[int] result_set: The result_set of the self.episodeItemRegex

        :return: A new MediaItem of type 'folder'.
        :rtype: MediaItem|None

        """

        url = "http://gdata.youtube.com/feeds/api/users/hardwareinfovideo/uploads?max-results=%s&start-index=%s" % (
            result_set[1], result_set[0])
        title = "Hardware Info TV %04d-%04d" % (result_set[0], result_set[0] + result_set[1])
        item = MediaItem(title, url)
        item.complete = True
        return item
Пример #25
0
    def add_categories_and_search(self, data):
        """ Adds some generic items such as search and categories to the main listing.

        The return values should always be instantiated in at least ("", []).

        :param str data: The retrieve data that was loaded for the current item and URL.

        :return: A tuple of the data and a list of MediaItems that were generated.
        :rtype: tuple[str|JsonHelper,list[MediaItem]]

        """

        Logger.info("Performing Pre-Processing")
        items = []
        max_items = 200
        categories = {
            LanguageHelper.Popular:
            "https://urplay.se/api/bff/v1/search?product_type=program&query=&rows={}&start=0&view=most_viewed"
            .format(max_items),
            LanguageHelper.MostRecentEpisodes:
            "https://urplay.se/api/bff/v1/search?product_type=program&rows={}&start=0&view=published"
            .format(max_items),
            LanguageHelper.LastChance:
            "https://urplay.se/api/bff/v1/search?product_type=program&rows={}&start=0&view=last_chance"
            .format(max_items),
            LanguageHelper.Categories:
            "https://urplay.se/",
            LanguageHelper.Search:
            "searchSite"
        }

        for cat in categories:
            title = "\a.: {} :.".format(
                LanguageHelper.get_localized_string(cat))
            item = MediaItem(title, categories[cat])
            item.complete = True
            item.dontGroup = True
            items.append(item)

        Logger.debug("Pre-Processing finished")
        return data, items
Пример #26
0
    def create_json_video_item(self, result_set):
        """ This method creates a new MediaItem from the Regular Expression or Json
        results <result_set>. The method should be implemented by derived classes
        and are specific to the channel.

        If the item is completely processed an no further data needs to be fetched
        the self.complete property should be set to True. If not set to True, the
        self.update_video_item method is called if the item is focussed or selected
        for playback.

        :param list[str]|dict[str,str] result_set: The result_set of the self.episodeItemRegex

        :return: A new MediaItem of type 'video' or 'audio' (despite the method's name).
        :rtype: MediaItem|None

        """

        Logger.trace(result_set)

        main_title = result_set.get("mainTitle")
        if main_title:
            title = "{} - {}".format(main_title, result_set["title"])
        else:
            title = "%(title)s" % result_set
        url = "%s/program/%s" % (self.baseUrl, result_set["slug"])
        fanart = "https://assets.ur.se/id/%(id)s/images/1_hd.jpg" % result_set
        thumb = "https://assets.ur.se/id/%(id)s/images/1_l.jpg" % result_set
        item = MediaItem(title, url)
        item.type = "video"
        item.thumb = thumb
        item.description = result_set.get("description")
        item.fanart = fanart
        item.icon = self.icon
        if "duration" in result_set:
            item.set_info_label("duration", result_set["duration"])

        if "accessiblePlatforms" in result_set and "urplay" in result_set["accessiblePlatforms"]:
            start_time = result_set["accessiblePlatforms"]["urplay"]["startTime"]
            start_date_parts = [int(x) for x in start_time[0:10].split("-")]
            item.set_date(*start_date_parts)
        return item
Пример #27
0
    def __create_generic_item(self, result_set, expected_item_type, url_format):
        video_info = result_set["attributes"]
        name = video_info["name"]

        if expected_item_type != result_set["type"]:
            Logger.warning("Not %s, excluding %s", expected_item_type, name)
            return None

        channel_id = int(result_set["relationships"]["primaryChannel"]["data"]["id"])
        if self.primaryChannelId is not None and channel_id != self.primaryChannelId:
            return None

        item_id = result_set["id"]
        # Show the slug?
        # showSlug = video_info["alternateId"]

        url = url_format.format(item_id)
        item = MediaItem(name, url)
        item.description = video_info.get("description")

        geo_info = video_info.get("geoRestrictions", {"countries": ["world"]})
        item.isGeoLocked = "world" not in geo_info.get("countries")

        # set the images
        if "images" in result_set["relationships"]:
            thumb_id = result_set["relationships"]["images"]["data"][0]["id"]
            item.thumb = self.imageLookup.get(thumb_id, self.noImage)
            if item.thumb == self.noImage:
                Logger.warning("No thumb found for %s", thumb_id)

        # paid or not?
        if "contentPackages" in result_set["relationships"]:
            item.isPaid = not any(
                filter(
                    lambda p: p["id"].lower() == "free", result_set["relationships"]["contentPackages"]["data"]
                )
            )
        else:
            item.isPaid = False

        return item
Пример #28
0
    def create_api_program_type(self, result_set):
        """ Creates a new MediaItem for an episode.

        This method creates a new MediaItem from the Regular Expression or Json
        results <result_set>. The method should be implemented by derived classes
        and are specific to the channel.

        :param list[str]|dict result_set:   The result_set of the self.episodeItemRegex

        :return: A new MediaItem of type 'folder'.
        :rtype: MediaItem|None

        """

        # Logger.Trace(result_set)
        json = result_set
        title = json["name"]

        program_id = json["nid"]
        program_id = HtmlEntityHelper.url_encode(program_id)
        url = "https://api.tv4play.se/play/video_assets" \
              "?platform=tablet&per_page=%s&is_live=false&type=episode&" \
              "page=1&node_nids=%s&start=0" % (self.__maxPageSize, program_id,)

        item = MediaItem(title, url)
        item.description = result_set.get("description", None)

        item.thumb = result_set.get("image")
        if item.thumb is not None:
            item.thumb = "https://imageproxy.b17g.services/?format=jpg&shape=cut" \
                         "&quality=70&resize=520x293&source={}"\
                .format(HtmlEntityHelper.url_encode(item.thumb))

        item.fanart = result_set.get("image")
        if item.fanart is not None:
            item.fanart = "https://imageproxy.b17g.services/?format=jpg&shape=cut" \
                         "&quality=70&resize=1280x720&source={}" \
                .format(HtmlEntityHelper.url_encode(item.fanart))

        item.isPaid = result_set.get("is_premium", False)
        return item
Пример #29
0
    def add_live_channel(self, data):
        """ Adds the live channel.

        The return values should always be instantiated in at least ("", []).

        :param str data: The retrieve data that was loaded for the current item and URL.

        :return: A tuple of the data and a list of MediaItems that were generated.
        :rtype: tuple[str|JsonHelper,list[MediaItem]]

        """

        # Only get the first bit
        items = []

        item = MediaItem("\a.: Live :.", "http://sporza.be/cm/sporza/matchcenter/mc_livestream")
        item.type = "folder"
        item.dontGroup = True
        item.complete = False
        items.append(item)
        return data, items
    def add_search(self, data):
        """ Add a "search" item to the listing.

        :param str data: The retrieve data that was loaded for the current item and URL.

        :return: A tuple of the data and a list of MediaItems that were generated.
        :rtype: tuple[str|JsonHelper,list[MediaItem]]

        """

        Logger.info("Performing Pre-Processing")
        items = []

        title = "\a.: %s :." % (self.searchInfo.get(self.language, self.searchInfo["se"])[1], )
        Logger.trace("Adding search item: %s", title)
        search_item = MediaItem(title, "searchSite")
        search_item.dontGroup = True
        items.append(search_item)

        Logger.debug("Pre-Processing finished")
        return data, items