Merge branch 'develop' into tests/mastodon_api_controller.ex
[akkoma] / lib / pleroma / delivery.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.Delivery do
6 use Ecto.Schema
7
8 alias Pleroma.Delivery
9 alias Pleroma.FlakeId
10 alias Pleroma.Object
11 alias Pleroma.Repo
12 alias Pleroma.User
13 alias Pleroma.User
14
15 import Ecto.Changeset
16 import Ecto.Query
17
18 schema "deliveries" do
19 belongs_to(:user, User, type: FlakeId)
20 belongs_to(:object, Object)
21 end
22
23 def changeset(delivery, params \\ %{}) do
24 delivery
25 |> cast(params, [:user_id, :object_id])
26 |> validate_required([:user_id, :object_id])
27 |> foreign_key_constraint(:object_id)
28 |> foreign_key_constraint(:user_id)
29 |> unique_constraint(:user_id, name: :deliveries_user_id_object_id_index)
30 end
31
32 def create(object_id, user_id) do
33 %Delivery{}
34 |> changeset(%{user_id: user_id, object_id: object_id})
35 |> Repo.insert(on_conflict: :nothing)
36 end
37
38 def get(object_id, user_id) do
39 from(d in Delivery, where: d.user_id == ^user_id and d.object_id == ^object_id)
40 |> Repo.one()
41 end
42
43 # A hack because user delete activities have a fake id for whatever reason
44 # TODO: Get rid of this
45 def delete_all_by_object_id("pleroma:fake_object_id"), do: {0, []}
46
47 def delete_all_by_object_id(object_id) do
48 from(d in Delivery, where: d.object_id == ^object_id)
49 |> Repo.delete_all()
50 end
51 end