diff --git a/lib/live_beats/application.ex b/lib/live_beats/application.ex index e6ff89f..c459eee 100644 --- a/lib/live_beats/application.ex +++ b/lib/live_beats/application.ex @@ -25,7 +25,8 @@ defmodule LiveBeats.Application do presence: LiveBeatsWeb.Presence, name: PresenceClient}, # Start the Endpoint (http/https) - LiveBeatsWeb.Endpoint + LiveBeatsWeb.Endpoint, + {LiveBeats.SongsCleaner, count: 1, interval: "month"} # Start a worker by calling: LiveBeats.Worker.start_link(arg) # {LiveBeats.Worker, arg} diff --git a/lib/live_beats/media_library.ex b/lib/live_beats/media_library.ex index eb1b1c3..c0e0e7e 100644 --- a/lib/live_beats/media_library.ex +++ b/lib/live_beats/media_library.ex @@ -367,6 +367,9 @@ defmodule LiveBeats.MediaLibrary do end def delete_expired_songs(count, interval) do + #for substracting the interval of time when from_now/2 is invoked + count = count * -1 + Ecto.Multi.new() |> Ecto.Multi.delete_all( :delete_expired_songs, diff --git a/lib/live_beats/songs_cleaner.ex b/lib/live_beats/songs_cleaner.ex new file mode 100644 index 0000000..32e5c57 --- /dev/null +++ b/lib/live_beats/songs_cleaner.ex @@ -0,0 +1,35 @@ +defmodule LiveBeats.SongsCleaner do + @moduledoc """ + Remove user songs that were added ... ago + """ + + alias LiveBeats.MediaLibrary + use GenServer + + def start_link(opts) do + GenServer.start_link(__MODULE__, opts) + end + + @impl true + def init(opts) do + schedule_cleanup() + + count = Keyword.fetch!(opts, :count) + interval = Keyword.fetch!(opts, :interval) + MediaLibrary.delete_expired_songs(count, interval) + + {:ok, %{count: count, interval: interval}} + end + + @impl true + def handle_info(:remove_songs, %{count: count, interval: interval} = state) do + MediaLibrary.delete_expired_songs(count, interval) + schedule_cleanup() + + {:noreply, state} + end + + defp schedule_cleanup do + Process.send_after(self(), :remove_songs, :timer.hours(3)) + end +end