Skip to content

Commit 1b72c85

Browse files
committed
fix: requested changes
1 parent cf87e6e commit 1b72c85

File tree

1 file changed

+28
-22
lines changed

1 file changed

+28
-22
lines changed

lib/pinchflat/fast_indexing/youtube_api.ex

+28-22
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,7 @@ defmodule Pinchflat.FastIndexing.YoutubeApi do
2121
Returns boolean()
2222
"""
2323
@impl YoutubeBehaviour
24-
def enabled?() do
25-
try do
26-
not Enum.empty?(api_keys())
27-
rescue
28-
_ -> false
29-
end
30-
end
24+
def enabled?, do: Enum.any?(api_keys())
3125

3226
@doc """
3327
Fetches the recent media IDs from the YouTube API for a given source.
@@ -83,28 +77,40 @@ defmodule Pinchflat.FastIndexing.YoutubeApi do
8377
end
8478

8579
defp api_keys do
86-
Settings.get!(:youtube_api_key)
87-
|> String.trim()
88-
|> String.split(",")
89-
|> Enum.map(&String.trim/1)
90-
|> Enum.reject(&(&1 == ""))
80+
case Settings.get!(:youtube_api_key) do
81+
nil ->
82+
[]
83+
84+
keys ->
85+
keys
86+
|> String.split(",")
87+
|> Enum.map(&String.trim/1)
88+
|> Enum.reject(&(&1 == ""))
89+
end
90+
end
91+
92+
defp get_or_start_api_key_agent do
93+
case Agent.start(fn -> 0 end, name: @agent_name) do
94+
{:ok, pid} -> pid
95+
{:error, {:already_started, pid}} -> pid
96+
end
9197
end
9298

9399
# Gets the next API key in round-robin fashion
94100
defp next_api_key do
95101
keys = api_keys()
102+
96103
case keys do
97-
[] -> nil
104+
[] ->
105+
nil
106+
98107
keys ->
99-
case Agent.start(fn -> 0 end, name: @agent_name) do
100-
{:ok, _pid} -> :ok
101-
{:error, {:already_started, _pid}} -> :ok
102-
end
103-
104-
current_index = Agent.get_and_update(@agent_name, fn current ->
105-
next = rem(current + 1, length(keys))
106-
{current, next}
107-
end)
108+
pid = get_or_start_api_key_agent()
109+
110+
current_index =
111+
Agent.get_and_update(pid, fn current ->
112+
{current, rem(current + 1, length(keys))}
113+
end)
108114

109115
Logger.debug("Using YouTube API key: #{Enum.at(keys, current_index)}")
110116
Enum.at(keys, current_index)

0 commit comments

Comments
 (0)