e00a3fb8721849d8eaa302aed7ee23b3ff7f50b8
[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 |> Map.put("no_attachment_links", true)
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_activity_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_activity_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_activity_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 params =
545 params
546 |> Map.put("type", "Create")
547 |> Map.put("local_only", local_only)
548 |> Map.put("blocking_user", user)
549 |> Map.put("tag", String.downcase(params["tag"]))
550
551 activities =
552 ActivityPub.fetch_public_activities(params)
553 |> Enum.reverse()
554
555 conn
556 |> add_link_headers(:hashtag_timeline, activities, params["tag"], %{"local" => local_only})
557 |> put_view(StatusView)
558 |> render("index.json", %{activities: activities, for: user, as: :activity})
559 end
560
561 def followers(%{assigns: %{user: for_user}} = conn, %{"id" => id}) do
562 with %User{} = user <- Repo.get(User, id),
563 {:ok, followers} <- User.get_followers(user) do
564 followers =
565 cond do
566 for_user && user.id == for_user.id -> followers
567 user.info.hide_network -> []
568 true -> followers
569 end
570
571 conn
572 |> put_view(AccountView)
573 |> render("accounts.json", %{users: followers, as: :user})
574 end
575 end
576
577 def following(%{assigns: %{user: for_user}} = conn, %{"id" => id}) do
578 with %User{} = user <- Repo.get(User, id),
579 {:ok, followers} <- User.get_friends(user) do
580 followers =
581 cond do
582 for_user && user.id == for_user.id -> followers
583 user.info.hide_network -> []
584 true -> followers
585 end
586
587 conn
588 |> put_view(AccountView)
589 |> render("accounts.json", %{users: followers, as: :user})
590 end
591 end
592
593 def follow_requests(%{assigns: %{user: followed}} = conn, _params) do
594 with {:ok, follow_requests} <- User.get_follow_requests(followed) do
595 conn
596 |> put_view(AccountView)
597 |> render("accounts.json", %{users: follow_requests, as: :user})
598 end
599 end
600
601 def authorize_follow_request(%{assigns: %{user: followed}} = conn, %{"id" => id}) do
602 with %User{} = follower <- Repo.get(User, id),
603 {:ok, follower} <- User.maybe_follow(follower, followed),
604 %Activity{} = follow_activity <- Utils.fetch_latest_follow(follower, followed),
605 {:ok, follow_activity} <- Utils.update_follow_state(follow_activity, "accept"),
606 {:ok, _activity} <-
607 ActivityPub.accept(%{
608 to: [follower.ap_id],
609 actor: followed.ap_id,
610 object: follow_activity.data["id"],
611 type: "Accept"
612 }) do
613 conn
614 |> put_view(AccountView)
615 |> render("relationship.json", %{user: followed, target: follower})
616 else
617 {:error, message} ->
618 conn
619 |> put_resp_content_type("application/json")
620 |> send_resp(403, Jason.encode!(%{"error" => message}))
621 end
622 end
623
624 def reject_follow_request(%{assigns: %{user: followed}} = conn, %{"id" => id}) do
625 with %User{} = follower <- Repo.get(User, id),
626 %Activity{} = follow_activity <- Utils.fetch_latest_follow(follower, followed),
627 {:ok, follow_activity} <- Utils.update_follow_state(follow_activity, "reject"),
628 {:ok, _activity} <-
629 ActivityPub.reject(%{
630 to: [follower.ap_id],
631 actor: followed.ap_id,
632 object: follow_activity.data["id"],
633 type: "Reject"
634 }) do
635 conn
636 |> put_view(AccountView)
637 |> render("relationship.json", %{user: followed, target: follower})
638 else
639 {:error, message} ->
640 conn
641 |> put_resp_content_type("application/json")
642 |> send_resp(403, Jason.encode!(%{"error" => message}))
643 end
644 end
645
646 def follow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
647 with %User{} = followed <- Repo.get(User, id),
648 {:ok, follower} <- User.maybe_direct_follow(follower, followed),
649 {:ok, _activity} <- ActivityPub.follow(follower, followed),
650 {:ok, follower, followed} <-
651 User.wait_and_refresh(
652 Pleroma.Config.get([:activitypub, :follow_handshake_timeout]),
653 follower,
654 followed
655 ) do
656 conn
657 |> put_view(AccountView)
658 |> render("relationship.json", %{user: follower, target: followed})
659 else
660 {:error, message} ->
661 conn
662 |> put_resp_content_type("application/json")
663 |> send_resp(403, Jason.encode!(%{"error" => message}))
664 end
665 end
666
667 def follow(%{assigns: %{user: follower}} = conn, %{"uri" => uri}) do
668 with %User{} = followed <- Repo.get_by(User, nickname: uri),
669 {:ok, follower} <- User.maybe_direct_follow(follower, followed),
670 {:ok, _activity} <- ActivityPub.follow(follower, followed) do
671 conn
672 |> put_view(AccountView)
673 |> render("account.json", %{user: followed, for: follower})
674 else
675 {:error, message} ->
676 conn
677 |> put_resp_content_type("application/json")
678 |> send_resp(403, Jason.encode!(%{"error" => message}))
679 end
680 end
681
682 def unfollow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
683 with %User{} = followed <- Repo.get(User, id),
684 {:ok, _activity} <- ActivityPub.unfollow(follower, followed),
685 {:ok, follower, _} <- User.unfollow(follower, followed) do
686 conn
687 |> put_view(AccountView)
688 |> render("relationship.json", %{user: follower, target: followed})
689 end
690 end
691
692 def block(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
693 with %User{} = blocked <- Repo.get(User, id),
694 {:ok, blocker} <- User.block(blocker, blocked),
695 {:ok, _activity} <- ActivityPub.block(blocker, blocked) do
696 conn
697 |> put_view(AccountView)
698 |> render("relationship.json", %{user: blocker, target: blocked})
699 else
700 {:error, message} ->
701 conn
702 |> put_resp_content_type("application/json")
703 |> send_resp(403, Jason.encode!(%{"error" => message}))
704 end
705 end
706
707 def unblock(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
708 with %User{} = blocked <- Repo.get(User, id),
709 {:ok, blocker} <- User.unblock(blocker, blocked),
710 {:ok, _activity} <- ActivityPub.unblock(blocker, blocked) do
711 conn
712 |> put_view(AccountView)
713 |> render("relationship.json", %{user: blocker, target: blocked})
714 else
715 {:error, message} ->
716 conn
717 |> put_resp_content_type("application/json")
718 |> send_resp(403, Jason.encode!(%{"error" => message}))
719 end
720 end
721
722 def blocks(%{assigns: %{user: user}} = conn, _) do
723 with blocked_accounts <- User.blocked_users(user) do
724 res = AccountView.render("accounts.json", users: blocked_accounts, for: user, as: :user)
725 json(conn, res)
726 end
727 end
728
729 def domain_blocks(%{assigns: %{user: %{info: info}}} = conn, _) do
730 json(conn, info.domain_blocks || [])
731 end
732
733 def block_domain(%{assigns: %{user: blocker}} = conn, %{"domain" => domain}) do
734 User.block_domain(blocker, domain)
735 json(conn, %{})
736 end
737
738 def unblock_domain(%{assigns: %{user: blocker}} = conn, %{"domain" => domain}) do
739 User.unblock_domain(blocker, domain)
740 json(conn, %{})
741 end
742
743 def status_search(user, query) do
744 fetched =
745 if Regex.match?(~r/https?:/, query) do
746 with {:ok, object} <- ActivityPub.fetch_object_from_id(query),
747 %Activity{} = activity <-
748 Activity.get_create_activity_by_object_ap_id(object.data["id"]),
749 true <- ActivityPub.visible_for_user?(activity, user) do
750 [activity]
751 else
752 _e -> []
753 end
754 end || []
755
756 q =
757 from(
758 a in Activity,
759 where: fragment("?->>'type' = 'Create'", a.data),
760 where: "https://www.w3.org/ns/activitystreams#Public" in a.recipients,
761 where:
762 fragment(
763 "to_tsvector('english', ?->'object'->>'content') @@ plainto_tsquery('english', ?)",
764 a.data,
765 ^query
766 ),
767 limit: 20,
768 order_by: [desc: :id]
769 )
770
771 Repo.all(q) ++ fetched
772 end
773
774 def search2(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
775 accounts = User.search(query, params["resolve"] == "true")
776
777 statuses = status_search(user, query)
778
779 tags_path = Web.base_url() <> "/tag/"
780
781 tags =
782 String.split(query)
783 |> Enum.uniq()
784 |> Enum.filter(fn tag -> String.starts_with?(tag, "#") end)
785 |> Enum.map(fn tag -> String.slice(tag, 1..-1) end)
786 |> Enum.map(fn tag -> %{name: tag, url: tags_path <> tag} end)
787
788 res = %{
789 "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
790 "statuses" =>
791 StatusView.render("index.json", activities: statuses, for: user, as: :activity),
792 "hashtags" => tags
793 }
794
795 json(conn, res)
796 end
797
798 def search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
799 accounts = User.search(query, params["resolve"] == "true")
800
801 statuses = status_search(user, query)
802
803 tags =
804 String.split(query)
805 |> Enum.uniq()
806 |> Enum.filter(fn tag -> String.starts_with?(tag, "#") end)
807 |> Enum.map(fn tag -> String.slice(tag, 1..-1) end)
808
809 res = %{
810 "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
811 "statuses" =>
812 StatusView.render("index.json", activities: statuses, for: user, as: :activity),
813 "hashtags" => tags
814 }
815
816 json(conn, res)
817 end
818
819 def account_search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
820 accounts = User.search(query, params["resolve"] == "true")
821
822 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
823
824 json(conn, res)
825 end
826
827 def favourites(%{assigns: %{user: user}} = conn, _) do
828 params =
829 %{}
830 |> Map.put("type", "Create")
831 |> Map.put("favorited_by", user.ap_id)
832 |> Map.put("blocking_user", user)
833
834 activities =
835 ActivityPub.fetch_public_activities(params)
836 |> Enum.reverse()
837
838 conn
839 |> put_view(StatusView)
840 |> render("index.json", %{activities: activities, for: user, as: :activity})
841 end
842
843 def get_lists(%{assigns: %{user: user}} = conn, opts) do
844 lists = Pleroma.List.for_user(user, opts)
845 res = ListView.render("lists.json", lists: lists)
846 json(conn, res)
847 end
848
849 def get_list(%{assigns: %{user: user}} = conn, %{"id" => id}) do
850 with %Pleroma.List{} = list <- Pleroma.List.get(id, user) do
851 res = ListView.render("list.json", list: list)
852 json(conn, res)
853 else
854 _e -> json(conn, "error")
855 end
856 end
857
858 def account_lists(%{assigns: %{user: user}} = conn, %{"id" => account_id}) do
859 lists = Pleroma.List.get_lists_account_belongs(user, account_id)
860 res = ListView.render("lists.json", lists: lists)
861 json(conn, res)
862 end
863
864 def delete_list(%{assigns: %{user: user}} = conn, %{"id" => id}) do
865 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
866 {:ok, _list} <- Pleroma.List.delete(list) do
867 json(conn, %{})
868 else
869 _e ->
870 json(conn, "error")
871 end
872 end
873
874 def create_list(%{assigns: %{user: user}} = conn, %{"title" => title}) do
875 with {:ok, %Pleroma.List{} = list} <- Pleroma.List.create(title, user) do
876 res = ListView.render("list.json", list: list)
877 json(conn, res)
878 end
879 end
880
881 def add_to_list(%{assigns: %{user: user}} = conn, %{"id" => id, "account_ids" => accounts}) do
882 accounts
883 |> Enum.each(fn account_id ->
884 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
885 %User{} = followed <- Repo.get(User, account_id) do
886 Pleroma.List.follow(list, followed)
887 end
888 end)
889
890 json(conn, %{})
891 end
892
893 def remove_from_list(%{assigns: %{user: user}} = conn, %{"id" => id, "account_ids" => accounts}) do
894 accounts
895 |> Enum.each(fn account_id ->
896 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
897 %User{} = followed <- Repo.get(Pleroma.User, account_id) do
898 Pleroma.List.unfollow(list, followed)
899 end
900 end)
901
902 json(conn, %{})
903 end
904
905 def list_accounts(%{assigns: %{user: user}} = conn, %{"id" => id}) do
906 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
907 {:ok, users} = Pleroma.List.get_following(list) do
908 conn
909 |> put_view(AccountView)
910 |> render("accounts.json", %{users: users, as: :user})
911 end
912 end
913
914 def rename_list(%{assigns: %{user: user}} = conn, %{"id" => id, "title" => title}) do
915 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
916 {:ok, list} <- Pleroma.List.rename(list, title) do
917 res = ListView.render("list.json", list: list)
918 json(conn, res)
919 else
920 _e ->
921 json(conn, "error")
922 end
923 end
924
925 def list_timeline(%{assigns: %{user: user}} = conn, %{"list_id" => id} = params) do
926 with %Pleroma.List{title: _title, following: following} <- Pleroma.List.get(id, user) do
927 params =
928 params
929 |> Map.put("type", "Create")
930 |> Map.put("blocking_user", user)
931
932 # we must filter the following list for the user to avoid leaking statuses the user
933 # does not actually have permission to see (for more info, peruse security issue #270).
934 following_to =
935 following
936 |> Enum.filter(fn x -> x in user.following end)
937
938 activities =
939 ActivityPub.fetch_activities_bounded(following_to, following, params)
940 |> Enum.reverse()
941
942 conn
943 |> put_view(StatusView)
944 |> render("index.json", %{activities: activities, for: user, as: :activity})
945 else
946 _e ->
947 conn
948 |> put_status(403)
949 |> json(%{error: "Error."})
950 end
951 end
952
953 def index(%{assigns: %{user: user}} = conn, _params) do
954 token =
955 conn
956 |> get_session(:oauth_token)
957
958 if user && token do
959 mastodon_emoji = mastodonized_emoji()
960
961 limit = Pleroma.Config.get([:instance, :limit])
962
963 accounts =
964 Map.put(%{}, user.id, AccountView.render("account.json", %{user: user, for: user}))
965
966 initial_state =
967 %{
968 meta: %{
969 streaming_api_base_url:
970 String.replace(Pleroma.Web.Endpoint.static_url(), "http", "ws"),
971 access_token: token,
972 locale: "en",
973 domain: Pleroma.Web.Endpoint.host(),
974 admin: "1",
975 me: "#{user.id}",
976 unfollow_modal: false,
977 boost_modal: false,
978 delete_modal: true,
979 auto_play_gif: false,
980 display_sensitive_media: false,
981 reduce_motion: false,
982 max_toot_chars: limit
983 },
984 rights: %{
985 delete_others_notice: !!user.info.is_moderator,
986 admin: !!user.info.is_admin
987 },
988 compose: %{
989 me: "#{user.id}",
990 default_privacy: user.info.default_scope,
991 default_sensitive: false
992 },
993 media_attachments: %{
994 accept_content_types: [
995 ".jpg",
996 ".jpeg",
997 ".png",
998 ".gif",
999 ".webm",
1000 ".mp4",
1001 ".m4v",
1002 "image\/jpeg",
1003 "image\/png",
1004 "image\/gif",
1005 "video\/webm",
1006 "video\/mp4"
1007 ]
1008 },
1009 settings:
1010 user.info.settings ||
1011 %{
1012 onboarded: true,
1013 home: %{
1014 shows: %{
1015 reblog: true,
1016 reply: true
1017 }
1018 },
1019 notifications: %{
1020 alerts: %{
1021 follow: true,
1022 favourite: true,
1023 reblog: true,
1024 mention: true
1025 },
1026 shows: %{
1027 follow: true,
1028 favourite: true,
1029 reblog: true,
1030 mention: true
1031 },
1032 sounds: %{
1033 follow: true,
1034 favourite: true,
1035 reblog: true,
1036 mention: true
1037 }
1038 }
1039 },
1040 push_subscription: nil,
1041 accounts: accounts,
1042 custom_emojis: mastodon_emoji,
1043 char_limit: limit
1044 }
1045 |> Jason.encode!()
1046
1047 conn
1048 |> put_layout(false)
1049 |> put_view(MastodonView)
1050 |> render("index.html", %{initial_state: initial_state})
1051 else
1052 conn
1053 |> redirect(to: "/web/login")
1054 end
1055 end
1056
1057 def put_settings(%{assigns: %{user: user}} = conn, %{"data" => settings} = _params) do
1058 info_cng = User.Info.mastodon_settings_update(user.info, settings)
1059
1060 with changeset <- Ecto.Changeset.change(user),
1061 changeset <- Ecto.Changeset.put_embed(changeset, :info, info_cng),
1062 {:ok, _user} <- User.update_and_set_cache(changeset) do
1063 json(conn, %{})
1064 else
1065 e ->
1066 conn
1067 |> put_resp_content_type("application/json")
1068 |> send_resp(500, Jason.encode!(%{"error" => inspect(e)}))
1069 end
1070 end
1071
1072 def login(conn, %{"code" => code}) do
1073 with {:ok, app} <- get_or_make_app(),
1074 %Authorization{} = auth <- Repo.get_by(Authorization, token: code, app_id: app.id),
1075 {:ok, token} <- Token.exchange_token(app, auth) do
1076 conn
1077 |> put_session(:oauth_token, token.token)
1078 |> redirect(to: "/web/getting-started")
1079 end
1080 end
1081
1082 def login(conn, _) do
1083 with {:ok, app} <- get_or_make_app() do
1084 path =
1085 o_auth_path(conn, :authorize,
1086 response_type: "code",
1087 client_id: app.client_id,
1088 redirect_uri: ".",
1089 scope: app.scopes
1090 )
1091
1092 conn
1093 |> redirect(to: path)
1094 end
1095 end
1096
1097 defp get_or_make_app() do
1098 with %App{} = app <- Repo.get_by(App, client_name: "Mastodon-Local") do
1099 {:ok, app}
1100 else
1101 _e ->
1102 cs =
1103 App.register_changeset(%App{}, %{
1104 client_name: "Mastodon-Local",
1105 redirect_uris: ".",
1106 scopes: "read,write,follow"
1107 })
1108
1109 Repo.insert(cs)
1110 end
1111 end
1112
1113 def logout(conn, _) do
1114 conn
1115 |> clear_session
1116 |> redirect(to: "/")
1117 end
1118
1119 def relationship_noop(%{assigns: %{user: user}} = conn, %{"id" => id}) do
1120 Logger.debug("Unimplemented, returning unmodified relationship")
1121
1122 with %User{} = target <- Repo.get(User, id) do
1123 conn
1124 |> put_view(AccountView)
1125 |> render("relationship.json", %{user: user, target: target})
1126 end
1127 end
1128
1129 def empty_array(conn, _) do
1130 Logger.debug("Unimplemented, returning an empty array")
1131 json(conn, [])
1132 end
1133
1134 def empty_object(conn, _) do
1135 Logger.debug("Unimplemented, returning an empty object")
1136 json(conn, %{})
1137 end
1138
1139 def render_notification(user, %{id: id, activity: activity, inserted_at: created_at} = _params) do
1140 actor = User.get_cached_by_ap_id(activity.data["actor"])
1141 parent_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
1142 mastodon_type = Activity.mastodon_notification_type(activity)
1143
1144 response = %{
1145 id: to_string(id),
1146 type: mastodon_type,
1147 created_at: CommonAPI.Utils.to_masto_date(created_at),
1148 account: AccountView.render("account.json", %{user: actor, for: user})
1149 }
1150
1151 case mastodon_type do
1152 "mention" ->
1153 response
1154 |> Map.merge(%{
1155 status: StatusView.render("status.json", %{activity: activity, for: user})
1156 })
1157
1158 "favourite" ->
1159 response
1160 |> Map.merge(%{
1161 status: StatusView.render("status.json", %{activity: parent_activity, for: user})
1162 })
1163
1164 "reblog" ->
1165 response
1166 |> Map.merge(%{
1167 status: StatusView.render("status.json", %{activity: parent_activity, for: user})
1168 })
1169
1170 "follow" ->
1171 response
1172
1173 _ ->
1174 nil
1175 end
1176 end
1177
1178 def get_filters(%{assigns: %{user: user}} = conn, _) do
1179 filters = Pleroma.Filter.get_filters(user)
1180 res = FilterView.render("filters.json", filters: filters)
1181 json(conn, res)
1182 end
1183
1184 def create_filter(
1185 %{assigns: %{user: user}} = conn,
1186 %{"phrase" => phrase, "context" => context} = params
1187 ) do
1188 query = %Pleroma.Filter{
1189 user_id: user.id,
1190 phrase: phrase,
1191 context: context,
1192 hide: Map.get(params, "irreversible", nil),
1193 whole_word: Map.get(params, "boolean", true)
1194 # expires_at
1195 }
1196
1197 {:ok, response} = Pleroma.Filter.create(query)
1198 res = FilterView.render("filter.json", filter: response)
1199 json(conn, res)
1200 end
1201
1202 def get_filter(%{assigns: %{user: user}} = conn, %{"id" => filter_id}) do
1203 filter = Pleroma.Filter.get(filter_id, user)
1204 res = FilterView.render("filter.json", filter: filter)
1205 json(conn, res)
1206 end
1207
1208 def update_filter(
1209 %{assigns: %{user: user}} = conn,
1210 %{"phrase" => phrase, "context" => context, "id" => filter_id} = params
1211 ) do
1212 query = %Pleroma.Filter{
1213 user_id: user.id,
1214 filter_id: filter_id,
1215 phrase: phrase,
1216 context: context,
1217 hide: Map.get(params, "irreversible", nil),
1218 whole_word: Map.get(params, "boolean", true)
1219 # expires_at
1220 }
1221
1222 {:ok, response} = Pleroma.Filter.update(query)
1223 res = FilterView.render("filter.json", filter: response)
1224 json(conn, res)
1225 end
1226
1227 def delete_filter(%{assigns: %{user: user}} = conn, %{"id" => filter_id}) do
1228 query = %Pleroma.Filter{
1229 user_id: user.id,
1230 filter_id: filter_id
1231 }
1232
1233 {:ok, _} = Pleroma.Filter.delete(query)
1234 json(conn, %{})
1235 end
1236
1237 def create_push_subscription(%{assigns: %{user: user, token: token}} = conn, params) do
1238 true = Pleroma.Web.Push.enabled()
1239 Pleroma.Web.Push.Subscription.delete_if_exists(user, token)
1240 {:ok, subscription} = Pleroma.Web.Push.Subscription.create(user, token, params)
1241 view = PushSubscriptionView.render("push_subscription.json", subscription: subscription)
1242 json(conn, view)
1243 end
1244
1245 def get_push_subscription(%{assigns: %{user: user, token: token}} = conn, _params) do
1246 true = Pleroma.Web.Push.enabled()
1247 subscription = Pleroma.Web.Push.Subscription.get(user, token)
1248 view = PushSubscriptionView.render("push_subscription.json", subscription: subscription)
1249 json(conn, view)
1250 end
1251
1252 def update_push_subscription(
1253 %{assigns: %{user: user, token: token}} = conn,
1254 params
1255 ) do
1256 true = Pleroma.Web.Push.enabled()
1257 {:ok, subscription} = Pleroma.Web.Push.Subscription.update(user, token, params)
1258 view = PushSubscriptionView.render("push_subscription.json", subscription: subscription)
1259 json(conn, view)
1260 end
1261
1262 def delete_push_subscription(%{assigns: %{user: user, token: token}} = conn, _params) do
1263 true = Pleroma.Web.Push.enabled()
1264 {:ok, _response} = Pleroma.Web.Push.Subscription.delete(user, token)
1265 json(conn, %{})
1266 end
1267
1268 def errors(conn, _) do
1269 conn
1270 |> put_status(500)
1271 |> json("Something went wrong")
1272 end
1273
1274 def suggestions(%{assigns: %{user: user}} = conn, _) do
1275 suggestions = Pleroma.Config.get(:suggestions)
1276
1277 if Keyword.get(suggestions, :enabled, false) do
1278 api = Keyword.get(suggestions, :third_party_engine, "")
1279 timeout = Keyword.get(suggestions, :timeout, 5000)
1280 limit = Keyword.get(suggestions, :limit, 23)
1281
1282 host = Pleroma.Config.get([Pleroma.Web.Endpoint, :url, :host])
1283
1284 user = user.nickname
1285 url = String.replace(api, "{{host}}", host) |> String.replace("{{user}}", user)
1286
1287 with {:ok, %{status: 200, body: body}} <-
1288 @httpoison.get(
1289 url,
1290 [],
1291 adapter: [
1292 timeout: timeout,
1293 recv_timeout: timeout
1294 ]
1295 ),
1296 {:ok, data} <- Jason.decode(body) do
1297 data2 =
1298 Enum.slice(data, 0, limit)
1299 |> Enum.map(fn x ->
1300 Map.put(
1301 x,
1302 "id",
1303 case User.get_or_fetch(x["acct"]) do
1304 %{id: id} -> id
1305 _ -> 0
1306 end
1307 )
1308 end)
1309 |> Enum.map(fn x ->
1310 Map.put(x, "avatar", MediaProxy.url(x["avatar"]))
1311 end)
1312 |> Enum.map(fn x ->
1313 Map.put(x, "avatar_static", MediaProxy.url(x["avatar_static"]))
1314 end)
1315
1316 conn
1317 |> json(data2)
1318 else
1319 e -> Logger.error("Could not retrieve suggestions at fetch #{url}, #{inspect(e)}")
1320 end
1321 else
1322 json(conn, [])
1323 end
1324 end
1325
1326 def try_render(conn, target, params)
1327 when is_binary(target) do
1328 res = render(conn, target, params)
1329
1330 if res == nil do
1331 conn
1332 |> put_status(501)
1333 |> json(%{error: "Can't display this activity"})
1334 else
1335 res
1336 end
1337 end
1338
1339 def try_render(conn, _, _) do
1340 conn
1341 |> put_status(501)
1342 |> json(%{error: "Can't display this activity"})
1343 end
1344 end