1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Announcement do
8 import Ecto.Changeset, only: [cast: 3, validate_required: 2]
11 alias Pleroma.AnnouncementReadRelationship
14 @type t :: %__MODULE__{}
15 @primary_key {:id, FlakeId.Ecto.CompatType, autogenerate: true}
17 schema "announcements" do
19 field(:starts_at, :utc_datetime)
20 field(:ends_at, :utc_datetime)
21 field(:rendered, :map)
23 timestamps(type: :utc_datetime)
26 def change(struct, params \\ %{}) do
27 params = validate_params(struct, params)
30 |> cast(params, [:data, :starts_at, :ends_at, :rendered])
31 |> validate_required([:data])
34 defp validate_params(struct, params) do
40 |> Map.merge((struct && struct.data) || %{})
43 Map.merge(base_data, params.data)
44 |> Map.take(["content", "all_day"])
47 |> Map.merge(%{data: merged_data})
48 |> add_rendered_properties()
51 def add_rendered_properties(params) do
52 {content_html, _, _} =
53 Pleroma.Web.CommonAPI.Utils.format_input(params.data["content"], "text/plain",
54 mentions_format: :full
58 "content" => content_html
62 |> Map.put(:rendered, rendered)
66 changeset = change(%__MODULE__{}, params)
68 Repo.insert(changeset)
71 def update(announcement, params) do
72 changeset = change(announcement, params)
74 Repo.update(changeset)
82 def list_paginated(%{limit: limited_number, offset: offset_number}) do
84 |> limit(^limited_number)
85 |> offset(^offset_number)
90 Repo.get_by(__MODULE__, id: id)
93 def delete_by_id(id) do
94 with announcement when not is_nil(announcement) <- get_by_id(id),
95 {:ok, _} <- Repo.delete(announcement) do
103 def read_by?(announcement, user) do
104 AnnouncementReadRelationship.exists?(user, announcement)
107 def mark_read_by(announcement, user) do
108 AnnouncementReadRelationship.mark_read(user, announcement)
111 def render_json(announcement, opts \\ []) do
113 case Keyword.fetch(opts, :for) do
114 {:ok, user} when not is_nil(user) ->
115 %{read: read_by?(announcement, user)}
122 case Keyword.fetch(opts, :admin) do
124 %{pleroma: %{raw_content: announcement.data["content"]}}
132 content: announcement.rendered["content"],
133 starts_at: announcement.starts_at,
134 ends_at: announcement.ends_at,
135 all_day: announcement.data["all_day"],
136 published_at: announcement.inserted_at,
137 updated_at: announcement.updated_at,
146 |> Map.merge(extra_params)
147 |> Map.merge(admin_extra_params)
151 # starts_at < time < ends_at
152 def list_all_visible_when(time) do
154 |> where([a], is_nil(a.starts_at) or a.starts_at < ^time)
155 |> where([a], is_nil(a.ends_at) or a.ends_at > ^time)
159 def list_all_visible do
160 list_all_visible_when(DateTime.now("Etc/UTC") |> elem(1))