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