Merge develop
[akkoma] / lib / pleroma / activity_expiration.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.ActivityExpiration do
6 use Ecto.Schema
7
8 alias Pleroma.Activity
9 alias Pleroma.ActivityExpiration
10 alias Pleroma.FlakeId
11 alias Pleroma.Repo
12
13 import Ecto.Changeset
14 import Ecto.Query
15
16 @type t :: %__MODULE__{}
17 @min_activity_lifetime :timer.hours(1)
18
19 schema "activity_expirations" do
20 belongs_to(:activity, Activity, type: FlakeId)
21 field(:scheduled_at, :naive_datetime)
22 end
23
24 def changeset(%ActivityExpiration{} = expiration, attrs) do
25 expiration
26 |> cast(attrs, [:scheduled_at])
27 |> validate_required([:scheduled_at])
28 |> validate_scheduled_at()
29 end
30
31 def get_by_activity_id(activity_id) do
32 ActivityExpiration
33 |> where([exp], exp.activity_id == ^activity_id)
34 |> Repo.one()
35 end
36
37 def create(%Activity{} = activity, scheduled_at) do
38 %ActivityExpiration{activity_id: activity.id}
39 |> changeset(%{scheduled_at: scheduled_at})
40 |> Repo.insert()
41 end
42
43 def due_expirations(offset \\ 0) do
44 naive_datetime =
45 NaiveDateTime.utc_now()
46 |> NaiveDateTime.add(offset, :millisecond)
47
48 ActivityExpiration
49 |> where([exp], exp.scheduled_at < ^naive_datetime)
50 |> Repo.all()
51 end
52
53 def validate_scheduled_at(changeset) do
54 validate_change(changeset, :scheduled_at, fn _, scheduled_at ->
55 if not expires_late_enough?(scheduled_at) do
56 [scheduled_at: "an ephemeral activity must live for at least one hour"]
57 else
58 []
59 end
60 end)
61 end
62
63 def expires_late_enough?(scheduled_at) do
64 now = NaiveDateTime.utc_now()
65 diff = NaiveDateTime.diff(scheduled_at, now, :millisecond)
66 diff >= @min_activity_lifetime
67 end
68 end