All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.tinymediamanager.scraper.tmdb.TmdbMovieSetMetadataProvider Maven / Gradle / Ivy

/*
 * Copyright 2012 - 2016 Manuel Laggner
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.tinymediamanager.scraper.tmdb;

import static org.tinymediamanager.scraper.tmdb.TmdbMetadataProvider.providerInfo;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tinymediamanager.scraper.MediaMetadata;
import org.tinymediamanager.scraper.MediaScrapeOptions;
import org.tinymediamanager.scraper.MediaSearchOptions;
import org.tinymediamanager.scraper.MediaSearchResult;
import org.tinymediamanager.scraper.entities.MediaArtwork;
import org.tinymediamanager.scraper.entities.MediaLanguages;
import org.tinymediamanager.scraper.entities.MediaType;
import org.tinymediamanager.scraper.util.ListUtils;
import org.tinymediamanager.scraper.util.MetadataUtil;

import com.uwetrottmann.tmdb2.Tmdb;
import com.uwetrottmann.tmdb2.entities.BaseCollection;
import com.uwetrottmann.tmdb2.entities.BaseMovie;
import com.uwetrottmann.tmdb2.entities.Collection;
import com.uwetrottmann.tmdb2.entities.CollectionResultsPage;

/**
 * The class TmdbMovieSetMetadataProvider is used to provide metadata for moviesets from tmdb
 */
class TmdbMovieSetMetadataProvider {
  private static final Logger LOGGER = LoggerFactory.getLogger(TmdbMovieSetMetadataProvider.class);

  private final Tmdb          api;

  public TmdbMovieSetMetadataProvider(Tmdb api) {
    this.api = api;
  }

  /**
   * searches a movie set with the given query parameters
   *
   * @param query
   *          the query parameters
   * @return a list of found movie sets
   * @throws Exception
   *           any exception which can be thrown while searching
   */
  List search(MediaSearchOptions query) throws Exception {
    LOGGER.debug("search() " + query.toString());

    List movieSetsFound = new ArrayList<>();

    String searchString = "";
    if (StringUtils.isEmpty(searchString) && StringUtils.isNotEmpty(query.getQuery())) {
      searchString = query.getQuery();
    }

    if (StringUtils.isEmpty(searchString)) {
      LOGGER.debug("TMDB Scraper: empty searchString");
      return movieSetsFound;
    }

    String language = query.getLanguage().getLanguage();
    if (StringUtils.isNotBlank(query.getLanguage().getCountry())) {
      language += "-" + query.getLanguage().getCountry();
    }

    synchronized (api) {
      try {
        CollectionResultsPage resultsPage = api.searchService().collection(searchString, 1, language).execute().body();
        if (resultsPage != null) {
          for (BaseCollection collection : ListUtils.nullSafe(resultsPage.results)) {
            MediaSearchResult searchResult = new MediaSearchResult(TmdbMetadataProvider.providerInfo.getId(), MediaType.MOVIE_SET);
            searchResult.setId(Integer.toString(collection.id));
            searchResult.setTitle(collection.name);
            searchResult.setPosterUrl(TmdbMetadataProvider.configuration.images.base_url + "w342" + collection.poster_path);
            searchResult.setScore(MetadataUtil.calculateScore(searchString, collection.name));
            if (searchResult.getScore() < 0.5 && providerInfo.getConfig().getValueAsBool("titleFallback")) {
              if (verifyMovieSetTitleLanguage(movieSetsFound, resultsPage, query)) {
                break;
              }
            }
            movieSetsFound.add(searchResult);
          }
        }
      }
      catch (Exception e) {
        LOGGER.debug("failed to search: " + e.getMessage());
      }
    }

    LOGGER.info("found " + movieSetsFound.size() + " results");
    return movieSetsFound;
  }

  /**
   * Language Fallback Mechanism - For Search Results
   *
   * @param query
   *          the query options
   * @param original
   *          the original movie set list
   * @param movieSetsFound
   *          the list that movie sets will be added.
   */
  private boolean verifyMovieSetTitleLanguage(List movieSetsFound, CollectionResultsPage original, MediaSearchOptions query)
      throws Exception {

    String lang = MediaLanguages.get(providerInfo.getConfig().getValue("titleFallbackLanguage")).name().replace("_", "-");
    CollectionResultsPage fallBackResultsPage = api.searchService().collection(query.getQuery(), 1, lang).execute().body();

    if (fallBackResultsPage != null && original.results != null && fallBackResultsPage.results != null) {

      movieSetsFound.clear();

      for (int i = 0; i < original.results.size(); i++) {
        BaseCollection originalCollection = original.results.get(i);
        BaseCollection fallbackCollection = fallBackResultsPage.results.get(i);

        MediaSearchResult searchResult = new MediaSearchResult(TmdbMetadataProvider.providerInfo.getId(), MediaType.MOVIE_SET);

        searchResult.setId(Integer.toString(originalCollection.id));

        if (MetadataUtil.calculateScore(query.getQuery(), originalCollection.name) >= MetadataUtil.calculateScore(query.getQuery(),
            fallbackCollection.name)) {
          searchResult.setTitle(originalCollection.name);
          searchResult.setPosterUrl(TmdbMetadataProvider.configuration.images.base_url + "w342" + originalCollection.poster_path);
          searchResult.setScore(MetadataUtil.calculateScore(query.getQuery(), originalCollection.name));
        }
        else {
          searchResult.setTitle(fallbackCollection.name);
          searchResult.setPosterUrl(TmdbMetadataProvider.configuration.images.base_url + "w342" + fallbackCollection.poster_path);
          searchResult.setScore(MetadataUtil.calculateScore(query.getQuery(), fallbackCollection.name));
        }
        movieSetsFound.add(searchResult);
      }
      return true;
    }
    else {
      return false;
    }
  }

  /**
   * Get the movie set metadata for the given search options
   *
   * @param options
   *          the options for scraping
   * @return the metadata (never null)
   * @throws Exception
   *           any exception which can be thrown while scraping
   */
  MediaMetadata getMetadata(MediaScrapeOptions options) throws Exception {
    LOGGER.debug("getMetadata() " + options.toString());

    MediaMetadata md = new MediaMetadata(TmdbMetadataProvider.providerInfo.getId());

    int tmdbId = 0;

    // tmdbId from option - own id
    try {
      tmdbId = Integer.parseInt(options.getId(TmdbMetadataProvider.providerInfo.getId()));
    }
    catch (NumberFormatException ignored) {
    }

    // tmdbId from option - legacy id
    if (tmdbId == 0) {
      tmdbId = options.getTmdbId();
    }

    if (tmdbId == 0) {
      LOGGER.warn("not possible to scrape from TMDB - no tmdbId found");
      return md;
    }

    String language = options.getLanguage().getLanguage();
    if (StringUtils.isNotBlank(options.getLanguage().getCountry())) {
      language += "-" + options.getLanguage().getCountry();
    }

    Collection collection = null;
    synchronized (api) {
      try {
        collection = api.collectionService().summary(tmdbId, language).execute().body();
        // if collection title/overview is not availbale, rescrape in the fallback language
        if (collection != null && (StringUtils.isBlank(collection.overview) || StringUtils.isBlank(collection.name))
            && providerInfo.getConfig().getValueAsBool("titleFallback")) {

          String fallbackLang = MediaLanguages.get(providerInfo.getConfig().getValue("titleFallbackLanguage")).name().replace("_", "-");
          Collection collectionInFallbackLanguage = api.collectionService().summary(tmdbId, fallbackLang).execute().body();

          if (collectionInFallbackLanguage != null) {
            Collection collectionInDefaultLanguage = null;
            if (StringUtils.isBlank(collectionInFallbackLanguage.name) || StringUtils.isBlank(collectionInFallbackLanguage.overview)) {
              collectionInDefaultLanguage = api.collectionService().summary(tmdbId).execute().body();

            }

            if (StringUtils.isBlank(collection.name) && StringUtils.isNotBlank(collectionInFallbackLanguage.name)) {
              collection.name = collectionInFallbackLanguage.name;
            }
            else if (StringUtils.isBlank(collection.name) && collectionInDefaultLanguage != null
                && StringUtils.isNotBlank(collectionInDefaultLanguage.name)) {
              collection.name = collectionInDefaultLanguage.name;
            }

            if (StringUtils.isBlank(collection.overview) && StringUtils.isNotBlank(collectionInFallbackLanguage.overview)) {
              collection.overview = collectionInFallbackLanguage.overview;
            }
            else if (StringUtils.isBlank(collection.overview) && collectionInDefaultLanguage != null
                && StringUtils.isNotBlank(collectionInDefaultLanguage.overview)) {
              collection.overview = collectionInDefaultLanguage.overview;
            }

            for (BaseMovie movie : collection.parts) {
              for (BaseMovie fallbackMovie : collectionInFallbackLanguage.parts) {
                if (movie.id.equals(fallbackMovie.id)) {
                  if (StringUtils.isBlank(movie.overview) && !StringUtils.isBlank(fallbackMovie.overview)) {
                    movie.overview = fallbackMovie.overview;
                  }
                  if (movie.title.equals(movie.original_title) && !movie.original_language.equals(options.getLanguage().getLanguage())
                      && !StringUtils.isBlank(fallbackMovie.title)) {
                    movie.title = fallbackMovie.title;
                  }
                  break;
                }
              }
            }
          }
        }
      }
      catch (Exception e) {
        LOGGER.debug("failed to get meta data: " + e.getMessage());
      }
    }

    if (collection == null) {
      return md;
    }

    md.setId(MediaMetadata.TMDB_SET, collection.id);
    md.setTitle(collection.name);
    md.setPlot(collection.overview);

    // Poster
    if (StringUtils.isNotBlank(collection.poster_path)) {
      MediaArtwork ma = new MediaArtwork(TmdbMetadataProvider.providerInfo.getId(), MediaArtwork.MediaArtworkType.POSTER);
      ma.setPreviewUrl(TmdbMetadataProvider.configuration.images.base_url + "w185" + collection.poster_path);
      ma.setDefaultUrl(TmdbMetadataProvider.configuration.images.base_url + "w342" + collection.poster_path);
      ma.setLanguage(options.getLanguage().getLanguage());
      ma.setTmdbId(tmdbId);
      md.addMediaArt(ma);
    }

    // Fanart
    if (StringUtils.isNotBlank(collection.backdrop_path)) {
      MediaArtwork ma = new MediaArtwork(TmdbMetadataProvider.providerInfo.getId(), MediaArtwork.MediaArtworkType.BACKGROUND);
      ma.setPreviewUrl(TmdbMetadataProvider.configuration.images.base_url + "w300" + collection.backdrop_path);
      ma.setDefaultUrl(TmdbMetadataProvider.configuration.images.base_url + "w1280" + collection.backdrop_path);
      ma.setLanguage(options.getLanguage().getLanguage());
      ma.setTmdbId(tmdbId);
      md.addMediaArt(ma);
    }

    // add all movies belonging to this movie set
    for (BaseMovie part : ListUtils.nullSafe(collection.parts)) {
      MediaMetadata mdSubItem = new MediaMetadata(TmdbMetadataProvider.providerInfo.getId());
      mdSubItem.setId(TmdbMetadataProvider.providerInfo.getId(), part.id);
      mdSubItem.setTitle(part.title);

      // Poster
      if (StringUtils.isNotBlank(part.poster_path)) {
        MediaArtwork ma = new MediaArtwork(TmdbMetadataProvider.providerInfo.getId(), MediaArtwork.MediaArtworkType.POSTER);
        ma.setPreviewUrl(TmdbMetadataProvider.configuration.images.base_url + "w185" + part.poster_path);
        ma.setDefaultUrl(TmdbMetadataProvider.configuration.images.base_url + "w342" + part.poster_path);
        ma.setLanguage(options.getLanguage().getLanguage());
        ma.setTmdbId(part.id);
        mdSubItem.addMediaArt(ma);
      }

      // Fanart
      if (StringUtils.isNotBlank(part.backdrop_path)) {
        MediaArtwork ma = new MediaArtwork(TmdbMetadataProvider.providerInfo.getId(), MediaArtwork.MediaArtworkType.BACKGROUND);
        ma.setPreviewUrl(TmdbMetadataProvider.configuration.images.base_url + "w300" + part.backdrop_path);
        ma.setDefaultUrl(TmdbMetadataProvider.configuration.images.base_url + "w1280" + part.backdrop_path);
        ma.setLanguage(options.getLanguage().getLanguage());
        ma.setTmdbId(part.id);
        mdSubItem.addMediaArt(ma);
      }

      mdSubItem.setReleaseDate(part.release_date);
      md.addSubItem(mdSubItem);
    }

    return md;
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy