First
[anni] / test / pleroma / web / pleroma_api / controllers / chat_controller_test.exs
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4 defmodule Pleroma.Web.PleromaAPI.ChatControllerTest do
5   use Pleroma.Web.ConnCase
6
7   alias Pleroma.Chat
8   alias Pleroma.Chat.MessageReference
9   alias Pleroma.Object
10   alias Pleroma.User
11   alias Pleroma.Web.ActivityPub.ActivityPub
12   alias Pleroma.Web.CommonAPI
13
14   import Pleroma.Factory
15
16   describe "POST /api/v1/pleroma/chats/:id/messages/:message_id/read" do
17     setup do: oauth_access(["write:chats"])
18
19     test "it marks one message as read", %{conn: conn, user: user} do
20       other_user = insert(:user)
21
22       {:ok, create} = CommonAPI.post_chat_message(other_user, user, "sup")
23       {:ok, _create} = CommonAPI.post_chat_message(other_user, user, "sup part 2")
24       {:ok, chat} = Chat.get_or_create(user.id, other_user.ap_id)
25       object = Object.normalize(create, fetch: false)
26       cm_ref = MessageReference.for_chat_and_object(chat, object)
27
28       assert cm_ref.unread == true
29
30       result =
31         conn
32         |> post("/api/v1/pleroma/chats/#{chat.id}/messages/#{cm_ref.id}/read")
33         |> json_response_and_validate_schema(200)
34
35       assert result["unread"] == false
36
37       cm_ref = MessageReference.for_chat_and_object(chat, object)
38
39       assert cm_ref.unread == false
40     end
41   end
42
43   describe "POST /api/v1/pleroma/chats/:id/read" do
44     setup do: oauth_access(["write:chats"])
45
46     test "given a `last_read_id`, it marks everything until then as read", %{
47       conn: conn,
48       user: user
49     } do
50       other_user = insert(:user)
51
52       {:ok, create} = CommonAPI.post_chat_message(other_user, user, "sup")
53       {:ok, _create} = CommonAPI.post_chat_message(other_user, user, "sup part 2")
54       {:ok, chat} = Chat.get_or_create(user.id, other_user.ap_id)
55       object = Object.normalize(create, fetch: false)
56       cm_ref = MessageReference.for_chat_and_object(chat, object)
57
58       assert cm_ref.unread == true
59
60       result =
61         conn
62         |> put_req_header("content-type", "application/json")
63         |> post("/api/v1/pleroma/chats/#{chat.id}/read", %{"last_read_id" => cm_ref.id})
64         |> json_response_and_validate_schema(200)
65
66       assert result["unread"] == 1
67
68       cm_ref = MessageReference.for_chat_and_object(chat, object)
69
70       assert cm_ref.unread == false
71     end
72   end
73
74   describe "POST /api/v1/pleroma/chats/:id/messages" do
75     setup do: oauth_access(["write:chats"])
76
77     test "it posts a message to the chat", %{conn: conn, user: user} do
78       other_user = insert(:user)
79
80       {:ok, chat} = Chat.get_or_create(user.id, other_user.ap_id)
81
82       result =
83         conn
84         |> put_req_header("content-type", "application/json")
85         |> put_req_header("idempotency-key", "123")
86         |> post("/api/v1/pleroma/chats/#{chat.id}/messages", %{"content" => "Hallo!!"})
87         |> json_response_and_validate_schema(200)
88
89       assert result["content"] == "Hallo!!"
90       assert result["chat_id"] == chat.id |> to_string()
91       assert result["idempotency_key"] == "123"
92     end
93
94     test "it fails if there is no content", %{conn: conn, user: user} do
95       other_user = insert(:user)
96
97       {:ok, chat} = Chat.get_or_create(user.id, other_user.ap_id)
98
99       result =
100         conn
101         |> put_req_header("content-type", "application/json")
102         |> post("/api/v1/pleroma/chats/#{chat.id}/messages")
103         |> json_response_and_validate_schema(400)
104
105       assert %{"error" => "no_content"} == result
106     end
107
108     test "it works with an attachment", %{conn: conn, user: user} do
109       file = %Plug.Upload{
110         content_type: "image/jpeg",
111         path: Path.absname("test/fixtures/image.jpg"),
112         filename: "an_image.jpg"
113       }
114
115       {:ok, upload} = ActivityPub.upload(file, actor: user.ap_id)
116
117       other_user = insert(:user)
118
119       {:ok, chat} = Chat.get_or_create(user.id, other_user.ap_id)
120
121       result =
122         conn
123         |> put_req_header("content-type", "application/json")
124         |> post("/api/v1/pleroma/chats/#{chat.id}/messages", %{
125           "media_id" => to_string(upload.id)
126         })
127         |> json_response_and_validate_schema(200)
128
129       assert result["attachment"]
130     end
131
132     test "gets MRF reason when rejected", %{conn: conn, user: user} do
133       clear_config([:mrf_keyword, :reject], ["GNO"])
134       clear_config([:mrf, :policies], [Pleroma.Web.ActivityPub.MRF.KeywordPolicy])
135
136       other_user = insert(:user)
137
138       {:ok, chat} = Chat.get_or_create(user.id, other_user.ap_id)
139
140       result =
141         conn
142         |> put_req_header("content-type", "application/json")
143         |> post("/api/v1/pleroma/chats/#{chat.id}/messages", %{"content" => "GNO/Linux"})
144         |> json_response_and_validate_schema(422)
145
146       assert %{"error" => "[KeywordPolicy] Matches with rejected keyword"} == result
147     end
148   end
149
150   describe "DELETE /api/v1/pleroma/chats/:id/messages/:message_id" do
151     setup do: oauth_access(["write:chats"])
152
153     test "it deletes a message from the chat", %{conn: conn, user: user} do
154       recipient = insert(:user)
155
156       {:ok, message} =
157         CommonAPI.post_chat_message(user, recipient, "Hello darkness my old friend")
158
159       {:ok, other_message} = CommonAPI.post_chat_message(recipient, user, "nico nico ni")
160
161       object = Object.normalize(message, fetch: false)
162
163       chat = Chat.get(user.id, recipient.ap_id)
164
165       cm_ref = MessageReference.for_chat_and_object(chat, object)
166
167       # Deleting your own message removes the message and the reference
168       result =
169         conn
170         |> put_req_header("content-type", "application/json")
171         |> delete("/api/v1/pleroma/chats/#{chat.id}/messages/#{cm_ref.id}")
172         |> json_response_and_validate_schema(200)
173
174       assert result["id"] == cm_ref.id
175       refute MessageReference.get_by_id(cm_ref.id)
176       assert %{data: %{"type" => "Tombstone"}} = Object.get_by_id(object.id)
177
178       # Deleting other people's messages just removes the reference
179       object = Object.normalize(other_message, fetch: false)
180       cm_ref = MessageReference.for_chat_and_object(chat, object)
181
182       result =
183         conn
184         |> put_req_header("content-type", "application/json")
185         |> delete("/api/v1/pleroma/chats/#{chat.id}/messages/#{cm_ref.id}")
186         |> json_response_and_validate_schema(200)
187
188       assert result["id"] == cm_ref.id
189       refute MessageReference.get_by_id(cm_ref.id)
190       assert Object.get_by_id(object.id)
191     end
192   end
193
194   describe "GET /api/v1/pleroma/chats/:id/messages" do
195     setup do: oauth_access(["read:chats"])
196
197     test "it paginates", %{conn: conn, user: user} do
198       recipient = insert(:user)
199
200       Enum.each(1..30, fn _ ->
201         {:ok, _} = CommonAPI.post_chat_message(user, recipient, "hey")
202       end)
203
204       chat = Chat.get(user.id, recipient.ap_id)
205
206       response = get(conn, "/api/v1/pleroma/chats/#{chat.id}/messages")
207       result = json_response_and_validate_schema(response, 200)
208
209       [next, prev] = get_resp_header(response, "link") |> hd() |> String.split(", ")
210       api_endpoint = "/api/v1/pleroma/chats/"
211
212       assert String.match?(
213                next,
214                ~r(#{api_endpoint}.*/messages\?limit=\d+&max_id=.*; rel=\"next\"$)
215              )
216
217       assert String.match?(
218                prev,
219                ~r(#{api_endpoint}.*/messages\?limit=\d+&min_id=.*; rel=\"prev\"$)
220              )
221
222       assert length(result) == 20
223
224       response =
225         get(conn, "/api/v1/pleroma/chats/#{chat.id}/messages?max_id=#{List.last(result)["id"]}")
226
227       result = json_response_and_validate_schema(response, 200)
228       [next, prev] = get_resp_header(response, "link") |> hd() |> String.split(", ")
229
230       assert String.match?(
231                next,
232                ~r(#{api_endpoint}.*/messages\?limit=\d+&max_id=.*; rel=\"next\"$)
233              )
234
235       assert String.match?(
236                prev,
237                ~r(#{api_endpoint}.*/messages\?limit=\d+&max_id=.*&min_id=.*; rel=\"prev\"$)
238              )
239
240       assert length(result) == 10
241     end
242
243     test "it returns the messages for a given chat", %{conn: conn, user: user} do
244       other_user = insert(:user)
245       third_user = insert(:user)
246
247       {:ok, _} = CommonAPI.post_chat_message(user, other_user, "hey")
248       {:ok, _} = CommonAPI.post_chat_message(user, third_user, "hey")
249       {:ok, _} = CommonAPI.post_chat_message(user, other_user, "how are you?")
250       {:ok, _} = CommonAPI.post_chat_message(other_user, user, "fine, how about you?")
251
252       chat = Chat.get(user.id, other_user.ap_id)
253
254       result =
255         conn
256         |> get("/api/v1/pleroma/chats/#{chat.id}/messages")
257         |> json_response_and_validate_schema(200)
258
259       result
260       |> Enum.each(fn message ->
261         assert message["chat_id"] == chat.id |> to_string()
262       end)
263
264       assert length(result) == 3
265
266       # Trying to get the chat of a different user
267       other_user_chat = Chat.get(other_user.id, user.ap_id)
268
269       conn
270       |> get("/api/v1/pleroma/chats/#{other_user_chat.id}/messages")
271       |> json_response_and_validate_schema(404)
272     end
273   end
274
275   describe "POST /api/v1/pleroma/chats/by-account-id/:id" do
276     setup do: oauth_access(["write:chats"])
277
278     test "it creates or returns a chat", %{conn: conn} do
279       other_user = insert(:user)
280
281       result =
282         conn
283         |> post("/api/v1/pleroma/chats/by-account-id/#{other_user.id}")
284         |> json_response_and_validate_schema(200)
285
286       assert result["id"]
287     end
288   end
289
290   describe "GET /api/v1/pleroma/chats/:id" do
291     setup do: oauth_access(["read:chats"])
292
293     test "it returns a chat", %{conn: conn, user: user} do
294       other_user = insert(:user)
295
296       {:ok, chat} = Chat.get_or_create(user.id, other_user.ap_id)
297
298       result =
299         conn
300         |> get("/api/v1/pleroma/chats/#{chat.id}")
301         |> json_response_and_validate_schema(200)
302
303       assert result["id"] == to_string(chat.id)
304     end
305   end
306
307   for tested_endpoint <- ["/api/v1/pleroma/chats", "/api/v2/pleroma/chats"] do
308     describe "GET #{tested_endpoint}" do
309       setup do: oauth_access(["read:chats"])
310
311       test "it does not return chats with deleted users", %{conn: conn, user: user} do
312         recipient = insert(:user)
313         {:ok, _} = Chat.get_or_create(user.id, recipient.ap_id)
314
315         Pleroma.Repo.delete(recipient)
316         User.invalidate_cache(recipient)
317
318         result =
319           conn
320           |> get(unquote(tested_endpoint))
321           |> json_response_and_validate_schema(200)
322
323         assert length(result) == 0
324       end
325
326       test "it does not return chats with users you blocked", %{conn: conn, user: user} do
327         recipient = insert(:user)
328
329         {:ok, _} = Chat.get_or_create(user.id, recipient.ap_id)
330
331         result =
332           conn
333           |> get(unquote(tested_endpoint))
334           |> json_response_and_validate_schema(200)
335
336         assert length(result) == 1
337
338         User.block(user, recipient)
339
340         result =
341           conn
342           |> get(unquote(tested_endpoint))
343           |> json_response_and_validate_schema(200)
344
345         assert length(result) == 0
346       end
347
348       test "it does not return chats with users you muted", %{conn: conn, user: user} do
349         recipient = insert(:user)
350
351         {:ok, _} = Chat.get_or_create(user.id, recipient.ap_id)
352
353         result =
354           conn
355           |> get(unquote(tested_endpoint))
356           |> json_response_and_validate_schema(200)
357
358         assert length(result) == 1
359
360         User.mute(user, recipient)
361
362         result =
363           conn
364           |> get(unquote(tested_endpoint))
365           |> json_response_and_validate_schema(200)
366
367         assert length(result) == 0
368
369         result =
370           conn
371           |> get("#{unquote(tested_endpoint)}?with_muted=true")
372           |> json_response_and_validate_schema(200)
373
374         assert length(result) == 1
375       end
376
377       if tested_endpoint == "/api/v1/pleroma/chats" do
378         test "it returns all chats", %{conn: conn, user: user} do
379           Enum.each(1..30, fn _ ->
380             recipient = insert(:user)
381             {:ok, _} = Chat.get_or_create(user.id, recipient.ap_id)
382           end)
383
384           result =
385             conn
386             |> get(unquote(tested_endpoint))
387             |> json_response_and_validate_schema(200)
388
389           assert length(result) == 30
390         end
391       else
392         test "it paginates chats", %{conn: conn, user: user} do
393           Enum.each(1..30, fn _ ->
394             recipient = insert(:user)
395             {:ok, _} = Chat.get_or_create(user.id, recipient.ap_id)
396           end)
397
398           result =
399             conn
400             |> get(unquote(tested_endpoint))
401             |> json_response_and_validate_schema(200)
402
403           assert length(result) == 20
404           last_id = List.last(result)["id"]
405
406           result =
407             conn
408             |> get(unquote(tested_endpoint) <> "?max_id=#{last_id}")
409             |> json_response_and_validate_schema(200)
410
411           assert length(result) == 10
412         end
413       end
414
415       test "it return a list of chats the current user is participating in, in descending order of updates",
416            %{conn: conn, user: user} do
417         har = insert(:user)
418         jafnhar = insert(:user)
419         tridi = insert(:user)
420
421         {:ok, chat_1} = Chat.get_or_create(user.id, har.ap_id)
422         {:ok, chat_1} = time_travel(chat_1, -3)
423         {:ok, chat_2} = Chat.get_or_create(user.id, jafnhar.ap_id)
424         {:ok, _chat_2} = time_travel(chat_2, -2)
425         {:ok, chat_3} = Chat.get_or_create(user.id, tridi.ap_id)
426         {:ok, chat_3} = time_travel(chat_3, -1)
427
428         # bump the second one
429         {:ok, chat_2} = Chat.bump_or_create(user.id, jafnhar.ap_id)
430
431         result =
432           conn
433           |> get(unquote(tested_endpoint))
434           |> json_response_and_validate_schema(200)
435
436         ids = Enum.map(result, & &1["id"])
437
438         assert ids == [
439                  chat_2.id |> to_string(),
440                  chat_3.id |> to_string(),
441                  chat_1.id |> to_string()
442                ]
443       end
444
445       test "it is not affected by :restrict_unauthenticated setting (issue #1973)", %{
446         conn: conn,
447         user: user
448       } do
449         clear_config([:restrict_unauthenticated, :profiles, :local], true)
450         clear_config([:restrict_unauthenticated, :profiles, :remote], true)
451
452         user2 = insert(:user)
453         user3 = insert(:user, local: false)
454
455         {:ok, _chat_12} = Chat.get_or_create(user.id, user2.ap_id)
456         {:ok, _chat_13} = Chat.get_or_create(user.id, user3.ap_id)
457
458         result =
459           conn
460           |> get(unquote(tested_endpoint))
461           |> json_response_and_validate_schema(200)
462
463         account_ids = Enum.map(result, &get_in(&1, ["account", "id"]))
464         assert Enum.sort(account_ids) == Enum.sort([user2.id, user3.id])
465       end
466     end
467   end
468 end