Merge branch 'app-list-changes' into 'develop'
[akkoma] / lib / pleroma / web / mastodon_api / mastodon_api_controller.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do
6 use Pleroma.Web, :controller
7 alias Pleroma.{Repo, Object, Activity, User, Notification, Stats}
8 alias Pleroma.Web
9 alias Pleroma.HTML
10
11 alias Pleroma.Web.MastodonAPI.{
12 StatusView,
13 AccountView,
14 MastodonView,
15 ListView,
16 FilterView,
17 PushSubscriptionView
18 }
19
20 alias Pleroma.Web.ActivityPub.ActivityPub
21 alias Pleroma.Web.ActivityPub.Utils
22 alias Pleroma.Web.CommonAPI
23 alias Pleroma.Web.OAuth.{Authorization, Token, App}
24 alias Pleroma.Web.MediaProxy
25
26 import Ecto.Query
27 require Logger
28
29 @httpoison Application.get_env(:pleroma, :httpoison)
30
31 action_fallback(:errors)
32
33 def create_app(conn, params) do
34 with cs <- App.register_changeset(%App{}, params) |> IO.inspect(),
35 {:ok, app} <- Repo.insert(cs) |> IO.inspect() do
36 res = %{
37 id: app.id |> to_string,
38 name: app.client_name,
39 client_id: app.client_id,
40 client_secret: app.client_secret,
41 redirect_uri: app.redirect_uris,
42 website: app.website
43 }
44
45 json(conn, res)
46 end
47 end
48
49 defp add_if_present(
50 map,
51 params,
52 params_field,
53 map_field,
54 value_function \\ fn x -> {:ok, x} end
55 ) do
56 if Map.has_key?(params, params_field) do
57 case value_function.(params[params_field]) do
58 {:ok, new_value} -> Map.put(map, map_field, new_value)
59 :error -> map
60 end
61 else
62 map
63 end
64 end
65
66 def update_credentials(%{assigns: %{user: user}} = conn, params) do
67 original_user = user
68
69 user_params =
70 %{}
71 |> add_if_present(params, "display_name", :name)
72 |> add_if_present(params, "note", :bio, fn value -> {:ok, User.parse_bio(value)} end)
73 |> add_if_present(params, "avatar", :avatar, fn value ->
74 with %Plug.Upload{} <- value,
75 {:ok, object} <- ActivityPub.upload(value, type: :avatar) do
76 {:ok, object.data}
77 else
78 _ -> :error
79 end
80 end)
81
82 info_params =
83 %{}
84 |> add_if_present(params, "locked", :locked, fn value -> {:ok, value == "true"} end)
85 |> add_if_present(params, "header", :banner, fn value ->
86 with %Plug.Upload{} <- value,
87 {:ok, object} <- ActivityPub.upload(value, type: :banner) do
88 {:ok, object.data}
89 else
90 _ -> :error
91 end
92 end)
93
94 info_cng = User.Info.mastodon_profile_update(user.info, info_params)
95
96 with changeset <- User.update_changeset(user, user_params),
97 changeset <- Ecto.Changeset.put_embed(changeset, :info, info_cng),
98 {:ok, user} <- User.update_and_set_cache(changeset) do
99 if original_user != user do
100 CommonAPI.update(user)
101 end
102
103 json(conn, AccountView.render("account.json", %{user: user, for: user}))
104 else
105 _e ->
106 conn
107 |> put_status(403)
108 |> json(%{error: "Invalid request"})
109 end
110 end
111
112 def verify_credentials(%{assigns: %{user: user}} = conn, _) do
113 account = AccountView.render("account.json", %{user: user, for: user})
114 json(conn, account)
115 end
116
117 def user(%{assigns: %{user: for_user}} = conn, %{"id" => id}) do
118 with %User{} = user <- Repo.get(User, id),
119 true <- User.auth_active?(user) || user.id == for_user.id || User.superuser?(for_user) do
120 account = AccountView.render("account.json", %{user: user, for: for_user})
121 json(conn, account)
122 else
123 _e ->
124 conn
125 |> put_status(404)
126 |> json(%{error: "Can't find user"})
127 end
128 end
129
130 @mastodon_api_level "2.5.0"
131
132 def masto_instance(conn, _params) do
133 instance = Pleroma.Config.get(:instance)
134
135 response = %{
136 uri: Web.base_url(),
137 title: Keyword.get(instance, :name),
138 description: Keyword.get(instance, :description),
139 version: "#{@mastodon_api_level} (compatible; #{Pleroma.Application.named_version()})",
140 email: Keyword.get(instance, :email),
141 urls: %{
142 streaming_api: String.replace(Pleroma.Web.Endpoint.static_url(), "http", "ws")
143 },
144 stats: Stats.get_stats(),
145 thumbnail: Web.base_url() <> "/instance/thumbnail.jpeg",
146 max_toot_chars: Keyword.get(instance, :limit)
147 }
148
149 json(conn, response)
150 end
151
152 def peers(conn, _params) do
153 json(conn, Stats.get_peers())
154 end
155
156 defp mastodonized_emoji do
157 Pleroma.Emoji.get_all()
158 |> Enum.map(fn {shortcode, relative_url} ->
159 url = to_string(URI.merge(Web.base_url(), relative_url))
160
161 %{
162 "shortcode" => shortcode,
163 "static_url" => url,
164 "visible_in_picker" => true,
165 "url" => url
166 }
167 end)
168 end
169
170 def custom_emojis(conn, _params) do
171 mastodon_emoji = mastodonized_emoji()
172 json(conn, mastodon_emoji)
173 end
174
175 defp add_link_headers(conn, method, activities, param \\ nil, params \\ %{}) do
176 last = List.last(activities)
177 first = List.first(activities)
178
179 if last do
180 min = last.id
181 max = first.id
182
183 {next_url, prev_url} =
184 if param do
185 {
186 mastodon_api_url(
187 Pleroma.Web.Endpoint,
188 method,
189 param,
190 Map.merge(params, %{max_id: min})
191 ),
192 mastodon_api_url(
193 Pleroma.Web.Endpoint,
194 method,
195 param,
196 Map.merge(params, %{since_id: max})
197 )
198 }
199 else
200 {
201 mastodon_api_url(
202 Pleroma.Web.Endpoint,
203 method,
204 Map.merge(params, %{max_id: min})
205 ),
206 mastodon_api_url(
207 Pleroma.Web.Endpoint,
208 method,
209 Map.merge(params, %{since_id: max})
210 )
211 }
212 end
213
214 conn
215 |> put_resp_header("link", "<#{next_url}>; rel=\"next\", <#{prev_url}>; rel=\"prev\"")
216 else
217 conn
218 end
219 end
220
221 def home_timeline(%{assigns: %{user: user}} = conn, params) do
222 params =
223 params
224 |> Map.put("type", ["Create", "Announce"])
225 |> Map.put("blocking_user", user)
226 |> Map.put("user", user)
227
228 activities =
229 ActivityPub.fetch_activities([user.ap_id | user.following], params)
230 |> ActivityPub.contain_timeline(user)
231 |> Enum.reverse()
232
233 conn
234 |> add_link_headers(:home_timeline, activities)
235 |> put_view(StatusView)
236 |> render("index.json", %{activities: activities, for: user, as: :activity})
237 end
238
239 def public_timeline(%{assigns: %{user: user}} = conn, params) do
240 local_only = params["local"] in [true, "True", "true", "1"]
241
242 params =
243 params
244 |> Map.put("type", ["Create", "Announce"])
245 |> Map.put("local_only", local_only)
246 |> Map.put("blocking_user", user)
247
248 activities =
249 ActivityPub.fetch_public_activities(params)
250 |> Enum.reverse()
251
252 conn
253 |> add_link_headers(:public_timeline, activities, false, %{"local" => local_only})
254 |> put_view(StatusView)
255 |> render("index.json", %{activities: activities, for: user, as: :activity})
256 end
257
258 def user_statuses(%{assigns: %{user: reading_user}} = conn, params) do
259 with %User{} = user <- Repo.get(User, params["id"]) do
260 activities = ActivityPub.fetch_user_activities(user, reading_user, params)
261
262 conn
263 |> add_link_headers(:user_statuses, activities, params["id"])
264 |> put_view(StatusView)
265 |> render("index.json", %{
266 activities: activities,
267 for: reading_user,
268 as: :activity
269 })
270 end
271 end
272
273 def dm_timeline(%{assigns: %{user: user}} = conn, params) do
274 query =
275 ActivityPub.fetch_activities_query(
276 [user.ap_id],
277 Map.merge(params, %{"type" => "Create", visibility: "direct"})
278 )
279
280 activities = Repo.all(query)
281
282 conn
283 |> add_link_headers(:dm_timeline, activities)
284 |> put_view(StatusView)
285 |> render("index.json", %{activities: activities, for: user, as: :activity})
286 end
287
288 def get_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
289 with %Activity{} = activity <- Repo.get(Activity, id),
290 true <- ActivityPub.visible_for_user?(activity, user) do
291 conn
292 |> put_view(StatusView)
293 |> try_render("status.json", %{activity: activity, for: user})
294 end
295 end
296
297 def get_context(%{assigns: %{user: user}} = conn, %{"id" => id}) do
298 with %Activity{} = activity <- Repo.get(Activity, id),
299 activities <-
300 ActivityPub.fetch_activities_for_context(activity.data["context"], %{
301 "blocking_user" => user,
302 "user" => user
303 }),
304 activities <-
305 activities |> Enum.filter(fn %{id: aid} -> to_string(aid) != to_string(id) end),
306 activities <-
307 activities |> Enum.filter(fn %{data: %{"type" => type}} -> type == "Create" end),
308 grouped_activities <- Enum.group_by(activities, fn %{id: id} -> id < activity.id end) do
309 result = %{
310 ancestors:
311 StatusView.render(
312 "index.json",
313 for: user,
314 activities: grouped_activities[true] || [],
315 as: :activity
316 )
317 |> Enum.reverse(),
318 descendants:
319 StatusView.render(
320 "index.json",
321 for: user,
322 activities: grouped_activities[false] || [],
323 as: :activity
324 )
325 |> Enum.reverse()
326 }
327
328 json(conn, result)
329 end
330 end
331
332 def post_status(conn, %{"status" => "", "media_ids" => media_ids} = params)
333 when length(media_ids) > 0 do
334 params =
335 params
336 |> Map.put("status", ".")
337
338 post_status(conn, params)
339 end
340
341 def post_status(%{assigns: %{user: user}} = conn, %{"status" => _} = params) do
342 params =
343 params
344 |> Map.put("in_reply_to_status_id", params["in_reply_to_id"])
345
346 idempotency_key =
347 case get_req_header(conn, "idempotency-key") do
348 [key] -> key
349 _ -> Ecto.UUID.generate()
350 end
351
352 {:ok, activity} =
353 Cachex.fetch!(:idempotency_cache, idempotency_key, fn _ -> CommonAPI.post(user, params) end)
354
355 conn
356 |> put_view(StatusView)
357 |> try_render("status.json", %{activity: activity, for: user, as: :activity})
358 end
359
360 def delete_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
361 with {:ok, %Activity{}} <- CommonAPI.delete(id, user) do
362 json(conn, %{})
363 else
364 _e ->
365 conn
366 |> put_status(403)
367 |> json(%{error: "Can't delete this post"})
368 end
369 end
370
371 def reblog_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
372 with {:ok, announce, _activity} <- CommonAPI.repeat(ap_id_or_id, user) do
373 conn
374 |> put_view(StatusView)
375 |> try_render("status.json", %{activity: announce, for: user, as: :activity})
376 end
377 end
378
379 def unreblog_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
380 with {:ok, _unannounce, %{data: %{"id" => id}}} <- CommonAPI.unrepeat(ap_id_or_id, user),
381 %Activity{} = activity <- Activity.get_create_by_object_ap_id(id) do
382 conn
383 |> put_view(StatusView)
384 |> try_render("status.json", %{activity: activity, for: user, as: :activity})
385 end
386 end
387
388 def fav_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
389 with {:ok, _fav, %{data: %{"id" => id}}} <- CommonAPI.favorite(ap_id_or_id, user),
390 %Activity{} = activity <- Activity.get_create_by_object_ap_id(id) do
391 conn
392 |> put_view(StatusView)
393 |> try_render("status.json", %{activity: activity, for: user, as: :activity})
394 end
395 end
396
397 def unfav_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
398 with {:ok, _, _, %{data: %{"id" => id}}} <- CommonAPI.unfavorite(ap_id_or_id, user),
399 %Activity{} = activity <- Activity.get_create_by_object_ap_id(id) do
400 conn
401 |> put_view(StatusView)
402 |> try_render("status.json", %{activity: activity, for: user, as: :activity})
403 end
404 end
405
406 def pin_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
407 with {:ok, activity} <- CommonAPI.pin(ap_id_or_id, user) do
408 conn
409 |> put_view(StatusView)
410 |> try_render("status.json", %{activity: activity, for: user, as: :activity})
411 else
412 {:error, reason} ->
413 conn
414 |> put_resp_content_type("application/json")
415 |> send_resp(:bad_request, Jason.encode!(%{"error" => reason}))
416 end
417 end
418
419 def unpin_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
420 with {:ok, activity} <- CommonAPI.unpin(ap_id_or_id, user) do
421 conn
422 |> put_view(StatusView)
423 |> try_render("status.json", %{activity: activity, for: user, as: :activity})
424 end
425 end
426
427 def notifications(%{assigns: %{user: user}} = conn, params) do
428 notifications = Notification.for_user(user, params)
429
430 result =
431 Enum.map(notifications, fn x ->
432 render_notification(user, x)
433 end)
434 |> Enum.filter(& &1)
435
436 conn
437 |> add_link_headers(:notifications, notifications)
438 |> json(result)
439 end
440
441 def get_notification(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
442 with {:ok, notification} <- Notification.get(user, id) do
443 json(conn, render_notification(user, notification))
444 else
445 {:error, reason} ->
446 conn
447 |> put_resp_content_type("application/json")
448 |> send_resp(403, Jason.encode!(%{"error" => reason}))
449 end
450 end
451
452 def clear_notifications(%{assigns: %{user: user}} = conn, _params) do
453 Notification.clear(user)
454 json(conn, %{})
455 end
456
457 def dismiss_notification(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
458 with {:ok, _notif} <- Notification.dismiss(user, id) do
459 json(conn, %{})
460 else
461 {:error, reason} ->
462 conn
463 |> put_resp_content_type("application/json")
464 |> send_resp(403, Jason.encode!(%{"error" => reason}))
465 end
466 end
467
468 def relationships(%{assigns: %{user: user}} = conn, %{"id" => id}) do
469 id = List.wrap(id)
470 q = from(u in User, where: u.id in ^id)
471 targets = Repo.all(q)
472
473 conn
474 |> put_view(AccountView)
475 |> render("relationships.json", %{user: user, targets: targets})
476 end
477
478 # Instead of returning a 400 when no "id" params is present, Mastodon returns an empty array.
479 def relationships(%{assigns: %{user: _user}} = conn, _), do: json(conn, [])
480
481 def update_media(%{assigns: %{user: user}} = conn, data) do
482 with %Object{} = object <- Repo.get(Object, data["id"]),
483 true <- Object.authorize_mutation(object, user),
484 true <- is_binary(data["description"]),
485 description <- data["description"] do
486 new_data = %{object.data | "name" => description}
487
488 {:ok, _} =
489 object
490 |> Object.change(%{data: new_data})
491 |> Repo.update()
492
493 attachment_data = Map.put(new_data, "id", object.id)
494
495 conn
496 |> put_view(StatusView)
497 |> render("attachment.json", %{attachment: attachment_data})
498 end
499 end
500
501 def upload(%{assigns: %{user: user}} = conn, %{"file" => file} = data) do
502 with {:ok, object} <-
503 ActivityPub.upload(file,
504 actor: User.ap_id(user),
505 description: Map.get(data, "description")
506 ) do
507 attachment_data = Map.put(object.data, "id", object.id)
508
509 conn
510 |> put_view(StatusView)
511 |> render("attachment.json", %{attachment: attachment_data})
512 end
513 end
514
515 def favourited_by(conn, %{"id" => id}) do
516 with %Activity{data: %{"object" => %{"likes" => likes}}} <- Repo.get(Activity, id) do
517 q = from(u in User, where: u.ap_id in ^likes)
518 users = Repo.all(q)
519
520 conn
521 |> put_view(AccountView)
522 |> render(AccountView, "accounts.json", %{users: users, as: :user})
523 else
524 _ -> json(conn, [])
525 end
526 end
527
528 def reblogged_by(conn, %{"id" => id}) do
529 with %Activity{data: %{"object" => %{"announcements" => announces}}} <- Repo.get(Activity, id) do
530 q = from(u in User, where: u.ap_id in ^announces)
531 users = Repo.all(q)
532
533 conn
534 |> put_view(AccountView)
535 |> render("accounts.json", %{users: users, as: :user})
536 else
537 _ -> json(conn, [])
538 end
539 end
540
541 def hashtag_timeline(%{assigns: %{user: user}} = conn, params) do
542 local_only = params["local"] in [true, "True", "true", "1"]
543
544 tags =
545 [params["tag"], params["any"]]
546 |> List.flatten()
547 |> Enum.uniq()
548 |> Enum.filter(& &1)
549 |> Enum.map(&String.downcase(&1))
550
551 tag_all =
552 params["all"] ||
553 []
554 |> Enum.map(&String.downcase(&1))
555
556 tag_reject =
557 params["none"] ||
558 []
559 |> Enum.map(&String.downcase(&1))
560
561 query_params =
562 params
563 |> Map.put("type", "Create")
564 |> Map.put("local_only", local_only)
565 |> Map.put("blocking_user", user)
566 |> Map.put("tag", tags)
567 |> Map.put("tag_all", tag_all)
568 |> Map.put("tag_reject", tag_reject)
569
570 activities =
571 ActivityPub.fetch_public_activities(query_params)
572 |> Enum.reverse()
573
574 conn
575 |> add_link_headers(:hashtag_timeline, activities, params["tag"], %{"local" => local_only})
576 |> put_view(StatusView)
577 |> render("index.json", %{activities: activities, for: user, as: :activity})
578 end
579
580 def followers(%{assigns: %{user: for_user}} = conn, %{"id" => id}) do
581 with %User{} = user <- Repo.get(User, id),
582 {:ok, followers} <- User.get_followers(user) do
583 followers =
584 cond do
585 for_user && user.id == for_user.id -> followers
586 user.info.hide_network -> []
587 true -> followers
588 end
589
590 conn
591 |> put_view(AccountView)
592 |> render("accounts.json", %{users: followers, as: :user})
593 end
594 end
595
596 def following(%{assigns: %{user: for_user}} = conn, %{"id" => id}) do
597 with %User{} = user <- Repo.get(User, id),
598 {:ok, followers} <- User.get_friends(user) do
599 followers =
600 cond do
601 for_user && user.id == for_user.id -> followers
602 user.info.hide_network -> []
603 true -> followers
604 end
605
606 conn
607 |> put_view(AccountView)
608 |> render("accounts.json", %{users: followers, as: :user})
609 end
610 end
611
612 def follow_requests(%{assigns: %{user: followed}} = conn, _params) do
613 with {:ok, follow_requests} <- User.get_follow_requests(followed) do
614 conn
615 |> put_view(AccountView)
616 |> render("accounts.json", %{users: follow_requests, as: :user})
617 end
618 end
619
620 def authorize_follow_request(%{assigns: %{user: followed}} = conn, %{"id" => id}) do
621 with %User{} = follower <- Repo.get(User, id),
622 {:ok, follower} <- User.maybe_follow(follower, followed),
623 %Activity{} = follow_activity <- Utils.fetch_latest_follow(follower, followed),
624 {:ok, follow_activity} <- Utils.update_follow_state(follow_activity, "accept"),
625 {:ok, _activity} <-
626 ActivityPub.accept(%{
627 to: [follower.ap_id],
628 actor: followed.ap_id,
629 object: follow_activity.data["id"],
630 type: "Accept"
631 }) do
632 conn
633 |> put_view(AccountView)
634 |> render("relationship.json", %{user: followed, target: follower})
635 else
636 {:error, message} ->
637 conn
638 |> put_resp_content_type("application/json")
639 |> send_resp(403, Jason.encode!(%{"error" => message}))
640 end
641 end
642
643 def reject_follow_request(%{assigns: %{user: followed}} = conn, %{"id" => id}) do
644 with %User{} = follower <- Repo.get(User, id),
645 %Activity{} = follow_activity <- Utils.fetch_latest_follow(follower, followed),
646 {:ok, follow_activity} <- Utils.update_follow_state(follow_activity, "reject"),
647 {:ok, _activity} <-
648 ActivityPub.reject(%{
649 to: [follower.ap_id],
650 actor: followed.ap_id,
651 object: follow_activity.data["id"],
652 type: "Reject"
653 }) do
654 conn
655 |> put_view(AccountView)
656 |> render("relationship.json", %{user: followed, target: follower})
657 else
658 {:error, message} ->
659 conn
660 |> put_resp_content_type("application/json")
661 |> send_resp(403, Jason.encode!(%{"error" => message}))
662 end
663 end
664
665 def follow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
666 with %User{} = followed <- Repo.get(User, id),
667 {:ok, follower} <- User.maybe_direct_follow(follower, followed),
668 {:ok, _activity} <- ActivityPub.follow(follower, followed),
669 {:ok, follower, followed} <-
670 User.wait_and_refresh(
671 Pleroma.Config.get([:activitypub, :follow_handshake_timeout]),
672 follower,
673 followed
674 ) do
675 conn
676 |> put_view(AccountView)
677 |> render("relationship.json", %{user: follower, target: followed})
678 else
679 {:error, message} ->
680 conn
681 |> put_resp_content_type("application/json")
682 |> send_resp(403, Jason.encode!(%{"error" => message}))
683 end
684 end
685
686 def follow(%{assigns: %{user: follower}} = conn, %{"uri" => uri}) do
687 with %User{} = followed <- Repo.get_by(User, nickname: uri),
688 {:ok, follower} <- User.maybe_direct_follow(follower, followed),
689 {:ok, _activity} <- ActivityPub.follow(follower, followed) do
690 conn
691 |> put_view(AccountView)
692 |> render("account.json", %{user: followed, for: follower})
693 else
694 {:error, message} ->
695 conn
696 |> put_resp_content_type("application/json")
697 |> send_resp(403, Jason.encode!(%{"error" => message}))
698 end
699 end
700
701 def unfollow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
702 with %User{} = followed <- Repo.get(User, id),
703 {:ok, _activity} <- ActivityPub.unfollow(follower, followed),
704 {:ok, follower, _} <- User.unfollow(follower, followed) do
705 conn
706 |> put_view(AccountView)
707 |> render("relationship.json", %{user: follower, target: followed})
708 end
709 end
710
711 def block(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
712 with %User{} = blocked <- Repo.get(User, id),
713 {:ok, blocker} <- User.block(blocker, blocked),
714 {:ok, _activity} <- ActivityPub.block(blocker, blocked) do
715 conn
716 |> put_view(AccountView)
717 |> render("relationship.json", %{user: blocker, target: blocked})
718 else
719 {:error, message} ->
720 conn
721 |> put_resp_content_type("application/json")
722 |> send_resp(403, Jason.encode!(%{"error" => message}))
723 end
724 end
725
726 def unblock(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
727 with %User{} = blocked <- Repo.get(User, id),
728 {:ok, blocker} <- User.unblock(blocker, blocked),
729 {:ok, _activity} <- ActivityPub.unblock(blocker, blocked) do
730 conn
731 |> put_view(AccountView)
732 |> render("relationship.json", %{user: blocker, target: blocked})
733 else
734 {:error, message} ->
735 conn
736 |> put_resp_content_type("application/json")
737 |> send_resp(403, Jason.encode!(%{"error" => message}))
738 end
739 end
740
741 def blocks(%{assigns: %{user: user}} = conn, _) do
742 with blocked_accounts <- User.blocked_users(user) do
743 res = AccountView.render("accounts.json", users: blocked_accounts, for: user, as: :user)
744 json(conn, res)
745 end
746 end
747
748 def domain_blocks(%{assigns: %{user: %{info: info}}} = conn, _) do
749 json(conn, info.domain_blocks || [])
750 end
751
752 def block_domain(%{assigns: %{user: blocker}} = conn, %{"domain" => domain}) do
753 User.block_domain(blocker, domain)
754 json(conn, %{})
755 end
756
757 def unblock_domain(%{assigns: %{user: blocker}} = conn, %{"domain" => domain}) do
758 User.unblock_domain(blocker, domain)
759 json(conn, %{})
760 end
761
762 def status_search(user, query) do
763 fetched =
764 if Regex.match?(~r/https?:/, query) do
765 with {:ok, object} <- ActivityPub.fetch_object_from_id(query),
766 %Activity{} = activity <- Activity.get_create_by_object_ap_id(object.data["id"]),
767 true <- ActivityPub.visible_for_user?(activity, user) do
768 [activity]
769 else
770 _e -> []
771 end
772 end || []
773
774 q =
775 from(
776 a in Activity,
777 where: fragment("?->>'type' = 'Create'", a.data),
778 where: "https://www.w3.org/ns/activitystreams#Public" in a.recipients,
779 where:
780 fragment(
781 "to_tsvector('english', ?->'object'->>'content') @@ plainto_tsquery('english', ?)",
782 a.data,
783 ^query
784 ),
785 limit: 20,
786 order_by: [desc: :id]
787 )
788
789 Repo.all(q) ++ fetched
790 end
791
792 def search2(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
793 accounts = User.search(query, params["resolve"] == "true", user)
794
795 statuses = status_search(user, query)
796
797 tags_path = Web.base_url() <> "/tag/"
798
799 tags =
800 String.split(query)
801 |> Enum.uniq()
802 |> Enum.filter(fn tag -> String.starts_with?(tag, "#") end)
803 |> Enum.map(fn tag -> String.slice(tag, 1..-1) end)
804 |> Enum.map(fn tag -> %{name: tag, url: tags_path <> tag} end)
805
806 res = %{
807 "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
808 "statuses" =>
809 StatusView.render("index.json", activities: statuses, for: user, as: :activity),
810 "hashtags" => tags
811 }
812
813 json(conn, res)
814 end
815
816 def search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
817 accounts = User.search(query, params["resolve"] == "true", user)
818
819 statuses = status_search(user, query)
820
821 tags =
822 String.split(query)
823 |> Enum.uniq()
824 |> Enum.filter(fn tag -> String.starts_with?(tag, "#") end)
825 |> Enum.map(fn tag -> String.slice(tag, 1..-1) end)
826
827 res = %{
828 "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
829 "statuses" =>
830 StatusView.render("index.json", activities: statuses, for: user, as: :activity),
831 "hashtags" => tags
832 }
833
834 json(conn, res)
835 end
836
837 def account_search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
838 accounts = User.search(query, params["resolve"] == "true", user)
839
840 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
841
842 json(conn, res)
843 end
844
845 def favourites(%{assigns: %{user: user}} = conn, params) do
846 params =
847 params
848 |> Map.put("type", "Create")
849 |> Map.put("favorited_by", user.ap_id)
850 |> Map.put("blocking_user", user)
851
852 activities =
853 ActivityPub.fetch_public_activities(params)
854 |> Enum.reverse()
855
856 conn
857 |> add_link_headers(:favourites, activities)
858 |> put_view(StatusView)
859 |> render("index.json", %{activities: activities, for: user, as: :activity})
860 end
861
862 def get_lists(%{assigns: %{user: user}} = conn, opts) do
863 lists = Pleroma.List.for_user(user, opts)
864 res = ListView.render("lists.json", lists: lists)
865 json(conn, res)
866 end
867
868 def get_list(%{assigns: %{user: user}} = conn, %{"id" => id}) do
869 with %Pleroma.List{} = list <- Pleroma.List.get(id, user) do
870 res = ListView.render("list.json", list: list)
871 json(conn, res)
872 else
873 _e -> json(conn, "error")
874 end
875 end
876
877 def account_lists(%{assigns: %{user: user}} = conn, %{"id" => account_id}) do
878 lists = Pleroma.List.get_lists_account_belongs(user, account_id)
879 res = ListView.render("lists.json", lists: lists)
880 json(conn, res)
881 end
882
883 def delete_list(%{assigns: %{user: user}} = conn, %{"id" => id}) do
884 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
885 {:ok, _list} <- Pleroma.List.delete(list) do
886 json(conn, %{})
887 else
888 _e ->
889 json(conn, "error")
890 end
891 end
892
893 def create_list(%{assigns: %{user: user}} = conn, %{"title" => title}) do
894 with {:ok, %Pleroma.List{} = list} <- Pleroma.List.create(title, user) do
895 res = ListView.render("list.json", list: list)
896 json(conn, res)
897 end
898 end
899
900 def add_to_list(%{assigns: %{user: user}} = conn, %{"id" => id, "account_ids" => accounts}) do
901 accounts
902 |> Enum.each(fn account_id ->
903 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
904 %User{} = followed <- Repo.get(User, account_id) do
905 Pleroma.List.follow(list, followed)
906 end
907 end)
908
909 json(conn, %{})
910 end
911
912 def remove_from_list(%{assigns: %{user: user}} = conn, %{"id" => id, "account_ids" => accounts}) do
913 accounts
914 |> Enum.each(fn account_id ->
915 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
916 %User{} = followed <- Repo.get(Pleroma.User, account_id) do
917 Pleroma.List.unfollow(list, followed)
918 end
919 end)
920
921 json(conn, %{})
922 end
923
924 def list_accounts(%{assigns: %{user: user}} = conn, %{"id" => id}) do
925 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
926 {:ok, users} = Pleroma.List.get_following(list) do
927 conn
928 |> put_view(AccountView)
929 |> render("accounts.json", %{users: users, as: :user})
930 end
931 end
932
933 def rename_list(%{assigns: %{user: user}} = conn, %{"id" => id, "title" => title}) do
934 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
935 {:ok, list} <- Pleroma.List.rename(list, title) do
936 res = ListView.render("list.json", list: list)
937 json(conn, res)
938 else
939 _e ->
940 json(conn, "error")
941 end
942 end
943
944 def list_timeline(%{assigns: %{user: user}} = conn, %{"list_id" => id} = params) do
945 with %Pleroma.List{title: _title, following: following} <- Pleroma.List.get(id, user) do
946 params =
947 params
948 |> Map.put("type", "Create")
949 |> Map.put("blocking_user", user)
950
951 # we must filter the following list for the user to avoid leaking statuses the user
952 # does not actually have permission to see (for more info, peruse security issue #270).
953 following_to =
954 following
955 |> Enum.filter(fn x -> x in user.following end)
956
957 activities =
958 ActivityPub.fetch_activities_bounded(following_to, following, params)
959 |> Enum.reverse()
960
961 conn
962 |> put_view(StatusView)
963 |> render("index.json", %{activities: activities, for: user, as: :activity})
964 else
965 _e ->
966 conn
967 |> put_status(403)
968 |> json(%{error: "Error."})
969 end
970 end
971
972 def index(%{assigns: %{user: user}} = conn, _params) do
973 token =
974 conn
975 |> get_session(:oauth_token)
976
977 if user && token do
978 mastodon_emoji = mastodonized_emoji()
979
980 limit = Pleroma.Config.get([:instance, :limit])
981
982 accounts =
983 Map.put(%{}, user.id, AccountView.render("account.json", %{user: user, for: user}))
984
985 initial_state =
986 %{
987 meta: %{
988 streaming_api_base_url:
989 String.replace(Pleroma.Web.Endpoint.static_url(), "http", "ws"),
990 access_token: token,
991 locale: "en",
992 domain: Pleroma.Web.Endpoint.host(),
993 admin: "1",
994 me: "#{user.id}",
995 unfollow_modal: false,
996 boost_modal: false,
997 delete_modal: true,
998 auto_play_gif: false,
999 display_sensitive_media: false,
1000 reduce_motion: false,
1001 max_toot_chars: limit
1002 },
1003 rights: %{
1004 delete_others_notice: !!user.info.is_moderator,
1005 admin: !!user.info.is_admin
1006 },
1007 compose: %{
1008 me: "#{user.id}",
1009 default_privacy: user.info.default_scope,
1010 default_sensitive: false
1011 },
1012 media_attachments: %{
1013 accept_content_types: [
1014 ".jpg",
1015 ".jpeg",
1016 ".png",
1017 ".gif",
1018 ".webm",
1019 ".mp4",
1020 ".m4v",
1021 "image\/jpeg",
1022 "image\/png",
1023 "image\/gif",
1024 "video\/webm",
1025 "video\/mp4"
1026 ]
1027 },
1028 settings:
1029 user.info.settings ||
1030 %{
1031 onboarded: true,
1032 home: %{
1033 shows: %{
1034 reblog: true,
1035 reply: true
1036 }
1037 },
1038 notifications: %{
1039 alerts: %{
1040 follow: true,
1041 favourite: true,
1042 reblog: true,
1043 mention: true
1044 },
1045 shows: %{
1046 follow: true,
1047 favourite: true,
1048 reblog: true,
1049 mention: true
1050 },
1051 sounds: %{
1052 follow: true,
1053 favourite: true,
1054 reblog: true,
1055 mention: true
1056 }
1057 }
1058 },
1059 push_subscription: nil,
1060 accounts: accounts,
1061 custom_emojis: mastodon_emoji,
1062 char_limit: limit
1063 }
1064 |> Jason.encode!()
1065
1066 conn
1067 |> put_layout(false)
1068 |> put_view(MastodonView)
1069 |> render("index.html", %{initial_state: initial_state})
1070 else
1071 conn
1072 |> redirect(to: "/web/login")
1073 end
1074 end
1075
1076 def put_settings(%{assigns: %{user: user}} = conn, %{"data" => settings} = _params) do
1077 info_cng = User.Info.mastodon_settings_update(user.info, settings)
1078
1079 with changeset <- Ecto.Changeset.change(user),
1080 changeset <- Ecto.Changeset.put_embed(changeset, :info, info_cng),
1081 {:ok, _user} <- User.update_and_set_cache(changeset) do
1082 json(conn, %{})
1083 else
1084 e ->
1085 conn
1086 |> put_resp_content_type("application/json")
1087 |> send_resp(500, Jason.encode!(%{"error" => inspect(e)}))
1088 end
1089 end
1090
1091 def login(conn, %{"code" => code}) do
1092 with {:ok, app} <- get_or_make_app(),
1093 %Authorization{} = auth <- Repo.get_by(Authorization, token: code, app_id: app.id),
1094 {:ok, token} <- Token.exchange_token(app, auth) do
1095 conn
1096 |> put_session(:oauth_token, token.token)
1097 |> redirect(to: "/web/getting-started")
1098 end
1099 end
1100
1101 def login(conn, _) do
1102 with {:ok, app} <- get_or_make_app() do
1103 path =
1104 o_auth_path(conn, :authorize,
1105 response_type: "code",
1106 client_id: app.client_id,
1107 redirect_uri: ".",
1108 scope: app.scopes
1109 )
1110
1111 conn
1112 |> redirect(to: path)
1113 end
1114 end
1115
1116 defp get_or_make_app() do
1117 with %App{} = app <- Repo.get_by(App, client_name: "Mastodon-Local") do
1118 {:ok, app}
1119 else
1120 _e ->
1121 cs =
1122 App.register_changeset(%App{}, %{
1123 client_name: "Mastodon-Local",
1124 redirect_uris: ".",
1125 scopes: "read,write,follow"
1126 })
1127
1128 Repo.insert(cs)
1129 end
1130 end
1131
1132 def logout(conn, _) do
1133 conn
1134 |> clear_session
1135 |> redirect(to: "/")
1136 end
1137
1138 def relationship_noop(%{assigns: %{user: user}} = conn, %{"id" => id}) do
1139 Logger.debug("Unimplemented, returning unmodified relationship")
1140
1141 with %User{} = target <- Repo.get(User, id) do
1142 conn
1143 |> put_view(AccountView)
1144 |> render("relationship.json", %{user: user, target: target})
1145 end
1146 end
1147
1148 def empty_array(conn, _) do
1149 Logger.debug("Unimplemented, returning an empty array")
1150 json(conn, [])
1151 end
1152
1153 def empty_object(conn, _) do
1154 Logger.debug("Unimplemented, returning an empty object")
1155 json(conn, %{})
1156 end
1157
1158 def render_notification(user, %{id: id, activity: activity, inserted_at: created_at} = _params) do
1159 actor = User.get_cached_by_ap_id(activity.data["actor"])
1160 parent_activity = Activity.get_create_by_object_ap_id(activity.data["object"])
1161 mastodon_type = Activity.mastodon_notification_type(activity)
1162
1163 response = %{
1164 id: to_string(id),
1165 type: mastodon_type,
1166 created_at: CommonAPI.Utils.to_masto_date(created_at),
1167 account: AccountView.render("account.json", %{user: actor, for: user})
1168 }
1169
1170 case mastodon_type do
1171 "mention" ->
1172 response
1173 |> Map.merge(%{
1174 status: StatusView.render("status.json", %{activity: activity, for: user})
1175 })
1176
1177 "favourite" ->
1178 response
1179 |> Map.merge(%{
1180 status: StatusView.render("status.json", %{activity: parent_activity, for: user})
1181 })
1182
1183 "reblog" ->
1184 response
1185 |> Map.merge(%{
1186 status: StatusView.render("status.json", %{activity: parent_activity, for: user})
1187 })
1188
1189 "follow" ->
1190 response
1191
1192 _ ->
1193 nil
1194 end
1195 end
1196
1197 def get_filters(%{assigns: %{user: user}} = conn, _) do
1198 filters = Pleroma.Filter.get_filters(user)
1199 res = FilterView.render("filters.json", filters: filters)
1200 json(conn, res)
1201 end
1202
1203 def create_filter(
1204 %{assigns: %{user: user}} = conn,
1205 %{"phrase" => phrase, "context" => context} = params
1206 ) do
1207 query = %Pleroma.Filter{
1208 user_id: user.id,
1209 phrase: phrase,
1210 context: context,
1211 hide: Map.get(params, "irreversible", nil),
1212 whole_word: Map.get(params, "boolean", true)
1213 # expires_at
1214 }
1215
1216 {:ok, response} = Pleroma.Filter.create(query)
1217 res = FilterView.render("filter.json", filter: response)
1218 json(conn, res)
1219 end
1220
1221 def get_filter(%{assigns: %{user: user}} = conn, %{"id" => filter_id}) do
1222 filter = Pleroma.Filter.get(filter_id, user)
1223 res = FilterView.render("filter.json", filter: filter)
1224 json(conn, res)
1225 end
1226
1227 def update_filter(
1228 %{assigns: %{user: user}} = conn,
1229 %{"phrase" => phrase, "context" => context, "id" => filter_id} = params
1230 ) do
1231 query = %Pleroma.Filter{
1232 user_id: user.id,
1233 filter_id: filter_id,
1234 phrase: phrase,
1235 context: context,
1236 hide: Map.get(params, "irreversible", nil),
1237 whole_word: Map.get(params, "boolean", true)
1238 # expires_at
1239 }
1240
1241 {:ok, response} = Pleroma.Filter.update(query)
1242 res = FilterView.render("filter.json", filter: response)
1243 json(conn, res)
1244 end
1245
1246 def delete_filter(%{assigns: %{user: user}} = conn, %{"id" => filter_id}) do
1247 query = %Pleroma.Filter{
1248 user_id: user.id,
1249 filter_id: filter_id
1250 }
1251
1252 {:ok, _} = Pleroma.Filter.delete(query)
1253 json(conn, %{})
1254 end
1255
1256 def create_push_subscription(%{assigns: %{user: user, token: token}} = conn, params) do
1257 true = Pleroma.Web.Push.enabled()
1258 Pleroma.Web.Push.Subscription.delete_if_exists(user, token)
1259 {:ok, subscription} = Pleroma.Web.Push.Subscription.create(user, token, params)
1260 view = PushSubscriptionView.render("push_subscription.json", subscription: subscription)
1261 json(conn, view)
1262 end
1263
1264 def get_push_subscription(%{assigns: %{user: user, token: token}} = conn, _params) do
1265 true = Pleroma.Web.Push.enabled()
1266 subscription = Pleroma.Web.Push.Subscription.get(user, token)
1267 view = PushSubscriptionView.render("push_subscription.json", subscription: subscription)
1268 json(conn, view)
1269 end
1270
1271 def update_push_subscription(
1272 %{assigns: %{user: user, token: token}} = conn,
1273 params
1274 ) do
1275 true = Pleroma.Web.Push.enabled()
1276 {:ok, subscription} = Pleroma.Web.Push.Subscription.update(user, token, params)
1277 view = PushSubscriptionView.render("push_subscription.json", subscription: subscription)
1278 json(conn, view)
1279 end
1280
1281 def delete_push_subscription(%{assigns: %{user: user, token: token}} = conn, _params) do
1282 true = Pleroma.Web.Push.enabled()
1283 {:ok, _response} = Pleroma.Web.Push.Subscription.delete(user, token)
1284 json(conn, %{})
1285 end
1286
1287 def errors(conn, _) do
1288 conn
1289 |> put_status(500)
1290 |> json("Something went wrong")
1291 end
1292
1293 def suggestions(%{assigns: %{user: user}} = conn, _) do
1294 suggestions = Pleroma.Config.get(:suggestions)
1295
1296 if Keyword.get(suggestions, :enabled, false) do
1297 api = Keyword.get(suggestions, :third_party_engine, "")
1298 timeout = Keyword.get(suggestions, :timeout, 5000)
1299 limit = Keyword.get(suggestions, :limit, 23)
1300
1301 host = Pleroma.Config.get([Pleroma.Web.Endpoint, :url, :host])
1302
1303 user = user.nickname
1304 url = String.replace(api, "{{host}}", host) |> String.replace("{{user}}", user)
1305
1306 with {:ok, %{status: 200, body: body}} <-
1307 @httpoison.get(
1308 url,
1309 [],
1310 adapter: [
1311 timeout: timeout,
1312 recv_timeout: timeout
1313 ]
1314 ),
1315 {:ok, data} <- Jason.decode(body) do
1316 data2 =
1317 Enum.slice(data, 0, limit)
1318 |> Enum.map(fn x ->
1319 Map.put(
1320 x,
1321 "id",
1322 case User.get_or_fetch(x["acct"]) do
1323 %{id: id} -> id
1324 _ -> 0
1325 end
1326 )
1327 end)
1328 |> Enum.map(fn x ->
1329 Map.put(x, "avatar", MediaProxy.url(x["avatar"]))
1330 end)
1331 |> Enum.map(fn x ->
1332 Map.put(x, "avatar_static", MediaProxy.url(x["avatar_static"]))
1333 end)
1334
1335 conn
1336 |> json(data2)
1337 else
1338 e -> Logger.error("Could not retrieve suggestions at fetch #{url}, #{inspect(e)}")
1339 end
1340 else
1341 json(conn, [])
1342 end
1343 end
1344
1345 def get_status_card(status_id) do
1346 with %Activity{} = activity <- Repo.get(Activity, status_id),
1347 true <- ActivityPub.is_public?(activity),
1348 %Object{} = object <- Object.normalize(activity.data["object"]),
1349 page_url <- HTML.extract_first_external_url(object, object.data["content"]),
1350 {:ok, rich_media} <- Pleroma.Web.RichMedia.Parser.parse(page_url) do
1351 page_url = rich_media[:url] || page_url
1352 site_name = rich_media[:site_name] || URI.parse(page_url).host
1353
1354 rich_media
1355 |> Map.take([:image, :title, :description])
1356 |> Map.put(:type, "link")
1357 |> Map.put(:provider_name, site_name)
1358 |> Map.put(:url, page_url)
1359 else
1360 _ -> %{}
1361 end
1362 end
1363
1364 def status_card(conn, %{"id" => status_id}) do
1365 json(conn, get_status_card(status_id))
1366 end
1367
1368 def try_render(conn, target, params)
1369 when is_binary(target) do
1370 res = render(conn, target, params)
1371
1372 if res == nil do
1373 conn
1374 |> put_status(501)
1375 |> json(%{error: "Can't display this activity"})
1376 else
1377 res
1378 end
1379 end
1380
1381 def try_render(conn, _, _) do
1382 conn
1383 |> put_status(501)
1384 |> json(%{error: "Can't display this activity"})
1385 end
1386 end