fix: requested changes

This commit is contained in:
rebel onion 2025-02-08 03:18:21 -06:00
parent cf87e6e047
commit 1b72c8571c

View file

@ -21,13 +21,7 @@ defmodule Pinchflat.FastIndexing.YoutubeApi do
Returns boolean() Returns boolean()
""" """
@impl YoutubeBehaviour @impl YoutubeBehaviour
def enabled?() do def enabled?, do: Enum.any?(api_keys())
try do
not Enum.empty?(api_keys())
rescue
_ -> false
end
end
@doc """ @doc """
Fetches the recent media IDs from the YouTube API for a given source. Fetches the recent media IDs from the YouTube API for a given source.
@ -83,28 +77,40 @@ defmodule Pinchflat.FastIndexing.YoutubeApi do
end end
defp api_keys do defp api_keys do
Settings.get!(:youtube_api_key) case Settings.get!(:youtube_api_key) do
|> String.trim() nil ->
|> String.split(",") []
|> Enum.map(&String.trim/1)
|> Enum.reject(&(&1 == "")) keys ->
keys
|> String.split(",")
|> Enum.map(&String.trim/1)
|> Enum.reject(&(&1 == ""))
end
end
defp get_or_start_api_key_agent do
case Agent.start(fn -> 0 end, name: @agent_name) do
{:ok, pid} -> pid
{:error, {:already_started, pid}} -> pid
end
end end
# Gets the next API key in round-robin fashion # Gets the next API key in round-robin fashion
defp next_api_key do defp next_api_key do
keys = api_keys() keys = api_keys()
case keys do
[] -> nil
keys ->
case Agent.start(fn -> 0 end, name: @agent_name) do
{:ok, _pid} -> :ok
{:error, {:already_started, _pid}} -> :ok
end
current_index = Agent.get_and_update(@agent_name, fn current -> case keys do
next = rem(current + 1, length(keys)) [] ->
{current, next} nil
end)
keys ->
pid = get_or_start_api_key_agent()
current_index =
Agent.get_and_update(pid, fn current ->
{current, rem(current + 1, length(keys))}
end)
Logger.debug("Using YouTube API key: #{Enum.at(keys, current_index)}") Logger.debug("Using YouTube API key: #{Enum.at(keys, current_index)}")
Enum.at(keys, current_index) Enum.at(keys, current_index)