Merge branch 'feature/807-bookmark-endpoint-extension' into 'develop'
[akkoma] / lib / pleroma / bookmark.ex
1 defmodule Pleroma.Bookmark do
2 use Ecto.Schema
3
4 import Ecto.Changeset
5 import Ecto.Query
6
7 alias Pleroma.Activity
8 alias Pleroma.Bookmark
9 alias Pleroma.FlakeId
10 alias Pleroma.Repo
11 alias Pleroma.User
12
13 @type t :: %__MODULE__{}
14
15 schema "bookmarks" do
16 belongs_to(:user, User, type: FlakeId)
17 belongs_to(:activity, Activity, type: FlakeId)
18
19 timestamps()
20 end
21
22 @spec create(FlakeId.t(), FlakeId.t()) :: {:ok, Bookmark.t()} | {:error, Changeset.t()}
23 def create(user_id, activity_id) do
24 attrs = %{
25 user_id: user_id,
26 activity_id: activity_id
27 }
28
29 %Bookmark{}
30 |> cast(attrs, [:user_id, :activity_id])
31 |> validate_required([:user_id, :activity_id])
32 |> unique_constraint(:activity_id, name: :bookmarks_user_id_activity_id_index)
33 |> Repo.insert()
34 end
35
36 @spec for_user_query(FlakeId.t()) :: Ecto.Query.t()
37 def for_user_query(user_id) do
38 Bookmark
39 |> where(user_id: ^user_id)
40 |> join(:inner, [b], activity in assoc(b, :activity))
41 |> preload([b, a], activity: a)
42 end
43
44 @spec destroy(FlakeId.t(), FlakeId.t()) :: {:ok, Bookmark.t()} | {:error, Changeset.t()}
45 def destroy(user_id, activity_id) do
46 from(b in Bookmark,
47 where: b.user_id == ^user_id,
48 where: b.activity_id == ^activity_id
49 )
50 |> Repo.one()
51 |> Repo.delete()
52 end
53 end