4df84d00f9387fd9c7338e1f2d60f456c649c2b0
[anni] / lib / pleroma / workers / scheduled_activity_worker.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Workers.ScheduledActivityWorker do
6   @moduledoc """
7   The worker to post scheduled activity.
8   """
9
10   use Pleroma.Workers.WorkerHelper, queue: "scheduled_activities"
11
12   alias Pleroma.Repo
13   alias Pleroma.ScheduledActivity
14   alias Pleroma.User
15
16   require Logger
17
18   @impl Oban.Worker
19   def perform(%Job{args: %{"activity_id" => activity_id}}) do
20     with %ScheduledActivity{} = scheduled_activity <- find_scheduled_activity(activity_id),
21          %User{} = user <- find_user(scheduled_activity.user_id) do
22       params = atomize_keys(scheduled_activity.params)
23
24       Repo.transaction(fn ->
25         {:ok, activity} = Pleroma.Web.CommonAPI.post(user, params)
26         {:ok, _} = ScheduledActivity.delete(scheduled_activity)
27         activity
28       end)
29     else
30       {:error, :scheduled_activity_not_found} = error ->
31         Logger.error("#{__MODULE__} Couldn't find scheduled activity: #{activity_id}")
32         error
33
34       {:error, :user_not_found} = error ->
35         Logger.error("#{__MODULE__} Couldn't find user for scheduled activity: #{activity_id}")
36         error
37     end
38   end
39
40   @impl Oban.Worker
41   def timeout(_job), do: :timer.seconds(5)
42
43   defp find_scheduled_activity(id) do
44     with nil <- Repo.get(ScheduledActivity, id) do
45       {:error, :scheduled_activity_not_found}
46     end
47   end
48
49   defp find_user(id) do
50     with nil <- User.get_cached_by_id(id) do
51       {:error, :user_not_found}
52     end
53   end
54
55   defp atomize_keys(map) do
56     Map.new(map, fn
57       {key, value} when is_map(value) -> {String.to_existing_atom(key), atomize_keys(value)}
58       {key, value} -> {String.to_existing_atom(key), value}
59     end)
60   end
61 end