|> Repo.update()
end
- def set_all_seen_for_chat(chat) do
- chat
- |> for_chat_query()
- |> exclude(:order_by)
- |> exclude(:preload)
- |> where([cmr], cmr.unread == true)
+ def set_all_seen_for_chat(chat, last_read_id \\ nil) do
+ query =
+ chat
+ |> for_chat_query()
+ |> exclude(:order_by)
+ |> exclude(:preload)
+ |> where([cmr], cmr.unread == true)
+
+ if last_read_id do
+ query
+ |> where([cmr], cmr.id <= ^last_read_id)
+ else
+ query
+ end
|> Repo.update_all(set: [unread: false])
end
end
summary: "Mark all messages in the chat as read",
operationId: "ChatController.mark_as_read",
parameters: [Operation.parameter(:id, :path, :string, "The ID of the Chat")],
+ requestBody: request_body("Parameters", mark_as_read()),
responses: %{
200 =>
Operation.response(
}
}
end
+
+ def mark_as_read do
+ %Schema{
+ title: "MarkAsReadRequest",
+ description: "POST body for marking a number of chat messages as read",
+ type: :object,
+ properties: %{
+ last_read_id: %Schema{
+ type: :string,
+ description: "The content of your message. Optional."
+ }
+ },
+ example: %{
+ "last_read_id" => "abcdef12456"
+ }
+ }
+ end
end
def mark_as_read(%{assigns: %{user: %{id: user_id}}} = conn, %{id: id}) do
with %Chat{} = chat <- Repo.get_by(Chat, id: id, user_id: user_id),
- {_n, _} <- MessageReference.set_all_seen_for_chat(chat) do
+ {_n, _} <-
+ MessageReference.set_all_seen_for_chat(chat, conn.body_params[:last_read_id]) do
conn
|> put_view(ChatView)
|> render("show.json", chat: chat)
assert cm_ref.unread == false
end
+
+ test "it given a `last_read_id` ", %{conn: conn, user: user} do
+ other_user = insert(:user)
+
+ {:ok, create} = CommonAPI.post_chat_message(other_user, user, "sup")
+ {:ok, _create} = CommonAPI.post_chat_message(other_user, user, "sup part 2")
+ {:ok, chat} = Chat.get_or_create(user.id, other_user.ap_id)
+ object = Object.normalize(create, false)
+ cm_ref = MessageReference.for_chat_and_object(chat, object)
+
+ assert cm_ref.unread == true
+
+ result =
+ conn
+ |> put_req_header("content-type", "application/json")
+ |> post("/api/v1/pleroma/chats/#{chat.id}/read", %{"last_read_id" => cm_ref.id})
+ |> json_response_and_validate_schema(200)
+
+ assert result["unread"] == 1
+
+ cm_ref = MessageReference.for_chat_and_object(chat, object)
+
+ assert cm_ref.unread == false
+ end
end
describe "POST /api/v1/pleroma/chats/:id/messages" do