Replace `Pleroma.FlakeId` with `flake_id` hex package
[akkoma] / lib / pleroma / filter.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.Filter do
6 use Ecto.Schema
7
8 import Ecto.Changeset
9 import Ecto.Query
10
11 alias Pleroma.Repo
12 alias Pleroma.User
13
14 schema "filters" do
15 belongs_to(:user, User, type: FlakeId.Ecto.CompatType)
16 field(:filter_id, :integer)
17 field(:hide, :boolean, default: false)
18 field(:whole_word, :boolean, default: true)
19 field(:phrase, :string)
20 field(:context, {:array, :string})
21 field(:expires_at, :utc_datetime)
22
23 timestamps()
24 end
25
26 def get(id, %{id: user_id} = _user) do
27 query =
28 from(
29 f in Pleroma.Filter,
30 where: f.filter_id == ^id,
31 where: f.user_id == ^user_id
32 )
33
34 Repo.one(query)
35 end
36
37 def get_filters(%User{id: user_id} = _user) do
38 query =
39 from(
40 f in Pleroma.Filter,
41 where: f.user_id == ^user_id,
42 order_by: [desc: :id]
43 )
44
45 Repo.all(query)
46 end
47
48 def create(%Pleroma.Filter{user_id: user_id, filter_id: nil} = filter) do
49 # If filter_id wasn't given, use the max filter_id for this user plus 1.
50 # XXX This could result in a race condition if a user tries to add two
51 # different filters for their account from two different clients at the
52 # same time, but that should be unlikely.
53
54 max_id_query =
55 from(
56 f in Pleroma.Filter,
57 where: f.user_id == ^user_id,
58 select: max(f.filter_id)
59 )
60
61 filter_id =
62 case Repo.one(max_id_query) do
63 # Start allocating from 1
64 nil ->
65 1
66
67 max_id ->
68 max_id + 1
69 end
70
71 filter
72 |> Map.put(:filter_id, filter_id)
73 |> Repo.insert()
74 end
75
76 def create(%Pleroma.Filter{} = filter) do
77 Repo.insert(filter)
78 end
79
80 def delete(%Pleroma.Filter{id: filter_key} = filter) when is_number(filter_key) do
81 Repo.delete(filter)
82 end
83
84 def delete(%Pleroma.Filter{id: filter_key} = filter) when is_nil(filter_key) do
85 %Pleroma.Filter{id: id} = get(filter.filter_id, %{id: filter.user_id})
86
87 filter
88 |> Map.put(:id, id)
89 |> Repo.delete()
90 end
91
92 def update(%Pleroma.Filter{} = filter) do
93 destination = Map.from_struct(filter)
94
95 Pleroma.Filter.get(filter.filter_id, %{id: filter.user_id})
96 |> cast(destination, [:phrase, :context, :hide, :expires_at, :whole_word])
97 |> Repo.update()
98 end
99 end