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