Merge branch 'develop' into tests/mastodon_api_controller.ex
[akkoma] / lib / pleroma / daemons / scheduled_activity_daemon.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Daemons.ScheduledActivityDaemon do
6 @moduledoc """
7 Sends scheduled activities to the job queue.
8 """
9
10 alias Pleroma.Config
11 alias Pleroma.ScheduledActivity
12 alias Pleroma.User
13 alias Pleroma.Web.CommonAPI
14
15 use GenServer
16 require Logger
17
18 @schedule_interval :timer.minutes(1)
19
20 def start_link(_) do
21 GenServer.start_link(__MODULE__, nil)
22 end
23
24 def init(_) do
25 if Config.get([ScheduledActivity, :enabled]) do
26 schedule_next()
27 {:ok, nil}
28 else
29 :ignore
30 end
31 end
32
33 def perform(:execute, scheduled_activity_id) do
34 try do
35 {:ok, scheduled_activity} = ScheduledActivity.delete(scheduled_activity_id)
36 %User{} = user = User.get_cached_by_id(scheduled_activity.user_id)
37 {:ok, _result} = CommonAPI.post(user, scheduled_activity.params)
38 rescue
39 error ->
40 Logger.error(
41 "#{__MODULE__} Couldn't create a status from the scheduled activity: #{inspect(error)}"
42 )
43 end
44 end
45
46 def handle_info(:perform, state) do
47 ScheduledActivity.due_activities(@schedule_interval)
48 |> Enum.each(fn scheduled_activity ->
49 Pleroma.Workers.ScheduledActivityWorker.enqueue(
50 "execute",
51 %{"activity_id" => scheduled_activity.id}
52 )
53 end)
54
55 schedule_next()
56 {:noreply, state}
57 end
58
59 defp schedule_next do
60 Process.send_after(self(), :perform, @schedule_interval)
61 end
62 end