summaryrefslogtreecommitdiff
path: root/lib/pleroma/web/pleroma_api/views/chat_view.ex
blob: 3794818a77f167f0f53e8465ad8b9b8a8625f51a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# Pleroma: A lightweight social networking server
# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only

defmodule Pleroma.Web.PleromaAPI.ChatView do
  use Pleroma.Web, :view

  alias Pleroma.Chat
  alias Pleroma.Chat.MessageReference
  alias Pleroma.User
  alias Pleroma.Web.CommonAPI.Utils
  alias Pleroma.Web.MastodonAPI.AccountView
  alias Pleroma.Web.PleromaAPI.Chat.MessageReferenceView

  def render("show.json", %{chat: %Chat{} = chat} = opts) do
    recipient = User.get_cached_by_ap_id(chat.recipient)
    last_message = opts[:last_message] || MessageReference.last_message_for_chat(chat)
    account_view_opts = account_view_opts(opts, recipient)

    %{
      id: chat.id |> to_string(),
      account: AccountView.render("show.json", account_view_opts),
      unread: MessageReference.unread_count_for_chat(chat),
      last_message:
        last_message &&
          MessageReferenceView.render("show.json", chat_message_reference: last_message),
      updated_at: Utils.to_masto_date(chat.updated_at)
    }
  end

  def render("index.json", %{chats: chats} = opts) do
    render_many(chats, __MODULE__, "show.json", Map.delete(opts, :chats))
  end

  defp account_view_opts(opts, recipient) do
    account_view_opts = Map.put(opts, :user, recipient)

    if Map.has_key?(account_view_opts, :for) do
      account_view_opts
    else
      Map.put(account_view_opts, :skip_visibility_check, true)
    end
  end
end