ChatController: Basic message posting.
authorlain <lain@soykaf.club>
Thu, 9 Apr 2020 15:18:31 +0000 (17:18 +0200)
committerlain <lain@soykaf.club>
Thu, 9 Apr 2020 15:18:31 +0000 (17:18 +0200)
lib/pleroma/web/pleroma_api/controllers/chat_controller.ex
lib/pleroma/web/router.ex
test/web/pleroma_api/controllers/chat_controller_test.exs

index de23b9a225f2fc94983dcaaae483784d40f4f677..972330f4e0c4f7dfaedf604e352528d86e90b359 100644 (file)
@@ -7,9 +7,35 @@ defmodule Pleroma.Web.PleromaAPI.ChatController do
   alias Pleroma.Chat
   alias Pleroma.Object
   alias Pleroma.Repo
+  alias Pleroma.User
+  alias Pleroma.Web.CommonAPI
 
   import Ecto.Query
 
+  # TODO
+  # - Oauth stuff
+  # - Views / Representers
+  # - Error handling
+
+  def post_chat_message(%{assigns: %{user: %{id: user_id} = user}} = conn, %{
+        "id" => id,
+        "content" => content
+      }) do
+    with %Chat{} = chat <- Repo.get_by(Chat, id: id, user_id: user_id),
+         %User{} = recipient <- User.get_cached_by_ap_id(chat.recipient),
+         {:ok, activity} <- CommonAPI.post_chat_message(user, recipient, content),
+         message <- Object.normalize(activity) do
+      represented_message = %{
+        actor: message.data["actor"],
+        id: message.id,
+        content: message.data["content"]
+      }
+
+      conn
+      |> json(represented_message)
+    end
+  end
+
   def messages(%{assigns: %{user: %{id: user_id} = user}} = conn, %{"id" => id}) do
     with %Chat{} = chat <- Repo.get_by(Chat, id: id, user_id: user_id) do
       messages =
index 368e77d3e809cef41e03a445c47480b6ba2cee44..ce69725dc88e3302c7f418d1a855409cb3422a26 100644 (file)
@@ -290,6 +290,7 @@ defmodule Pleroma.Web.Router do
       post("/chats/by-ap-id/:ap_id", ChatController, :create)
       get("/chats", ChatController, :index)
       get("/chats/:id/messages", ChatController, :messages)
+      post("/chats/:id/messages", ChatController, :post_chat_message)
     end
 
     scope [] do
index 6b2db5064307c455182c17480c26c25f549a0acb..b4230e5ade4d92b50c3a08edcc0b68a620cdfd80 100644 (file)
@@ -9,6 +9,23 @@ defmodule Pleroma.Web.PleromaAPI.ChatControllerTest do
 
   import Pleroma.Factory
 
+  describe "POST /api/v1/pleroma/chats/:id/messages" do
+    test "it posts a message to the chat", %{conn: conn} do
+      user = insert(:user)
+      other_user = insert(:user)
+
+      {:ok, chat} = Chat.get_or_create(user.id, other_user.ap_id)
+
+      result =
+        conn
+        |> assign(:user, user)
+        |> post("/api/v1/pleroma/chats/#{chat.id}/messages", %{"content" => "Hallo!!"})
+        |> json_response(200)
+
+      assert result["content"] == "Hallo!!"
+    end
+  end
+
   describe "GET /api/v1/pleroma/chats/:id/messages" do
     # TODO
     # - Test that statuses don't show