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