Exemplo n.º 1
0
def series_modal(request):
    content_discovery = ContentDiscovery()
    content_manager = ContentManager()
    report_modal = request.GET.get("report_modal", False)

    # Get the ID from the URL
    tmdb_id = request.GET.get("tmdb_id", None)
    tvdb_id = request.GET.get("tvdb_id", None)

    # Determine the TVDB ID
    if tvdb_id:
        pass

    elif tmdb_id:
        tvdb_id = content_discovery.get_external_ids(tmdb_id, "tv")["tvdb_id"]

    # Check if the show is already within Sonarr's collection
    requested_show = content_manager.get(tvdb_id=tvdb_id)

    # If it doesn't already exists, add then add it
    if requested_show is None:

        sonarr_params = obtain_sonarr_parameters(content_discovery,
                                                 content_manager, tmdb_id,
                                                 tvdb_id)

        requested_show = content_manager.add(
            tvdb_id=tvdb_id,
            quality_profile_id=sonarr_params["sonarr_profile_id"],
            root_dir=sonarr_params["sonarr_root"],
            series_type=sonarr_params["series_type"],
            season_folders=sonarr_params["season_folders"],
        )

    # Keep refreshing until we get the series from Sonarr
    series = content_manager.get(tvdb_id=tvdb_id,
                                 obtain_season_info=True,
                                 force_update_cache=True)
    if series is None:
        series_fetch_retries = 0
        while series is None:
            if series_fetch_retries > MAX_SERIES_FETCH_RETRIES:
                break
            series_fetch_retries = series_fetch_retries + 1
            series = content_manager.get(tvdb_id=tvdb_id,
                                         obtain_season_info=True,
                                         force_update_cache=True)
            log.handler(
                "Sonarr did not have the series information! Conreq is waiting...",
                log.INFO,
                __logger,
            )

    context = generate_context({
        "seasons": series["seasons"],
        "tvdb_id": tvdb_id,
        "report_modal": report_modal
    })
    template = loader.get_template("modal/series_selection.html")
    return HttpResponse(template.render(context, request))
Exemplo n.º 2
0
def content_preview_modal(request):
    content_discovery = ContentDiscovery()

    # Get the ID from the URL
    tmdb_id = request.GET.get("tmdb_id", None)
    content_type = request.GET.get("content_type", None)

    if tmdb_id and content_type:
        # Fetch and process
        content = content_discovery.get_by_tmdb_id(tmdb_id,
                                                   content_type,
                                                   obtain_extras=False)
        set_single_availability(content)
        preprocess_tmdb_result(content)

        # Check if the user has already requested this
        requested = False
        if UserRequest.objects.filter(
                content_id=content["id"],
                source="tmdb",
                content_type=content["content_type"],
        ):
            requested = True

        context = generate_context({
            "content": content,
            "requested": requested
        })
        template = loader.get_template("modal/content_preview.html")
        return HttpResponse(template.render(context, request))
Exemplo n.º 3
0
def series_modal(user, tmdb_id=None, tvdb_id=None):
    # Validate login status
    if user.is_authenticated:
        content_discovery = ContentDiscovery()
        content_manager = ContentManager()
        # Determine the TVDB ID
        if tvdb_id is not None:
            pass

        elif tmdb_id is not None:
            tvdb_id = content_discovery.get_external_ids(tmdb_id,
                                                         "tv")["tvdb_id"]

        # Check if the show is already within Sonarr's collection
        requested_show = content_manager.get(tvdb_id=tvdb_id)

        # If it doesn't already exists, add then add it
        if requested_show is None:

            sonarr_params = obtain_sonarr_parameters(content_discovery,
                                                     content_manager, tmdb_id,
                                                     tvdb_id)

            requested_show = content_manager.add(
                tvdb_id=tvdb_id,
                quality_profile_id=sonarr_params["sonarr_profile_id"],
                root_dir=sonarr_params["sonarr_root"],
                series_type=sonarr_params["series_type"],
                season_folders=sonarr_params["season_folders"],
            )

        # Keep refreshing until we get the series from Sonarr
        series = content_manager.get(tvdb_id=tvdb_id, obtain_season_info=True)
        if series is None:
            series_fetch_retries = 0
            while series is None:
                if series_fetch_retries > MAX_SERIES_FETCH_RETRIES:
                    break
                series_fetch_retries = series_fetch_retries + 1
                sleep(0.5)
                series = content_manager.get(tvdb_id=tvdb_id,
                                             obtain_season_info=True,
                                             force_update_cache=True)
                log.handler(
                    "Retrying content fetch!",
                    log.INFO,
                    __logger,
                )

        context = generate_context({"seasons": series["seasons"]})
        return render_to_string("modal/series_selection.html", context)
Exemplo n.º 4
0
def convert_card_to_tmdb(index, all_results):
    content_discovery = ContentDiscovery()
    # NOTE: For some reason, overriding values in all_results requires the list and index value.
    # It will NOT work if attempting to change values by reference (ex. card = newCard).

    # Convert Sonarr cards to TMDB
    if all_results[index].__contains__("tvdbId"):
        try:
            tmdb_query = content_discovery.get_by_tvdb_id(all_results[index]["tvdbId"])
            tmdb_result = tmdb_query["tv_results"][0]
            all_results[index] = tmdb_result
            all_results[index]["tmdbCard"] = True
        except:
            pass
Exemplo n.º 5
0
def request_content(request):
    # User submitted a new request
    if request.method == "POST":
        request_parameters = json.loads(request.body.decode("utf-8"))
        log.handler(
            "Request received: " + str(request_parameters),
            log.INFO,
            _logger,
        )

        content_manager = ContentManager()
        content_discovery = ContentDiscovery()

        # TV show was requested
        if request_parameters["content_type"] == "tv":
            # Try to obtain a TVDB ID (from params or fetch it from TMDB)
            tvdb_id = None
            tmdb_id = None
            if request_parameters.__contains__("tvdb_id"):
                tvdb_id = request_parameters["tvdb_id"]
            if request_parameters.__contains__("tmdb_id"):
                tmdb_id = request_parameters["tmdb_id"]
            if not tvdb_id and tmdb_id:
                tvdb_id = content_discovery.get_external_ids(tmdb_id,
                                                             "tv")["tvdb_id"]

            # Request the show by the TVDB ID
            if tvdb_id:
                sonarr_request(
                    tvdb_id,
                    tmdb_id,
                    request,
                    request_parameters,
                    content_manager,
                    content_discovery,
                )

            else:
                return HttpResponseForbidden()

        # Movie was requested
        elif request_parameters["content_type"] == "movie":
            tmdb_id = request_parameters["tmdb_id"]
            radarr_request(tmdb_id, request, content_manager,
                           content_discovery)

        # The request succeeded
        return JsonResponse({"success": True})

    return HttpResponseForbidden()
Exemplo n.º 6
0
def set_single_availability(card):
    """Sets the availabily on a single card."""
    content_manager = ContentManager()
    content_discovery = ContentDiscovery()
    try:
        # Compute the availability of a Sonarr card
        if card.__contains__("tvdbId"):
            content = content_manager.get(tvdb_id=card["tvdbId"])
            if content is not None:
                card["availability"] = content["availability"]

        # Compute the availability of a Radarr card
        elif card.__contains__("tmdbId"):
            content = content_manager.get(tmdb_id=card["tmdbId"])
            if content is not None:
                card["availability"] = content["availability"]

        # Compute the availability of TV show
        elif card.__contains__("name"):
            external_id = content_discovery.get_external_ids(card["id"], "tv")
            content = content_manager.get(tvdb_id=external_id["tvdb_id"])
            if content is not None:
                card["availability"] = content["availability"]

        # Compute the availability of movie
        elif card.__contains__("title"):
            content = content_manager.get(tmdb_id=card["id"])
            if content is not None:
                card["availability"] = content["availability"]

        # Something unexpected was passed in
        else:
            log.handler(
                "Card did not contain content_type, title, or name!",
                log.WARNING,
                _logger,
            )
            return card

    except:
        log.handler(
            "Could not determine the availability of card!\n" + str(card),
            log.ERROR,
            _logger,
        )
        return card
Exemplo n.º 7
0
def collection(request):
    collection_id = request.GET.get("collection_id", None)

    if collection_id:
        content_discovery = ContentDiscovery()

        tmdb_collection = content_discovery.collections(collection_id)

        if not isinstance(tmdb_collection, dict) or not tmdb_collection:
            tmdb_collection = None

        else:
            set_many_availability(tmdb_collection["parts"])

        context = generate_context({"collection": tmdb_collection})
        template = loader.get_template("viewport/more_info_collection.html")
        return HttpResponse(template.render(context, request))
Exemplo n.º 8
0
def set_single_conreq_status(card):
    content_manager = ContentManager()
    content_discovery = ContentDiscovery()
    try:
        # Compute conreq status of a Sonarr card
        if card.__contains__("tvdbId"):
            content = content_manager.get(tvdb_id=card["tvdbId"])
            if content is not None:
                card["conreqStatus"] = content["conreqStatus"]

        # Compute conreq status of a Radarr card
        elif card.__contains__("tmdbId"):
            content = content_manager.get(tmdb_id=card["tmdbId"])
            if content is not None:
                card["conreqStatus"] = content["conreqStatus"]

        # Compute conreq status of TV show
        elif card.__contains__("name"):
            external_id = content_discovery.get_external_ids(card["id"], "tv")
            content = content_manager.get(tvdb_id=external_id["tvdb_id"])
            if content is not None:
                card["conreqStatus"] = content["conreqStatus"]

        # Compute conreq status of movie
        elif card.__contains__("title"):
            content = content_manager.get(tmdb_id=card["id"])
            if content is not None:
                card["conreqStatus"] = content["conreqStatus"]

        # Something unexpected was passed in
        else:
            log.handler(
                "Card did not contain contentType, title, or name!",
                log.WARNING,
                __logger,
            )
            return card

    except:
        log.handler(
            "Could not determine Conreq Status of card!\n" + card,
            log.ERROR,
            __logger,
        )
        return card
Exemplo n.º 9
0
def discover_movies(request):
    content_discovery = ContentDiscovery()
    template = loader.get_template("viewport/discover.html")

    # Get the page number from the URL
    page = int(request.GET.get("page", 1))

    # Search for TV content
    tmdb_results = content_discovery.movies(page)["results"]

    # Set the availability for all cards
    set_many_availability(tmdb_results)

    context = generate_context({
        "all_cards": tmdb_results,
    })

    return HttpResponse(template.render(context, request))
Exemplo n.º 10
0
def discover_tv(request):
    content_discovery = ContentDiscovery()
    template = loader.get_template("viewport/discover.html")

    # Get the page number from the URL
    page = int(request.GET.get("page", 1))

    # Search for TV content
    tmdb_results = content_discovery.tv(page, page_multiplier=2)["results"]

    # Set conreq status for all cards
    set_many_conreq_status(tmdb_results)

    context = generate_context({
        "all_cards": tmdb_results,
    })

    return HttpResponse(template.render(context, request))
Exemplo n.º 11
0
def recommended(request):
    tmdb_id = request.GET.get("tmdb_id", None)
    content_type = request.GET.get("content_type", None)
    if tmdb_id and content_type:
        content_discovery = ContentDiscovery()

        tmdb_recommended = content_discovery.similar_and_recommended(
            tmdb_id, content_type)

        if not isinstance(tmdb_recommended, dict) or not tmdb_recommended:
            tmdb_recommended = None

        else:
            set_many_availability(tmdb_recommended["results"])

        context = generate_context({"recommended": tmdb_recommended})
        template = loader.get_template("viewport/more_info_recommended.html")
        return HttpResponse(template.render(context, request))
Exemplo n.º 12
0
def generate_requests_cards(user_requests):
    """Takes in a DB query containing requests, and pops out a list of their current request status"""
    content_discovery = ContentDiscovery()
    content_manager = ContentManager()
    all_cards = []
    function_list = []
    for request in user_requests.values():
        function_list.append(
            {
                "function": __generate_request_card,
                "args": [request, content_discovery, content_manager],
            }
        )

    all_cards = threaded_execution_unique_args(function_list)
    content_discovery.determine_id_validity({"results": all_cards})
    set_many_availability(all_cards)

    return all_cards
Exemplo n.º 13
0
def search(request):
    content_discovery = ContentDiscovery()
    searcher = Search()

    # Get the ID from the URL
    query = request.GET.get("query", "")
    content_type = request.GET.get("content_type", None)
    template = loader.get_template("viewport/search.html")

    # Determine which search method to use (tv/movie/all)
    if content_type == "tv":
        arr_results = searcher.television(query)
    elif content_type == "movie":
        arr_results = searcher.movie(query)
    else:
        arr_results = searcher.all(query)

    # Attempt to convert cards to TMDB equivalents
    thread_list = []
    for index in range(0, len(arr_results)):
        thread = Thread(target=convert_card_to_tmdb, args=[index, arr_results])
        thread.start()
        thread_list.append(thread)

    # Wait for computation to complete
    for thread in thread_list:
        thread.join()

    # Generate conreq status
    content_discovery.determine_id_validity({"results": arr_results})
    set_many_conreq_status(arr_results)

    context = generate_context(
        {
            "all_cards": arr_results,
        }
    )
    return HttpResponse(template.render(context, request))
Exemplo n.º 14
0
def more_info(request):
    content_discovery = ContentDiscovery()
    template = loader.get_template("viewport/more_info.html")
    thread_list = []

    # Get the ID from the URL
    tmdb_id = request.GET.get("tmdb_id", None)
    tvdb_id = request.GET.get("tvdb_id", None)

    if tmdb_id:
        content_type = request.GET.get("content_type", None)

        # Get all the basic metadata for a given ID
        content = content_discovery.get_by_tmdb_id(tmdb_id, content_type)

        # Determine the availability of the current TMDB ID
        set_single_availability(content)

        # Pre-process data attributes within tmdb_result
        preprocess_tmdb_result(content)

        # Get collection information
        if (content.__contains__("belongs_to_collection")
                and content["belongs_to_collection"] is not None):
            tmdb_collection_id = content["belongs_to_collection"]["id"]
        else:
            tmdb_collection_id = None

        # Check if the user has already requested this
        requested = False
        if UserRequest.objects.filter(
                content_id=content["id"],
                source="tmdb",
                content_type=content["content_type"],
        ):
            requested = True

        # Generate context for page rendering
        context = generate_context({
            "content": content,
            "collection_id": tmdb_collection_id,
            "content_type": content["content_type"],
            "requested": requested,
        })

    elif tvdb_id:
        searcher = Search()
        # Fallback for TVDB
        content = searcher.television(tvdb_id)[0]
        thread_list = []

        # Preprocess results
        preprocess_arr_result(content)

        # Determine the availability
        set_single_availability(content)

        # Generate context for page rendering
        context = generate_context({
            "content": content,
            "content_type": content["contentType"],
        })

    # Render the page
    return HttpResponse(template.render(context, request))
Exemplo n.º 15
0
def my_issues(request):
    # Get the parameters from the URL
    content_discovery = ContentDiscovery()
    content_manager = ContentManager()
    reported_issues = (
        ReportedIssue.objects.filter(reported_by=request.user).order_by("id").reverse()
    )

    all_cards = []
    for entry in reported_issues.values(
        "reported_by__username",
        "content_id",
        "source",
        "resolved",
        "content_type",
        "issues",
        "seasons",
        "episodes",
    ):
        # Fetch TMDB entry
        if entry["source"] == "tmdb":
            card = content_discovery.get_by_tmdb_id(
                tmdb_id=entry["content_id"],
                content_type=entry["content_type"],
                obtain_extras=False,
            )
            if card is not None:
                card["tmdbCard"] = True
                all_cards.append({**card, **entry})

        # Fetch TVDB entry
        if entry["source"] == "tvdb":
            # Attempt to convert card to TMDB
            conversion = content_discovery.get_by_tvdb_id(tvdb_id=entry["content_id"])
            # Conversion found
            if conversion.__contains__("tv_results") and conversion["tv_results"]:
                card = conversion["tv_results"][0]
                card["tmdbCard"] = True
                all_cards.append({**card, **entry})

                # Convert all requests to use this new ID
                old_requests = ReportedIssue.objects.filter(
                    content_id=entry["content_id"], source="tvdb"
                )
                old_requests.update(content_id=card["id"], source="tmdb")

            # Fallback to checking sonarr's database
            else:
                card = content_manager.get(tvdb_id=entry["content_id"])
                all_cards.append({**card, **entry})

        if card is None:
            log.handler(
                entry["content_type"]
                + " from "
                + entry["source"]
                + " with ID "
                + entry["content_id"]
                + " no longer exists!",
                log.WARNING,
                __logger,
            )

    context = generate_context({"all_cards": all_cards})
    template = loader.get_template("viewport/reported_issues.html")
    return HttpResponse(template.render(context, request))
Exemplo n.º 16
0
def more_info(request):
    content_discovery = ContentDiscovery()
    template = loader.get_template("viewport/more_info.html")
    thread_list = []

    # Get the ID from the URL
    tmdb_id = request.GET.get("tmdb_id", None)
    tvdb_id = request.GET.get("tvdb_id", None)

    if tmdb_id:
        content_type = request.GET.get("content_type", None)

        # Get all the basic metadata for a given ID
        content = content_discovery.get_by_tmdb_id(tmdb_id, content_type)

        # Get recommended results
        similar_and_recommended_thread = ReturnThread(
            target=content_discovery.similar_and_recommended,
            args=[tmdb_id, content_type],
        )
        similar_and_recommended_thread.start()

        # Determine the availability of the current TMDB ID
        thread = Thread(target=set_single_availability, args=[content])
        thread.start()
        thread_list.append(thread)

        # Pre-process data attributes within tmdb_result
        thread = Thread(target=preprocess_tmdb_result, args=[content])
        thread.start()
        thread_list.append(thread)

        # Get collection information
        if (content.__contains__("belongs_to_collection")
                and content["belongs_to_collection"] is not None):
            tmdb_collection = True
            tmdb_collection_thread = ReturnThread(
                target=content_discovery.collections,
                args=[content["belongs_to_collection"]["id"]],
            )
            tmdb_collection_thread.start()
        else:
            tmdb_collection = None

        # Recommended content
        tmdb_recommended = similar_and_recommended_thread.join()
        if not isinstance(tmdb_recommended,
                          dict) or len(tmdb_recommended) == 0:
            tmdb_recommended = None

        # Determine the availability for all recommended content
        thread = Thread(target=set_many_availability,
                        args=[tmdb_recommended["results"]])
        thread.start()
        thread_list.append(thread)

        # Wait for thread computation to complete
        for thread in thread_list:
            thread.join()
        if tmdb_collection is not None:
            tmdb_collection = tmdb_collection_thread.join()

        # Check if the user has already requested this
        requested = False
        if UserRequest.objects.filter(
                content_id=content["id"],
                source="tmdb",
                content_type=content["content_type"],
        ):
            requested = True

        # Generate context for page rendering
        context = generate_context({
            "content": content,
            "recommended": tmdb_recommended,
            "collection": tmdb_collection,
            "content_type": content["content_type"],
            "requested": requested,
        })

    elif tvdb_id:
        searcher = Search()
        # Fallback for TVDB
        content = searcher.television(tvdb_id)[0]
        thread_list = []

        # Preprocess results
        thread = Thread(target=preprocess_arr_result, args=[content])
        thread.start()
        thread_list.append(thread)

        # Determine the availability
        thread = Thread(target=set_single_availability, args=[content])
        thread.start()
        thread_list.append(thread)

        # Wait for thread computation to complete
        for thread in thread_list:
            thread.join()

        # Generate context for page rendering
        context = generate_context({
            "content": content,
            "content_type": content["contentType"],
        })

    # Render the page
    return HttpResponse(template.render(context, request))
Exemplo n.º 17
0
    async def __request_content(self, content):
        content_manager = await database_sync_to_async(ContentManager)()
        content_discovery = ContentDiscovery()

        # TV show was requested
        if content["parameters"]["content_type"] == "tv":
            # Obtain the TVDB ID if needed
            tvdb_id = content["parameters"]["tvdb_id"]
            tmdb_id = content["parameters"]["tmdb_id"]
            if tvdb_id is None and tmdb_id is not None:
                tvdb_id = content_discovery.get_external_ids(tmdb_id,
                                                             "tv")["tvdb_id"]

            # Request the show by the TVDB ID
            if tvdb_id is not None:
                # Check if the show is already within Sonarr's collection
                preexisting_show = content_manager.get(tvdb_id=tvdb_id)

                # If it doesn't already exists, add then request it
                if preexisting_show is None:
                    sonarr_params = await database_sync_to_async(
                        obtain_sonarr_parameters)(content_discovery,
                                                  content_manager, tmdb_id,
                                                  tvdb_id)
                    new_show = content_manager.add(
                        tvdb_id=tvdb_id,
                        quality_profile_id=sonarr_params["sonarr_profile_id"],
                        root_dir=sonarr_params["sonarr_root"],
                        series_type=sonarr_params["series_type"],
                        season_folders=sonarr_params["season_folders"],
                    )
                    if new_show.__contains__("id"):
                        content_manager.request(
                            sonarr_id=new_show["id"],
                            seasons=content["parameters"]["seasons"],
                            episode_ids=content["parameters"]["episode_ids"],
                        )
                    else:
                        log.handler(
                            "Show was added to Sonarr, but Sonarr did not return an ID!",
                            log.ERROR,
                            self.__logger,
                        )
                else:
                    content_manager.request(
                        sonarr_id=preexisting_show["id"],
                        seasons=content["parameters"]["seasons"],
                        episode_ids=content["parameters"]["episode_ids"],
                    )

        # Movie was requested
        elif content["parameters"]["content_type"] == "movie":
            radarr_params = await database_sync_to_async(
                obtain_radarr_parameters)(content_discovery, content_manager,
                                          content["parameters"]["tmdb_id"])

            # Check if the movie is already within Radarr's collection
            preexisting_movie = content_manager.get(
                tmdb_id=content["parameters"]["tmdb_id"])

            # If it doesn't already exists, add then request it
            if preexisting_movie is None:
                new_movie = content_manager.add(
                    tmdb_id=content["parameters"]["tmdb_id"],
                    quality_profile_id=radarr_params["radarr_profile_id"],
                    root_dir=radarr_params["radarr_root"],
                )
                if new_movie.__contains__("id"):
                    content_manager.request(radarr_id=new_movie["id"])
                else:
                    log.handler(
                        "Movie was added to Radarr, but Radarr did not return an ID!",
                        log.ERROR,
                        self.__logger,
                    )

            # If it already existed, just request it
            else:
                content_manager.request(radarr_id=preexisting_movie["id"])
Exemplo n.º 18
0
def generate_issue_cards(reported_issues):
    """Retruns a list of cards"""
    content_discovery = ContentDiscovery()
    content_manager = ContentManager()
    all_cards = []
    for entry in reported_issues.values(
        "id",
        "reported_by__username",
        "content_id",
        "source",
        "resolved",
        "content_type",
        "issues",
        "seasons",
        "episodes",
    ):
        # Fetch TMDB entry
        if entry["source"] == "tmdb":
            card = content_discovery.get_by_tmdb_id(
                tmdb_id=entry["content_id"],
                content_type=entry["content_type"],
                obtain_extras=False,
            )
            if card is not None:
                all_cards.append({**card, **entry})

        # Fetch TVDB entry
        if entry["source"] == "tvdb":
            # Attempt to convert card to TMDB
            conversion = content_discovery.get_by_tvdb_id(tvdb_id=entry["content_id"])
            # Conversion found
            if conversion.__contains__("tv_results") and conversion["tv_results"]:
                card = conversion["tv_results"][0]
                all_cards.append({**card, **entry})

                # Convert all requests to use this new ID
                old_requests = ReportedIssue.objects.filter(
                    content_id=entry["content_id"], source="tvdb"
                )
                old_requests.update(content_id=card["id"], source="tmdb")
                log.handler(
                    entry["content_type"]
                    + " from "
                    + entry["source"]
                    + " with ID "
                    + entry["content_id"]
                    + " has been converted to TMDB",
                    log.INFO,
                    _logger,
                )

            # Fallback to checking sonarr's database
            else:
                card = content_manager.get(tvdb_id=entry["content_id"])
                all_cards.append({**card, **entry})

        if card is None:
            log.handler(
                entry["content_type"]
                + " from "
                + entry["source"]
                + " with ID "
                + entry["content_id"]
                + " no longer exists!",
                log.WARNING,
                _logger,
            )

    return all_cards
Exemplo n.º 19
0
def all_requests(request):
    template = loader.get_template("viewport/requests.html")

    content_discovery = ContentDiscovery()
    content_manager = ContentManager()
    user_requests = UserRequest.objects.all().order_by("id").reverse()

    all_cards = []
    request_dict = {}

    for entry in user_requests.values(
            "content_id",
            "source",
            "content_type",
            "requested_by__username",
    ):
        # Fetch TMDB entry
        if entry["source"] == "tmdb" and request_is_unique(
                entry, request_dict):
            card = content_discovery.get_by_tmdb_id(
                tmdb_id=entry["content_id"],
                content_type=entry["content_type"],
                obtain_extras=False,
            )
            if card is not None:
                card["tmdbCard"] = True
                card["requested_by"] = entry["requested_by__username"]
                all_cards.append(card)

        # Fetch TVDB entry
        if entry["source"] == "tvdb" and request_is_unique(
                entry, request_dict):
            # Attempt to convert card to TMDB
            conversion = content_discovery.get_by_tvdb_id(
                tvdb_id=entry["content_id"])
            # Conversion found
            if conversion.__contains__(
                    "tv_results") and conversion["tv_results"]:
                card = conversion["tv_results"][0]
                card["tmdbCard"] = True
                card["requested_by"] = entry["requested_by__username"]
                all_cards.append(card)

                # Convert all requests to use this new ID
                old_requests = UserRequest.objects.filter(
                    content_id=entry["content_id"], source="tvdb")
                old_requests.update(content_id=card["id"], source="tmdb")

            # Fallback to checking sonarr's database
            else:
                card = content_manager.get(tvdb_id=entry["content_id"])

                # Determine if the card has a known poster image
                if isinstance(card, dict):
                    card["contentType"] = entry["content_type"]
                    if card.__contains__("images"):
                        remote_poster = is_key_value_in_list("coverType",
                                                             "poster",
                                                             card["images"],
                                                             return_item=True)
                        if remote_poster:
                            card["remotePoster"] = remote_poster["remoteUrl"]

                card["requested_by"] = entry["requested_by__username"]
                all_cards.append(card)

        if card is None and not request_is_unique(entry, request_dict):
            log.handler(
                entry["content_type"] + " from " + entry["source"] +
                " with ID " + entry["content_id"] + " no longer exists!",
                log.WARNING,
                __logger,
            )

    # Set the availability
    content_discovery.determine_id_validity({"results": all_cards})
    set_many_availability(all_cards)

    context = generate_context({"all_cards": all_cards})

    return HttpResponse(template.render(context, request))
Exemplo n.º 20
0
def request_content(request):
    # User submitted a new request
    if request.method == "POST":
        request_parameters = json.loads(request.body.decode("utf-8"))
        log.handler(
            "Request received: " + str(request_parameters),
            log.INFO,
            __logger,
        )

        content_manager = ContentManager()
        content_discovery = ContentDiscovery()

        # TV show was requested
        if request_parameters["content_type"] == "tv":
            # Obtain the TVDB ID if needed
            tvdb_id = None
            tmdb_id = None
            if request_parameters.__contains__("tvdb_id"):
                tvdb_id = request_parameters["tvdb_id"]
            if request_parameters.__contains__("tmdb_id"):
                tmdb_id = request_parameters["tmdb_id"]

            if not tvdb_id and tmdb_id:
                tvdb_id = content_discovery.get_external_ids(tmdb_id,
                                                             "tv")["tvdb_id"]

            # Request the show by the TVDB ID
            if tvdb_id:
                # Check if the show is already within Sonarr's collection
                show = content_manager.get(tvdb_id=tvdb_id)

                # If it doesn't already exists, add then request it
                if show is None:
                    sonarr_params = obtain_sonarr_parameters(
                        content_discovery, content_manager, tmdb_id, tvdb_id)
                    show = content_manager.add(
                        tvdb_id=tvdb_id,
                        quality_profile_id=sonarr_params["sonarr_profile_id"],
                        root_dir=sonarr_params["sonarr_root"],
                        series_type=sonarr_params["series_type"],
                        season_folders=sonarr_params["season_folders"],
                    )

                # Save and request
                if tmdb_id:
                    add_unique_to_db(
                        UserRequest,
                        content_id=tmdb_id,
                        source="tmdb",
                        content_type="tv",
                        requested_by=request.user,
                    )
                else:
                    add_unique_to_db(
                        UserRequest,
                        content_id=tvdb_id,
                        source="tvdb",
                        content_type="tv",
                        requested_by=request.user,
                    )
                content_manager.request(
                    sonarr_id=show["id"],
                    seasons=request_parameters["seasons"],
                    episode_ids=request_parameters["episode_ids"],
                )

                log.handler(
                    request.user.username + " requested TV series " +
                    show["title"],
                    log.INFO,
                    __logger,
                )

        # Movie was requested
        elif request_parameters["content_type"] == "movie":
            tmdb_id = request_parameters["tmdb_id"]
            radarr_params = obtain_radarr_parameters(content_discovery,
                                                     content_manager, tmdb_id)

            # Check if the movie is already within Radarr's collection
            movie = content_manager.get(tmdb_id=tmdb_id)

            # If it doesn't already exists, add then request it
            if movie is None:
                movie = content_manager.add(
                    tmdb_id=tmdb_id,
                    quality_profile_id=radarr_params["radarr_profile_id"],
                    root_dir=radarr_params["radarr_root"],
                )

            # Save and request
            add_unique_to_db(
                UserRequest,
                content_id=tmdb_id,
                source="tmdb",
                content_type="movie",
                requested_by=request.user,
            )
            content_manager.request(radarr_id=movie["id"])

            log.handler(
                request.user.username + " requested movie " + movie["title"],
                log.INFO,
                __logger,
            )

        return JsonResponse({})

    return HttpResponseForbidden()