Add scheduled activities
[akkoma] / lib / pleroma / scheduled_activity.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.ScheduledActivity do
6 use Ecto.Schema
7
8 alias Pleroma.Repo
9 alias Pleroma.ScheduledActivity
10 alias Pleroma.User
11
12 import Ecto.Query
13 import Ecto.Changeset
14
15 schema "scheduled_activities" do
16 belongs_to(:user, User, type: Pleroma.FlakeId)
17 field(:scheduled_at, :naive_datetime)
18 field(:params, :map)
19
20 timestamps()
21 end
22
23 def changeset(%ScheduledActivity{} = scheduled_activity, attrs) do
24 scheduled_activity
25 |> cast(attrs, [:scheduled_at, :params])
26 end
27
28 def update_changeset(%ScheduledActivity{} = scheduled_activity, attrs) do
29 scheduled_activity
30 |> cast(attrs, [:scheduled_at])
31 end
32
33 def new(%User{} = user, attrs) do
34 %ScheduledActivity{user_id: user.id}
35 |> changeset(attrs)
36 end
37
38 def create(%User{} = user, attrs) do
39 user
40 |> new(attrs)
41 |> Repo.insert()
42 end
43
44 def get(%User{} = user, scheduled_activity_id) do
45 ScheduledActivity
46 |> where(user_id: ^user.id)
47 |> where(id: ^scheduled_activity_id)
48 |> Repo.one()
49 end
50
51 def update(%User{} = user, scheduled_activity_id, attrs) do
52 with %ScheduledActivity{} = scheduled_activity <- get(user, scheduled_activity_id) do
53 scheduled_activity
54 |> update_changeset(attrs)
55 |> Repo.update()
56 else
57 nil -> {:error, :not_found}
58 end
59 end
60
61 def delete(%User{} = user, scheduled_activity_id) do
62 with %ScheduledActivity{} = scheduled_activity <- get(user, scheduled_activity_id) do
63 scheduled_activity
64 |> Repo.delete()
65 else
66 nil -> {:error, :not_found}
67 end
68 end
69
70 def for_user_query(%User{} = user) do
71 ScheduledActivity
72 |> where(user_id: ^user.id)
73 end
74 end