Fix buckets for query timing
[akkoma] / lib / pleroma / workers / scheduled_activity_worker.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 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 defp find_scheduled_activity(id) do
41 with nil <- Repo.get(ScheduledActivity, id) do
42 {:error, :scheduled_activity_not_found}
43 end
44 end
45
46 defp find_user(id) do
47 with nil <- User.get_cached_by_id(id) do
48 {:error, :user_not_found}
49 end
50 end
51
52 defp atomize_keys(map) do
53 Map.new(map, fn
54 {key, value} when is_map(value) -> {String.to_existing_atom(key), atomize_keys(value)}
55 {key, value} -> {String.to_existing_atom(key), value}
56 end)
57 end
58 end