@@ -21,13 +21,7 @@ defmodule Pinchflat.FastIndexing.YoutubeApi do
21
21
Returns boolean()
22
22
"""
23
23
@ 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 ( ) )
31
25
32
26
@ doc """
33
27
Fetches the recent media IDs from the YouTube API for a given source.
@@ -83,28 +77,40 @@ defmodule Pinchflat.FastIndexing.YoutubeApi do
83
77
end
84
78
85
79
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
91
97
end
92
98
93
99
# Gets the next API key in round-robin fashion
94
100
defp next_api_key do
95
101
keys = api_keys ( )
102
+
96
103
case keys do
97
- [ ] -> nil
104
+ [ ] ->
105
+ nil
106
+
98
107
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 )
108
114
109
115
Logger . debug ( "Using YouTube API key: #{ Enum . at ( keys , current_index ) } " )
110
116
Enum . at ( keys , current_index )
0 commit comments