示例#1
0
def GetMetadata(media, movie, source, TVDBid, mappingList, num=0):
    """ [tvdb4.mapping.xml] Attempt to get the ASS's episode mapping data
      [tvdb4.posters.xml] Attempt to get the ASS's image data
  """
    Log.Info('=== tvdb4.GetMetadata() ==='.ljust(157, '='))
    TVDB4_dict, TVDB4_mapping, TVDB4_xml = {}, None, None

    if movie or not source == "tvdb4":
        Log.Info("not tvdb4 mode")
        return TVDB4_dict
    Log.Info("tvdb4 mode")

    def find_tvdb4_file(file_to_find):
        try:
            folder = common.GetMediaDir(media, movie)
            while folder and folder[-1] not in ["/", "\\"]:
                filename = os.path.join(folder, file_to_find)
                if os.path.exists(filename):
                    file = Core.storage.load(os.path.realpath(filename))
                    try:
                        return XML.ElementFromString(file)
                    except:
                        return file
                folder = os.path.dirname(folder)
            else:
                Log.Info("No '{}' file detected locally".format(file_to_find))
        except Exception as e:
            Log.Error(
                "Issues in finding setup info as directories have most likely changed post scan into Plex, Exception: '%s'"
                % e)
        return ""

    Log.Info("--- tvdb4.mapping.xml ---".ljust(157, '-'))
    TVDB4_mapping = find_tvdb4_file("tvdb4.mapping")

    if TVDB4_mapping: Log.Debug("'tvdb4.mapping' file detected locally")
    else:
        TVDB4_mapping = TVDB4_mapping or common.LoadFile(
            filename=os.path.basename(TVDB4_MAPPING_URL),
            url=TVDB4_MAPPING_URL,
            cache=CACHE_1DAY *
            6)  # AniDB title database loaded once every 2 weeks
    entry = ""
    if isinstance(TVDB4_mapping, str): entry = TVDB4_mapping
    else:
        entry = common.GetXml(TVDB4_mapping,
                              "/tvdb4entries/anime[@tvdbid='%s']" % TVDBid)
        if not entry:
            Log.Error("TVDBid '%s' is not found in mapping file" % TVDBid)
    if entry:
        for line in filter(None, entry.strip().splitlines()):
            season = line.strip().split("|")
            for absolute_episode in range(int(season[1]), int(season[2]) + 1):
                SaveDict((str(int(season[0])), str(absolute_episode)),
                         mappingList, 'absolute_map', str(absolute_episode))
            SaveDict(True if "(unknown length)" in season[3] else False,
                     mappingList, 'absolute_map', 'unknown_series_length')
            SaveDict(str(int(season[0])), mappingList, 'absolute_map',
                     'max_season')

    Log.Info("--- tvdb4.posters.xml ---".ljust(157, '-'))
    TVDB4_xml = find_tvdb4_file(os.path.basename(TVDB4_POSTERS_URL))

    if TVDB4_xml: Log.Debug("'tvdb4.posters.xml' file detected locally")
    else:
        TVDB4_xml = TVDB4_xml or common.LoadFile(
            filename=os.path.basename(TVDB4_POSTERS_URL),
            url=TVDB4_POSTERS_URL,
            cache=CACHE_1DAY *
            6)  # AniDB title database loaded once every 2 weeks
    if TVDB4_xml:
        seasonposternum = 0
        entry = common.GetXml(TVDB4_xml,
                              "/tvdb4entries/posters[@tvdbid='%s']" % TVDBid)
        if not entry:
            Log.Error("TVDBid '%s' is not found in posters file" % TVDBid)
        for line in filter(None, entry.strip().splitlines()):
            season, url = line.strip().split("|", 1)
            season = season.lstrip("0") if season.lstrip("0") else "0"
            seasonposternum += 1
            SaveDict(("TheTVDB/seasons/%s-%s-%s" %
                      (TVDBid, season, os.path.basename(url)), 1, None),
                     TVDB4_dict, 'seasons', season, 'posters', url)

    Log.Info("--- return ---".ljust(157, '-'))
    Log.Info("absolute_map: {}".format(
        DictString(Dict(mappingList, 'absolute_map', default={}), 0)))
    Log.Info("TVDB4_dict: {}".format(DictString(TVDB4_dict, 4)))
    return TVDB4_dict
示例#2
0
def GetMetadata(myanimelistId, type, media):
    Log.Info("=== MyAnimeList.GetMetadata() ===".ljust(157, '='))
    detailUrl = MYANIMELIST_URL_DETAILS.format(id=myanimelistId)
    Log.Info("URL : " + str(detailUrl))
    try:
        json = JSON.ObjectFromString(
            HTTP.Request(detailUrl,
                         sleep=2.0,
                         cacheTime=MYANIMELIST_CACHE_TIME).content)
    except Exception as e:
        Log.Error("No Detail Information were available " + str(e))
        return
    result = {}
    if json:
        if Dict(json, "id"):
            SaveDict(str(Dict(json, "id")), result, "id")
            Log.Debug("ID:             " + str(Dict(json, "id")))
        if Dict(json, "title"):
            SaveDict(str(Dict(json, "title")), result, "title")
            Log.Debug("Title:          " + str(Dict(json, "title")))
        if Dict(json, "synopsis"):
            SaveDict(
                str(re.sub(re.compile('<.*?>'), '', Dict(json, "synopsis"))),
                result, "summary")
            Log.Debug("Summary:        " + str(Dict(json, "synopsis")))
        if Dict(json, "members_score"):
            SaveDict(float(Dict(json, "members_score")), result, "rating")
            Log.Debug("Rating:         " + str(Dict(json, "members_score")))
        if Dict(json, "classification"):
            SaveDict(str(Dict(json, "classification")), result,
                     "content_rating")
            Log.Debug("Content Rating: " + str(Dict(json, "classification")))
        if Dict(json, "duration"):
            SaveDict(int(Dict(json, "duration") * 60000), result, "duration")
            Log.Debug("Duration:       " + str(Dict(json, "duration") * 60000))
        if Dict(json, "start_date"):
            SaveDict(Dict(json, "start_date"), result,
                     "originally_available_at")
            Log.Debug("Release date:   " + str(Dict(json, "start_date")))
        if Dict(json, "image_url"):
            SaveDict((Dict(json, "image_url"), 1, None), result, 'poster',
                     Dict(json, "image_url"))
            Log.Debug("Cover:          " + str(Dict(json, "image_url")))
        for genre in Dict(json, "genres") if Dict(
                json, "genres") and len(Dict(json, "genres")) > 0 else []:
            SaveDict([str(genre)], result, "genres")
            Log.Debug("Genres: " + str(Dict(json, "genres")))

        ### TODO: Switch to Studios when they are available in the API (or add Producers to metadata when this is possible in Plex)
        #if Dict(json, "producers") and len(Dict(json, "producers")) > 0:
        #  apiAnimeProducers = ""
        #  for idx, producer in enumerate(Dict(json, "producers")):  apiAnimeProducers += str(producer) + ", "
        #  SaveDict(str(apiAnimeProducers[:-2]), result, "studio")
        #  Log.Debug("Producers: " + str(Dict(json, "producers")))

        if type == "tvshow":
            Log.Debug("Adding TV-Show specific data")
            Log.Debug("Episodes: " + str(Dict(json, "episodes")))
        #   metadata.seasons[1].episode_count = int( Dict(json, "episodes") or len(media.seasons[1].episodes))
        #   pages = int(math.ceil(float(metadata.seasons[1].episode_count) / 100))  # fetch the episodes in 100 chunks
        #   if pages is not None:
        #     for page in range(1, pages + 1):
        #       episodesUrl = MYANIMELIST_URL_EPISODES.format(id=metadata.id,page=page)
        #       try:
        #         Log.Info("Fetching URL " + str(episodesUrl))
        #         episodeResult = JSON.ObjectFromString(HTTP.Request(episodesUrl, sleep=2.0, cacheTime=MYANIMELIST_CACHE_TIME).content)
        #       except Exception as e:  Log.Info("episode results could not be requested " + str(e));  return
        #       if "error" in episodeResult:
        #         Log.Warn("Episode Information are not available (" + str(episodeResult["error"]) + ") (might want to add them to MyAnimeList.net)!")
        #         break
        #
        #       for episode in episodeResult:
        #         apiEpisodeNumber  = Dict(json, "number"  )
        #         apiEpisodeTitle   = Dict(json, "title"   )
        #         apiEpisodeAirDate = Dict(json, "air_date")
        #         if apiEpisodeNumber is not None:
        #           plexEpisode                         = metadata.seasons[1].episodes[int(apiEpisodeNumber)]
        #           plexEpisode.title                   = str(apiEpisodeTitle) if apiEpisodeTitle else "Episode: #" + str(apiEpisodeNumber)
        #           plexEpisode.originally_available_at = datetime.strptime(str(apiEpisodeAirDate), "%Y-%m-%d") if apiEpisodeAirDate else datetime.now()
        #         Log.Debug("Episode " + str(apiEpisodeNumber) + ": " + str(apiEpisodeTitle) + " - " + str(apiEpisodeAirDate))
        #
        if type == "movie":
            Log.Debug("Adding Movie specific data, nothing specific to add")

    Log.Info("MyAnimeList_dict: {}".format(DictString(result, 4)))
    Log.Info("--- return ---".ljust(157, '-'))
    return result