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