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
28 |> cast(validate_params(struct, params), [:data, :starts_at, :ends_at, :rendered])
29 |> validate_required([:data])
32 defp validate_params(struct, params) do
38 |> Map.merge((struct && struct.data) || %{})
41 Map.merge(base_data, params.data)
42 |> Map.take(["content", "all_day"])
45 |> Map.merge(%{data: merged_data})
46 |> add_rendered_properties()
49 def add_rendered_properties(params) do
50 {content_html, _, _} =
51 Pleroma.Web.CommonAPI.Utils.format_input(params.data["content"], "text/plain",
52 mentions_format: :full
56 "content" => content_html
60 |> Map.put(:rendered, rendered)
64 changeset = change(%__MODULE__{}, params)
66 Repo.insert(changeset)
69 def update(announcement, params) do
70 changeset = change(announcement, params)
72 Repo.update(changeset)
80 def list_paginated(%{limit: limited_number, offset: offset_number}) do
82 |> limit(^limited_number)
83 |> offset(^offset_number)
88 Repo.get_by(__MODULE__, id: id)
91 def delete_by_id(id) do
92 with announcement when not is_nil(announcement) <- get_by_id(id),
93 {:ok, _} <- Repo.delete(announcement) do
101 def read_by?(announcement, user) do
102 AnnouncementReadRelationship.exists?(user, announcement)
105 def mark_read_by(announcement, user) do
106 AnnouncementReadRelationship.mark_read(user, announcement)
109 def render_json(announcement, opts \\ []) do
111 case Keyword.fetch(opts, :for) do
112 {:ok, user} when not is_nil(user) ->
113 %{read: read_by?(announcement, user)}
120 case Keyword.fetch(opts, :admin) do
122 %{pleroma: %{raw_content: announcement.data["content"]}}
130 content: announcement.rendered["content"],
131 starts_at: announcement.starts_at,
132 ends_at: announcement.ends_at,
133 all_day: announcement.data["all_day"],
134 published_at: announcement.inserted_at,
135 updated_at: announcement.updated_at,
144 |> Map.merge(extra_params)
145 |> Map.merge(admin_extra_params)
149 # starts_at < time < ends_at
150 def list_all_visible_when(time) do
152 |> where([a], is_nil(a.starts_at) or a.starts_at < ^time)
153 |> where([a], is_nil(a.ends_at) or a.ends_at > ^time)
157 def list_all_visible do
158 list_all_visible_when(DateTime.now("Etc/UTC") |> elem(1))