1 # Pleroma: A lightweight social networking server
2 # Copyright © 2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.ActivityExpiration do
9 alias Pleroma.ActivityExpiration
15 @type t :: %__MODULE__{}
16 @min_activity_lifetime :timer.hours(1)
18 schema "activity_expirations" do
19 belongs_to(:activity, Activity, type: FlakeId.Ecto.CompatType)
20 field(:scheduled_at, :naive_datetime)
23 def changeset(%ActivityExpiration{} = expiration, attrs) do
25 |> cast(attrs, [:scheduled_at])
26 |> validate_required([:scheduled_at])
27 |> validate_scheduled_at()
30 def get_by_activity_id(activity_id) do
32 |> where([exp], exp.activity_id == ^activity_id)
36 def create(%Activity{} = activity, scheduled_at) do
37 %ActivityExpiration{activity_id: activity.id}
38 |> changeset(%{scheduled_at: scheduled_at})
42 def due_expirations(offset \\ 0) do
44 NaiveDateTime.utc_now()
45 |> NaiveDateTime.add(offset, :millisecond)
48 |> where([exp], exp.scheduled_at < ^naive_datetime)
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"]
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