First
[anni] / lib / pleroma / workers / poll_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.PollWorker do
6   @moduledoc """
7   Generates notifications when a poll ends.
8   """
9   use Pleroma.Workers.WorkerHelper, queue: "poll_notifications"
10
11   alias Pleroma.Activity
12   alias Pleroma.Notification
13   alias Pleroma.Object
14
15   @impl Oban.Worker
16   def perform(%Job{args: %{"op" => "poll_end", "activity_id" => activity_id}}) do
17     with %Activity{} = activity <- find_poll_activity(activity_id) do
18       Notification.create_poll_notifications(activity)
19     end
20   end
21
22   @impl Oban.Worker
23   def timeout(_job), do: :timer.seconds(5)
24
25   defp find_poll_activity(activity_id) do
26     with nil <- Activity.get_by_id(activity_id) do
27       {:error, :poll_activity_not_found}
28     end
29   end
30
31   def schedule_poll_end(%Activity{data: %{"type" => "Create"}, id: activity_id} = activity) do
32     with %Object{data: %{"type" => "Question", "closed" => closed}} when is_binary(closed) <-
33            Object.normalize(activity),
34          {:ok, end_time} <- NaiveDateTime.from_iso8601(closed),
35          :gt <- NaiveDateTime.compare(end_time, NaiveDateTime.utc_now()) do
36       %{
37         op: "poll_end",
38         activity_id: activity_id
39       }
40       |> new(scheduled_at: end_time)
41       |> Oban.insert()
42     else
43       _ -> {:error, activity}
44     end
45   end
46
47   def schedule_poll_end(activity), do: {:error, activity}
48 end