Merge branch 'develop' into refactor/subscription
[akkoma] / lib / pleroma / scheduled_activity_worker.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.ScheduledActivityWorker 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 use GenServer
15 require Logger
16
17 @schedule_interval :timer.minutes(1)
18
19 def start_link(_) do
20 GenServer.start_link(__MODULE__, nil)
21 end
22
23 def init(_) do
24 if Config.get([ScheduledActivity, :enabled]) do
25 schedule_next()
26 {:ok, nil}
27 else
28 :ignore
29 end
30 end
31
32 def perform(:execute, scheduled_activity_id) do
33 try do
34 {:ok, scheduled_activity} = ScheduledActivity.delete(scheduled_activity_id)
35 %User{} = user = User.get_cached_by_id(scheduled_activity.user_id)
36 {:ok, _result} = CommonAPI.post(user, scheduled_activity.params)
37 rescue
38 error ->
39 Logger.error(
40 "#{__MODULE__} Couldn't create a status from the scheduled activity: #{inspect(error)}"
41 )
42 end
43 end
44
45 def handle_info(:perform, state) do
46 ScheduledActivity.due_activities(@schedule_interval)
47 |> Enum.each(fn scheduled_activity ->
48 PleromaJobQueue.enqueue(:scheduled_activities, __MODULE__, [:execute, scheduled_activity.id])
49 end)
50
51 schedule_next()
52 {:noreply, state}
53 end
54
55 defp schedule_next do
56 Process.send_after(self(), :perform, @schedule_interval)
57 end
58 end