Ejemplo n.º 1
0
    def create_channel_item(self, channel):
        """ Creates a MediaItem of type 'video' for a live channel 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 channel: 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(channel)

        title = channel["programmeTitle"]
        episode = channel.get("episodeTitle", None)
        thumb = self.noImage
        channel_title = channel["channelName"]
        description = channel.get("description")
        channel_id = channel["channel"].lower()
        if channel_id == "svtbarn":
            channel_id = "barnkanalen"

        date_format = "%Y-%m-%dT%H:%M:%S"
        start_time = DateHelper.get_date_from_string(
            channel["publishingTime"][:19], date_format)
        end_time = DateHelper.get_date_from_string(
            channel["publishingEndTime"][:19], date_format)

        if episode:
            title = "%s: %s - %s (%02d:%02d - %02d:%02d)" \
                    % (channel_title, title, episode,
                       start_time.tm_hour, start_time.tm_min, end_time.tm_hour, end_time.tm_min)
        else:
            title = "%s: %s (%02d:%02d - %02d:%02d)" \
                    % (channel_title, title,
                       start_time.tm_hour, start_time.tm_min, end_time.tm_hour, end_time.tm_min)
        channel_item = MediaItem(
            title, "https://www.svt.se/videoplayer-api/video/ch-%s" %
            (channel_id.lower(), ))
        channel_item.type = "video"
        channel_item.description = description
        channel_item.isLive = True
        channel_item.isGeoLocked = True

        channel_item.thumb = thumb
        if "titlePageThumbnailIds" in channel and channel[
                "titlePageThumbnailIds"]:
            channel_item.thumb = "https://www.svtstatic.se/image/wide/650/%s.jpg" % (
                channel["titlePageThumbnailIds"][0], )
        return channel_item
Ejemplo n.º 2
0
    def create_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[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

        """

        item = chn_class.Channel.create_video_item(self, result_set)
        if item is None:
            return item

        time_stamp = DateHelper.get_date_from_string(result_set["date"],
                                                     "%d-%m-%Y %H:%M")
        item.set_date(*time_stamp[0:6])
        return item
Ejemplo n.º 3
0
    def create_video_item_new(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 result_set: The result_set of the self.episodeItemRegex
        :type result_set: list[str]|dict[str,str]

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

        """

        Logger.trace(result_set)

        videos = self.__get_nested_value(result_set, "Assets", "Video")
        if not videos:
            Logger.warning("No video information found.")
            return None

        video_infos = [vi for vi in videos if vi["fullLength"]]
        if len(video_infos) > 0:
            video_info = video_infos[0]
        else:
            Logger.warning("No full length video found.")
            return None
        # noinspection PyTypeChecker
        video_id = video_info["id"]

        url = "http://il.srgssr.ch/integrationlayer/1.0/ue/srf/video/play/%s.json" % (
            video_id, )
        item = MediaItem(result_set["title"], url)
        item.type = "video"

        item.thumb = self.__get_nested_value(video_info, "Image",
                                             "ImageRepresentations",
                                             "ImageRepresentation", 0, "url")
        item.description = self.__get_nested_value(video_info,
                                                   "AssetMetadatas",
                                                   "AssetMetadata", 0,
                                                   "description")

        date_value = str(result_set["publishedDate"])
        date_value = date_value[0:-6]
        # 2015-01-20T22:17:59"
        date_time = DateHelper.get_date_from_string(date_value,
                                                    "%Y-%m-%dT%H:%M:%S")
        item.set_date(*date_time[0:6])

        item.icon = self.icon
        item.httpHeaders = self.httpHeaders
        item.complete = False
        return item
Ejemplo n.º 4
0
    def create_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 result_set: The result_set of the self.episodeItemRegex
        :type result_set: list[str]|dict[str,dict[str,dict]]

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

        """

        Logger.trace(result_set)

        if "fullengthSegment" in result_set and "segment" in result_set[
                "fullengthSegment"]:
            video_id = result_set["fullengthSegment"]["segment"]["id"]
            geo_location = result_set["fullengthSegment"]["segment"][
                "geolocation"]
            geo_block = False
            if "flags" in result_set["fullengthSegment"]["segment"]:
                geo_block = result_set["fullengthSegment"]["segment"][
                    "flags"].get("geoblock", None)
            Logger.trace("Found geoLocation/geoBlock: %s/%s", geo_location,
                         geo_block)
        else:
            Logger.warning("No video information found.")
            return None

        url = "http://www.srf.ch/player/webservice/videodetail/index?id=%s" % (
            video_id, )
        item = MediaItem(result_set["titleFull"], url)
        item.type = "video"

        # noinspection PyTypeChecker
        item.thumb = result_set.get("segmentThumbUrl", None)
        # apparently only the 144 return the correct HEAD info
        # item.thumb = "%s/scale/width/288" % (item.thumb, )
        # the HEAD will not return a size, so Kodi can't handle it
        # item.fanart = resultSet.get("imageUrl", None)
        item.description = result_set.get("description", "")

        date_value = str(result_set["time_published"])
        # 2015-01-20 22:17:59"
        date_time = DateHelper.get_date_from_string(date_value,
                                                    "%Y-%m-%d %H:%M:%S")
        item.set_date(*date_time[0:6])

        item.icon = self.icon
        item.httpHeaders = self.httpHeaders
        item.complete = False
        return item
Ejemplo n.º 5
0
    def create_video_item(self, result_set, include_show_title=False):
        """ 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

        """

        if not result_set:
            return None

        url_format = "https://{0}/playback/videoPlaybackInfo/{{0}}".format(
            self.baseUrlApi)
        item = self.__create_generic_item(result_set, "video", url_format)
        if item is None:
            return None

        item.type = "video"
        video_info = result_set["attributes"]  # type: dict
        if "publishStart" in video_info or "airDate" in video_info:
            date = video_info.get("airDate", video_info["publishStart"])
            # 2018-03-20T20:00:00Z
            air_date = DateHelper.get_date_from_string(
                date, date_format="%Y-%m-%dT%H:%M:%SZ")
            item.set_date(*air_date[0:6])
            if datetime.datetime(*air_date[0:6]) > datetime.datetime.now():
                item.isPaid = True

        episode = video_info.get("episodeNumber", 0)
        season = video_info.get("seasonNumber", 0)
        if episode > 0 and season > 0:
            item.name = "s{0:02d}e{1:02d} - {2}".format(
                season, episode, item.name)
            item.set_season_info(season, episode)

        if include_show_title:
            show_id = result_set["relationships"].get("show",
                                                      {}).get("data",
                                                              {}).get("id")
            if show_id:
                show = self.showLookup[show_id]
                item.name = "{0} - {1}".format(show, item.name)

        if "videoDuration" in video_info:
            item.set_info_label(MediaItem.LabelDuration,
                                video_info["videoDuration"] / 1000)
        return item
Ejemplo n.º 6
0
    def create_instalment_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[str,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["titles"]["title"]
        sub_title = result_set["titles"]["subtitle"]

        # noinspection PyTypeChecker
        if result_set.get("availability", {}).get("status",
                                                  "available") != "available":
            Logger.debug("Found '%s' with a non-available status", title)
            return None

        url = "https://psapi.nrk.no/programs/{}?apiKey={}".format(
            result_set["prfId"], self.__api_key)
        item = MediaItem(title, url)
        item.type = 'video'
        item.thumb = self.__get_image(result_set["image"], "width", "url")
        item.fanart = self.parentItem.fanart

        # noinspection PyTypeChecker
        item.isGeoLocked = result_set.get("usageRights", {}).get(
            "geoBlock", {}).get("isGeoBlocked", False)
        if sub_title and sub_title.strip():
            item.description = sub_title

        if "firstTransmissionDateDisplayValue" in result_set:
            Logger.trace("Using 'firstTransmissionDateDisplayValue' for date")
            day, month, year = result_set[
                "firstTransmissionDateDisplayValue"].split(".")
            item.set_date(year, month, day)
        elif "usageRights" in result_set and "from" in result_set[
                "usageRights"] and result_set["usageRights"][
                    "from"] is not None:
            Logger.trace("Using 'usageRights.from.date' for date")
            # noinspection PyTypeChecker
            date_value = result_set["usageRights"]["from"]["date"].split(
                "+")[0]
            time_stamp = DateHelper.get_date_from_string(
                date_value, date_format="%Y-%m-%dT%H:%M:%S")
            item.set_date(*time_stamp[0:6])

        return item
Ejemplo n.º 7
0
    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 list[str]|dict[str,any] 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)
        url = "http://playapi.mtgx.tv/v3/videos/stream/%(id)s" % result_set
        item = MediaItem(result_set["title"], url)
        item.type = "video"
        item.thumb = self.parentItem.thumb
        item.icon = self.parentItem.icon
        item.description = result_set.get("summary", None)

        aired_at = result_set.get("airedAt", None)
        if aired_at is None:
            aired_at = result_set.get("publishedAt", None)
        if aired_at is not None:
            # 2016-05-20T15:05:00+00:00
            aired_at = aired_at.split("+")[0].rstrip('Z')
            time_stamp = DateHelper.get_date_from_string(
                aired_at, "%Y-%m-%dT%H:%M:%S")
            item.set_date(*time_stamp[0:6])

        item.thumb = self.__get_thumb_image(result_set.get("image"))

        # webvttPath / samiPath
        # loginRequired
        is_premium = result_set.get("loginRequired", False)
        if is_premium and AddonSettings.hide_premium_items():
            Logger.debug("Found premium item, hiding it.")
            return None

        srt = result_set.get("samiPath")
        if not srt:
            srt = result_set.get("subtitles_webvtt")
        if srt:
            Logger.debug("Storing SRT/WebVTT path: %s", srt)
            part = item.create_new_empty_media_part()
            part.Subtitle = srt
        return item
Ejemplo n.º 8
0
    def create_json_video_item(self, result_set, prepend_serie=False):
        """ 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

        """

        Logger.trace(result_set)

        if not result_set.get("available", True):
            Logger.warning("Item not available: %s", result_set)
            return None

        item = self.create_json_episode_item(result_set)
        if item is None:
            return None

        if prepend_serie and 'seriesTitle' in result_set:
            item.name = "{0} - {1}".format(item.name,
                                           result_set['seriesTitle'])
        elif 'seriesTitle' in result_set:
            item.name = result_set['seriesTitle']

        item.type = "video"
        # Older URL
        item.url = "https://embed.kijk.nl/api/video/%(id)s?id=kijkapp&format=DASH&drm=CENC" % result_set
        # New URL
        # item.url = "https://embed.kijk.nl/video/%(id)s" % result_set

        if 'subtitle' in result_set:
            item.name = "{0} - {1}".format(item.name, result_set['subtitle'])

        if "date" in result_set:
            date = result_set["date"].split("+")[0]
            # 2016-12-25T17:58:00+01:00
            time_stamp = DateHelper.get_date_from_string(
                date, "%Y-%m-%dT%H:%M:%S")
            item.set_date(*time_stamp[0:6])

        return item
Ejemplo n.º 9
0
    def create_json_video(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[str,any|None] 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

        """

        video_id = result_set['id']

        # Categories to use
        # category = result_set["maincategory"].title()
        # subcategory = result_set["subcategory"].title()

        url = "https://api.nos.nl/mobile/video/%s/phone.json" % (video_id, )
        item = MediaItem(result_set['title'], url, type="video")
        item.icon = self.icon
        if 'image' in result_set:
            images = result_set['image']["formats"]
            matched_image = images[-1]
            for image in images:
                if image["width"] >= 720:
                    matched_image = image
                    break
            item.thumb = matched_image["url"].values()[0]

        item.description = result_set["description"]
        item.complete = False
        item.isGeoLocked = result_set.get("geoprotection", False)

        # set the date and time
        date = result_set["published_at"]
        time_stamp = DateHelper.get_date_from_string(date, date_format="%Y-%m-%dT%H:%M:%S+{0}".format(date[-4:]))
        item.set_date(*time_stamp[0:6])
        return item
Ejemplo n.º 10
0
    def create_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[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

        """

        item = chn_class.Channel.create_video_item(self, result_set)
        if item is None:
            return item

        # http://www.rtbf.be/auvio/embed/media?id=2101078&autoplay=1
        if "videoId" in result_set:
            item.url = "%s/auvio/embed/media?id=%s" % (self.baseUrl,
                                                       result_set["videoId"])
        elif "liveId" in result_set:
            item.name = "%s - %s" % (result_set["channel"].strip(), item.name)
            item.url = "%s/auvio/embed/direct?id=%s" % (self.baseUrl,
                                                        result_set["liveId"])
            item.isLive = True

        if "date" in result_set:
            # 2016-05-14T20:00:00+02:00 -> strip the hours
            time_stamp = DateHelper.get_date_from_string(
                result_set["date"].rsplit("+")[0], "%Y-%m-%dT%H:%M:%S")
            item.set_date(*time_stamp[0:6])

        return item
    def create_show_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[str,Any] 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)

        start_date = result_set['start']  # 2017-01-01T00:00:00+01:00
        start_time_stamp = DateHelper.get_date_from_string(
            start_date.split("+")[0], "%Y-%m-%dT%H:%M:%S")
        end_date = result_set['end']
        end_time_stamp = DateHelper.get_date_from_string(
            end_date.split("+")[0], "%Y-%m-%dT%H:%M:%S")
        title = "%02d:%02d - %02d:%02d: %s" % (
            start_time_stamp.tm_hour, start_time_stamp.tm_min,
            end_time_stamp.tm_hour, end_time_stamp.tm_min, result_set['title'])
        item = MediaItem(title, "", type="video")
        item.description = result_set.get("description")

        item.thumb = self.noImage
        if "image" in result_set:
            if not item.description:
                item.description = result_set["image"].get("alt", None)
            item.thumb = "https://static.538.nl/%s" % (
                result_set["image"]['src'], )

        item.icon = self.icon
        item.set_date(*start_time_stamp[0:6])
        item.description = result_set.get('description')
        if "playbackUrls" in result_set and result_set["playbackUrls"]:
            title_format = "%%02d:%%02d - %s" % (result_set['title'], )
            item.complete = True
            hour = start_time_stamp.tm_hour
            for stream in result_set["playbackUrls"]:
                if stream.startswith("//"):
                    stream = "https:%s" % (stream, )
                part = item.create_new_empty_media_part()
                part.Name = title_format % (hour, start_time_stamp.tm_min)
                part.append_media_stream(stream, 0)
                hour += 1
        elif "showUrl" in result_set and result_set["showUrl"]:
            title_format = "%%02d:%%02d - %s" % (result_set['title'], )
            stream = result_set["showUrl"]
            item.complete = True
            hour = start_time_stamp.tm_hour
            if stream.startswith("//"):
                stream = "https:%s" % (stream, )
            part = item.create_new_empty_media_part()
            part.Name = title_format % (hour, start_time_stamp.tm_min)
            part.append_media_stream(stream, 0)
            hour += 1
        else:
            Logger.warning("Found item without streams: %s", item)
            return None
        return item
Ejemplo n.º 12
0
    def create_recent_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

        """

        Logger.trace(result_set)

        show_title = result_set["abstract_name"]
        episode_title = result_set["title"]
        title = "{} - {}".format(show_title, episode_title)
        description = result_set.get("synopsis")

        uuid = result_set["uuid"]
        url = "http://www.rtl.nl/system/s4m/xldata/ux/%s?context=rtlxl&" \
              "d=pc&fmt=adaptive&version=3" % (uuid, )
        # The JSON urls do not yet work
        # url = "http://www.rtl.nl/system/s4m/vfd/version=1/d=pc/output=json/" \
        #       "fun=abstract/uuid=%s/fmt=smooth" % (uuid,)

        item = MediaItem(title.title(), url)
        item.type = "video"
        item.description = description
        item.thumb = "%s%s" % (
            self.posterBase,
            uuid,
        )

        audience = result_set.get("audience")
        Logger.debug("Found audience: %s", audience)
        item.isGeoLocked = audience == "ALLEEN_NL"
        # We can play the DRM stuff
        # item.isDrmProtected = audience == "DRM"

        station = result_set.get("station", None)
        if station:
            item.name = "{} ({})".format(item.name, station)
            icon = self.largeIconSet.get(station.lower(), None)
            if icon:
                Logger.trace("Setting icon to: %s", icon)
                item.icon = icon

        # 2018-12-05T19:30:00.000Z
        date_time = result_set.get("dateTime", None)
        if date_time:
            date_time = DateHelper.get_date_from_string(
                date_time[:-5], "%Y-%m-%dT%H:%M:%S")
            # The time is in UTC, and the show as at UTC+1
            date_time = datetime.datetime(*date_time[:6]) + datetime.timedelta(
                hours=1)
            item.name = "{:02d}:{:02d}: {}".format(date_time.hour,
                                                   date_time.minute, item.name)
            item.set_date(date_time.year, date_time.month, date_time.day,
                          date_time.hour, date_time.minute, date_time.second)
        return item
Ejemplo n.º 13
0
    def create_json_item(self, result_set):  # NOSONAR
        """ 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

        """

        Logger.trace(result_set)

        # determine the title
        program_title = result_set.get("programTitle", "") or ""
        show_title = result_set.get("title", "") or ""
        if show_title == "" and program_title != "":
            title = program_title
        elif show_title != "" and program_title == "":
            title = show_title
        elif program_title == "" and show_title == "":
            Logger.warning("Could not find title for item: %s", result_set)
            return None
        elif show_title != "" and show_title != program_title:
            title = "%s - %s" % (program_title, show_title)
        else:
            # they are the same
            title = show_title  # NOSONAR

        if "live" in result_set and result_set["live"]:
            title = "%s (&middot;Live&middot;)" % (title, )

        item_type = result_set.get("contentType")
        if "contentUrl" in result_set:
            if "versions" in result_set and bool(result_set["versions"]):
                video_id = result_set["versions"][0]["id"]
            else:
                video_id = result_set["id"]
            url = "https://api.svt.se/videoplayer-api/video/{}".format(
                video_id)
        else:
            url = result_set["url"]
        broad_cast_date = result_set.get("broadcastDate", None)

        if item_type in ("videoEpisod", "videoKlipp", "singel"):
            if "/video/" not in url and "/klipp/" not in url:
                Logger.warning(
                    "Found video item without a /video/ or /klipp/ url.")
                return None
            item_type = "video"
            if "programVersionId" in result_set:
                url = "https://www.svt.se/videoplayer-api/video/%s" % (
                    result_set["programVersionId"], )
            elif not url.startswith("http"):
                url = "%s%s" % (self.baseUrl, url)
        else:
            item_type = "folder"
            url = "%s%s" % (self.baseUrl, url)

        item = MediaItem(title, url)
        item.icon = self.icon
        item.type = item_type
        item.isGeoLocked = result_set.get("onlyAvailableInSweden", False)
        item.description = result_set.get("description", "")

        if "season" in result_set and "episodeNumber" in result_set and result_set[
                "episodeNumber"]:
            season = int(result_set["season"])
            episode = int(result_set["episodeNumber"])
            if season > 0 and episode > 0:
                item.name = "s%02de%02d - %s" % (season, episode, item.name)
                item.set_season_info(season, episode)

        thumb = self.noImage
        if self.parentItem:
            thumb = self.parentItem.thumb

        for image_key in ("image", "imageMedium", "thumbnailMedium",
                          "thumbnail", "poster"):
            if image_key in result_set and result_set[image_key] is not None:
                thumb = result_set[image_key]
                break

        item.thumb = self.__get_thumb(thumb or self.noImage)

        if broad_cast_date is not None:
            if "+" in broad_cast_date:
                broad_cast_date = broad_cast_date.rsplit("+")[0]
            time_stamp = DateHelper.get_date_from_string(
                broad_cast_date, "%Y-%m-%dT%H:%M:%S")
            item.set_date(*time_stamp[0:6])

        # Set the expire date
        expire_date = result_set.get("expireDate")
        if expire_date is not None:
            expire_date = expire_date.split("+")[0].replace("T", " ")
            year = expire_date.split("-")[0]
            if len(year
                   ) == 4 and int(year) < datetime.datetime.now().year + 50:
                item.description = \
                    "{}\n\n{}: {}".format(item.description or "", self.__expires_text, expire_date)

        length = result_set.get("materialLength", 0)
        if length > 0:
            item.set_info_label(MediaItem.LabelDuration, length)
        return item
Ejemplo n.º 14
0
    def create_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[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)

        drm_locked = False
        geo_blocked = result_set["is_geo_blocked"]

        title = result_set["title"]
        if ("_links" not in result_set or "stream" not in result_set["_links"]
                or "href" not in result_set["_links"]["stream"]):
            Logger.warning("No streams found for %s", title)
            return None

        # the description
        description = result_set["description"].strip()  # The long version
        summary = result_set["summary"].strip()  # The short version
        # Logger.Trace("Comparing:\nDesc: %s\nSumm:%s", description, summary)
        if not description.startswith(summary):
            # the descripts starts with the summary. Don't show
            description = "%s\n\n%s" % (summary, description)

        video_type = result_set["type"]
        if not video_type == "program":
            title = "%s (%s)" % (title, video_type.title())

        elif result_set["format_position"][
                "is_episodic"]:  # and resultSet["format_position"]["episode"] != "0":
            # make sure we show the episodes and seaso
            # season = int(resultSet["format_position"]["season"])
            episode = int(result_set["format_position"]["episode"] or "0")
            webisode = result_set.get("webisode", False)

            # if the name had the episode in it, translate it
            if episode > 0 and not webisode:
                description = "%s\n\n%s" % (title, description)
                title = "%s - %s %s %s %s" % (
                    result_set["format_title"], self.seasonLabel,
                    result_set["format_position"]["season"], self.episodeLabel,
                    result_set["format_position"]["episode"])
            else:
                Logger.debug(
                    "Found episode number '0' for '%s', "
                    "using name instead of episode number", title)

        url = result_set["_links"]["stream"]["href"]
        item = MediaItem(title, url)

        date_info = None
        date_format = "%Y-%m-%dT%H:%M:%S"
        if "broadcasts" in result_set and len(result_set["broadcasts"]) > 0:
            date_info = result_set["broadcasts"][0]["air_at"]
            Logger.trace("Date set from 'air_at'")

            if "playable_from" in result_set["broadcasts"][0]:
                start_date = result_set["broadcasts"][0]["playable_from"]
                playable_from = DateHelper.get_date_from_string(
                    start_date[0:-6], date_format)
                playable_from = datetime.datetime(*playable_from[0:6])
                if playable_from > datetime.datetime.now():
                    drm_locked = True

        elif "publish_at" in result_set:
            date_info = result_set["publish_at"]
            Logger.trace("Date set from 'publish_at'")

        if date_info is not None:
            # publish_at=2007-09-02T21:55:00+00:00
            info = date_info.split("T")
            date_info = info[0]
            time_info = info[1]
            date_info = date_info.split("-")
            time_info = time_info.split(":")
            item.set_date(date_info[0], date_info[1], date_info[2],
                          time_info[0], time_info[1], 0)

        item.type = "video"
        item.complete = False
        item.icon = self.icon
        item.isGeoLocked = geo_blocked
        item.isDrmProtected = drm_locked

        thumb_data = result_set['_links'].get('image', None)
        if thumb_data is not None:
            # Older version
            # item.thumbUrl = thumb_data['href'].replace("{size}", "thumb")
            item.thumb = self.__get_thumb_image(thumb_data['href'])

        item.description = description

        srt = result_set.get("sami_path")
        if not srt:
            srt = result_set.get("subtitles_webvtt")
        if srt:
            Logger.debug("Storing SRT/WebVTT path: %s", srt)
            part = item.create_new_empty_media_part()
            part.Subtitle = srt
        return item