1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do
6 use Pleroma.Web, :controller
7 alias Pleroma.{Repo, Object, Activity, User, Notification, Stats}
11 alias Pleroma.Web.MastodonAPI.{
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
29 @httpoison Application.get_env(:pleroma, :httpoison)
31 action_fallback(:errors)
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
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,
54 value_function \\ fn x -> {:ok, x} end
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)
66 def update_credentials(%{assigns: %{user: user}} = conn, params) do
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
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
94 info_cng = User.Info.mastodon_profile_update(user.info, info_params)
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)
103 json(conn, AccountView.render("account.json", %{user: user, for: user}))
108 |> json(%{error: "Invalid request"})
112 def verify_credentials(%{assigns: %{user: user}} = conn, _) do
113 account = AccountView.render("account.json", %{user: user, for: user})
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})
126 |> json(%{error: "Can't find user"})
130 @mastodon_api_level "2.5.0"
132 def masto_instance(conn, _params) do
133 instance = Pleroma.Config.get(:instance)
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),
142 streaming_api: String.replace(Pleroma.Web.Endpoint.static_url(), "http", "ws")
144 stats: Stats.get_stats(),
145 thumbnail: Web.base_url() <> "/instance/thumbnail.jpeg",
146 max_toot_chars: Keyword.get(instance, :limit)
152 def peers(conn, _params) do
153 json(conn, Stats.get_peers())
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))
162 "shortcode" => shortcode,
164 "visible_in_picker" => true,
170 def custom_emojis(conn, _params) do
171 mastodon_emoji = mastodonized_emoji()
172 json(conn, mastodon_emoji)
175 defp add_link_headers(conn, method, activities, param \\ nil, params \\ %{}) do
176 last = List.last(activities)
177 first = List.first(activities)
183 {next_url, prev_url} =
187 Pleroma.Web.Endpoint,
190 Map.merge(params, %{max_id: min})
193 Pleroma.Web.Endpoint,
196 Map.merge(params, %{since_id: max})
202 Pleroma.Web.Endpoint,
204 Map.merge(params, %{max_id: min})
207 Pleroma.Web.Endpoint,
209 Map.merge(params, %{since_id: max})
215 |> put_resp_header("link", "<#{next_url}>; rel=\"next\", <#{prev_url}>; rel=\"prev\"")
221 def home_timeline(%{assigns: %{user: user}} = conn, params) do
224 |> Map.put("type", ["Create", "Announce"])
225 |> Map.put("blocking_user", user)
226 |> Map.put("user", user)
229 ActivityPub.fetch_activities([user.ap_id | user.following], params)
230 |> ActivityPub.contain_timeline(user)
234 |> add_link_headers(:home_timeline, activities)
235 |> put_view(StatusView)
236 |> render("index.json", %{activities: activities, for: user, as: :activity})
239 def public_timeline(%{assigns: %{user: user}} = conn, params) do
240 local_only = params["local"] in [true, "True", "true", "1"]
244 |> Map.put("type", ["Create", "Announce"])
245 |> Map.put("local_only", local_only)
246 |> Map.put("blocking_user", user)
249 ActivityPub.fetch_public_activities(params)
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})
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)
263 |> add_link_headers(:user_statuses, activities, params["id"])
264 |> put_view(StatusView)
265 |> render("index.json", %{
266 activities: activities,
273 def dm_timeline(%{assigns: %{user: user}} = conn, params) do
275 ActivityPub.fetch_activities_query(
277 Map.merge(params, %{"type" => "Create", visibility: "direct"})
280 activities = Repo.all(query)
283 |> add_link_headers(:dm_timeline, activities)
284 |> put_view(StatusView)
285 |> render("index.json", %{activities: activities, for: user, as: :activity})
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
292 |> put_view(StatusView)
293 |> try_render("status.json", %{activity: activity, for: user})
297 def get_context(%{assigns: %{user: user}} = conn, %{"id" => id}) do
298 with %Activity{} = activity <- Repo.get(Activity, id),
300 ActivityPub.fetch_activities_for_context(activity.data["context"], %{
301 "blocking_user" => user,
305 activities |> Enum.filter(fn %{id: aid} -> to_string(aid) != to_string(id) end),
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
314 activities: grouped_activities[true] || [],
322 activities: grouped_activities[false] || [],
332 def post_status(conn, %{"status" => "", "media_ids" => media_ids} = params)
333 when length(media_ids) > 0 do
336 |> Map.put("status", ".")
338 post_status(conn, params)
341 def post_status(%{assigns: %{user: user}} = conn, %{"status" => _} = params) do
344 |> Map.put("in_reply_to_status_id", params["in_reply_to_id"])
347 case get_req_header(conn, "idempotency-key") do
349 _ -> Ecto.UUID.generate()
353 Cachex.fetch!(:idempotency_cache, idempotency_key, fn _ -> CommonAPI.post(user, params) end)
356 |> put_view(StatusView)
357 |> try_render("status.json", %{activity: activity, for: user, as: :activity})
360 def delete_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
361 with {:ok, %Activity{}} <- CommonAPI.delete(id, user) do
367 |> json(%{error: "Can't delete this post"})
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
374 |> put_view(StatusView)
375 |> try_render("status.json", %{activity: announce, for: user, as: :activity})
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
383 |> put_view(StatusView)
384 |> try_render("status.json", %{activity: activity, for: user, as: :activity})
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
392 |> put_view(StatusView)
393 |> try_render("status.json", %{activity: activity, for: user, as: :activity})
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
401 |> put_view(StatusView)
402 |> try_render("status.json", %{activity: activity, for: user, as: :activity})
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
409 |> put_view(StatusView)
410 |> try_render("status.json", %{activity: activity, for: user, as: :activity})
414 |> put_resp_content_type("application/json")
415 |> send_resp(:bad_request, Jason.encode!(%{"error" => reason}))
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
422 |> put_view(StatusView)
423 |> try_render("status.json", %{activity: activity, for: user, as: :activity})
427 def notifications(%{assigns: %{user: user}} = conn, params) do
428 notifications = Notification.for_user(user, params)
431 Enum.map(notifications, fn x ->
432 render_notification(user, x)
437 |> add_link_headers(:notifications, notifications)
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))
447 |> put_resp_content_type("application/json")
448 |> send_resp(403, Jason.encode!(%{"error" => reason}))
452 def clear_notifications(%{assigns: %{user: user}} = conn, _params) do
453 Notification.clear(user)
457 def dismiss_notification(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
458 with {:ok, _notif} <- Notification.dismiss(user, id) do
463 |> put_resp_content_type("application/json")
464 |> send_resp(403, Jason.encode!(%{"error" => reason}))
468 def relationships(%{assigns: %{user: user}} = conn, %{"id" => id}) do
470 q = from(u in User, where: u.id in ^id)
471 targets = Repo.all(q)
474 |> put_view(AccountView)
475 |> render("relationships.json", %{user: user, targets: targets})
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, [])
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}
490 |> Object.change(%{data: new_data})
493 attachment_data = Map.put(new_data, "id", object.id)
496 |> put_view(StatusView)
497 |> render("attachment.json", %{attachment: attachment_data})
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")
507 attachment_data = Map.put(object.data, "id", object.id)
510 |> put_view(StatusView)
511 |> render("attachment.json", %{attachment: attachment_data})
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)
521 |> put_view(AccountView)
522 |> render(AccountView, "accounts.json", %{users: users, as: :user})
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)
534 |> put_view(AccountView)
535 |> render("accounts.json", %{users: users, as: :user})
541 def hashtag_timeline(%{assigns: %{user: user}} = conn, params) do
542 local_only = params["local"] in [true, "True", "true", "1"]
545 [params["tag"], params["any"]]
549 |> Enum.map(&String.downcase(&1))
554 |> Enum.map(&String.downcase(&1))
559 |> Enum.map(&String.downcase(&1))
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)
571 ActivityPub.fetch_public_activities(query_params)
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})
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
585 for_user && user.id == for_user.id -> followers
586 user.info.hide_network -> []
591 |> put_view(AccountView)
592 |> render("accounts.json", %{users: followers, as: :user})
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
601 for_user && user.id == for_user.id -> followers
602 user.info.hide_network -> []
607 |> put_view(AccountView)
608 |> render("accounts.json", %{users: followers, as: :user})
612 def follow_requests(%{assigns: %{user: followed}} = conn, _params) do
613 with {:ok, follow_requests} <- User.get_follow_requests(followed) do
615 |> put_view(AccountView)
616 |> render("accounts.json", %{users: follow_requests, as: :user})
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"),
626 ActivityPub.accept(%{
627 to: [follower.ap_id],
628 actor: followed.ap_id,
629 object: follow_activity.data["id"],
633 |> put_view(AccountView)
634 |> render("relationship.json", %{user: followed, target: follower})
638 |> put_resp_content_type("application/json")
639 |> send_resp(403, Jason.encode!(%{"error" => message}))
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"),
648 ActivityPub.reject(%{
649 to: [follower.ap_id],
650 actor: followed.ap_id,
651 object: follow_activity.data["id"],
655 |> put_view(AccountView)
656 |> render("relationship.json", %{user: followed, target: follower})
660 |> put_resp_content_type("application/json")
661 |> send_resp(403, Jason.encode!(%{"error" => message}))
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]),
676 |> put_view(AccountView)
677 |> render("relationship.json", %{user: follower, target: followed})
681 |> put_resp_content_type("application/json")
682 |> send_resp(403, Jason.encode!(%{"error" => message}))
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
691 |> put_view(AccountView)
692 |> render("account.json", %{user: followed, for: follower})
696 |> put_resp_content_type("application/json")
697 |> send_resp(403, Jason.encode!(%{"error" => message}))
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
706 |> put_view(AccountView)
707 |> render("relationship.json", %{user: follower, target: followed})
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
716 |> put_view(AccountView)
717 |> render("relationship.json", %{user: blocker, target: blocked})
721 |> put_resp_content_type("application/json")
722 |> send_resp(403, Jason.encode!(%{"error" => message}))
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
731 |> put_view(AccountView)
732 |> render("relationship.json", %{user: blocker, target: blocked})
736 |> put_resp_content_type("application/json")
737 |> send_resp(403, Jason.encode!(%{"error" => message}))
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)
748 def domain_blocks(%{assigns: %{user: %{info: info}}} = conn, _) do
749 json(conn, info.domain_blocks || [])
752 def block_domain(%{assigns: %{user: blocker}} = conn, %{"domain" => domain}) do
753 User.block_domain(blocker, domain)
757 def unblock_domain(%{assigns: %{user: blocker}} = conn, %{"domain" => domain}) do
758 User.unblock_domain(blocker, domain)
762 def status_search(user, query) do
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
777 where: fragment("?->>'type' = 'Create'", a.data),
778 where: "https://www.w3.org/ns/activitystreams#Public" in a.recipients,
781 "to_tsvector('english', ?->'object'->>'content') @@ plainto_tsquery('english', ?)",
786 order_by: [desc: :id]
789 Repo.all(q) ++ fetched
792 def search2(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
793 accounts = User.search(query, params["resolve"] == "true", user)
795 statuses = status_search(user, query)
797 tags_path = Web.base_url() <> "/tag/"
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)
807 "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
809 StatusView.render("index.json", activities: statuses, for: user, as: :activity),
816 def search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
817 accounts = User.search(query, params["resolve"] == "true", user)
819 statuses = status_search(user, query)
824 |> Enum.filter(fn tag -> String.starts_with?(tag, "#") end)
825 |> Enum.map(fn tag -> String.slice(tag, 1..-1) end)
828 "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
830 StatusView.render("index.json", activities: statuses, for: user, as: :activity),
837 def account_search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
838 accounts = User.search(query, params["resolve"] == "true", user)
840 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
845 def favourites(%{assigns: %{user: user}} = conn, params) do
848 |> Map.put("type", "Create")
849 |> Map.put("favorited_by", user.ap_id)
850 |> Map.put("blocking_user", user)
853 ActivityPub.fetch_public_activities(params)
857 |> add_link_headers(:favourites, activities)
858 |> put_view(StatusView)
859 |> render("index.json", %{activities: activities, for: user, as: :activity})
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)
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)
873 _e -> json(conn, "error")
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)
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
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)
900 def add_to_list(%{assigns: %{user: user}} = conn, %{"id" => id, "account_ids" => accounts}) do
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)
912 def remove_from_list(%{assigns: %{user: user}} = conn, %{"id" => id, "account_ids" => accounts}) do
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)
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
928 |> put_view(AccountView)
929 |> render("accounts.json", %{users: users, as: :user})
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)
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
948 |> Map.put("type", "Create")
949 |> Map.put("blocking_user", user)
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).
955 |> Enum.filter(fn x -> x in user.following end)
958 ActivityPub.fetch_activities_bounded(following_to, following, params)
962 |> put_view(StatusView)
963 |> render("index.json", %{activities: activities, for: user, as: :activity})
968 |> json(%{error: "Error."})
972 def index(%{assigns: %{user: user}} = conn, _params) do
975 |> get_session(:oauth_token)
978 mastodon_emoji = mastodonized_emoji()
980 limit = Pleroma.Config.get([:instance, :limit])
983 Map.put(%{}, user.id, AccountView.render("account.json", %{user: user, for: user}))
988 streaming_api_base_url:
989 String.replace(Pleroma.Web.Endpoint.static_url(), "http", "ws"),
992 domain: Pleroma.Web.Endpoint.host(),
995 unfollow_modal: false,
998 auto_play_gif: false,
999 display_sensitive_media: false,
1000 reduce_motion: false,
1001 max_toot_chars: limit
1004 delete_others_notice: !!user.info.is_moderator,
1005 admin: !!user.info.is_admin
1009 default_privacy: user.info.default_scope,
1010 default_sensitive: false
1012 media_attachments: %{
1013 accept_content_types: [
1029 user.info.settings ||
1059 push_subscription: nil,
1061 custom_emojis: mastodon_emoji,
1067 |> put_layout(false)
1068 |> put_view(MastodonView)
1069 |> render("index.html", %{initial_state: initial_state})
1072 |> redirect(to: "/web/login")
1076 def put_settings(%{assigns: %{user: user}} = conn, %{"data" => settings} = _params) do
1077 info_cng = User.Info.mastodon_settings_update(user.info, settings)
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
1086 |> put_resp_content_type("application/json")
1087 |> send_resp(500, Jason.encode!(%{"error" => inspect(e)}))
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
1096 |> put_session(:oauth_token, token.token)
1097 |> redirect(to: "/web/getting-started")
1101 def login(conn, _) do
1102 with {:ok, app} <- get_or_make_app() do
1104 o_auth_path(conn, :authorize,
1105 response_type: "code",
1106 client_id: app.client_id,
1112 |> redirect(to: path)
1116 defp get_or_make_app() do
1117 with %App{} = app <- Repo.get_by(App, client_name: "Mastodon-Local") do
1122 App.register_changeset(%App{}, %{
1123 client_name: "Mastodon-Local",
1125 scopes: "read,write,follow"
1132 def logout(conn, _) do
1135 |> redirect(to: "/")
1138 def relationship_noop(%{assigns: %{user: user}} = conn, %{"id" => id}) do
1139 Logger.debug("Unimplemented, returning unmodified relationship")
1141 with %User{} = target <- Repo.get(User, id) do
1143 |> put_view(AccountView)
1144 |> render("relationship.json", %{user: user, target: target})
1148 def empty_array(conn, _) do
1149 Logger.debug("Unimplemented, returning an empty array")
1153 def empty_object(conn, _) do
1154 Logger.debug("Unimplemented, returning an empty object")
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)
1165 type: mastodon_type,
1166 created_at: CommonAPI.Utils.to_masto_date(created_at),
1167 account: AccountView.render("account.json", %{user: actor, for: user})
1170 case mastodon_type do
1174 status: StatusView.render("status.json", %{activity: activity, for: user})
1180 status: StatusView.render("status.json", %{activity: parent_activity, for: user})
1186 status: StatusView.render("status.json", %{activity: parent_activity, for: user})
1197 def get_filters(%{assigns: %{user: user}} = conn, _) do
1198 filters = Pleroma.Filter.get_filters(user)
1199 res = FilterView.render("filters.json", filters: filters)
1204 %{assigns: %{user: user}} = conn,
1205 %{"phrase" => phrase, "context" => context} = params
1207 query = %Pleroma.Filter{
1211 hide: Map.get(params, "irreversible", nil),
1212 whole_word: Map.get(params, "boolean", true)
1216 {:ok, response} = Pleroma.Filter.create(query)
1217 res = FilterView.render("filter.json", filter: response)
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)
1228 %{assigns: %{user: user}} = conn,
1229 %{"phrase" => phrase, "context" => context, "id" => filter_id} = params
1231 query = %Pleroma.Filter{
1233 filter_id: filter_id,
1236 hide: Map.get(params, "irreversible", nil),
1237 whole_word: Map.get(params, "boolean", true)
1241 {:ok, response} = Pleroma.Filter.update(query)
1242 res = FilterView.render("filter.json", filter: response)
1246 def delete_filter(%{assigns: %{user: user}} = conn, %{"id" => filter_id}) do
1247 query = %Pleroma.Filter{
1249 filter_id: filter_id
1252 {:ok, _} = Pleroma.Filter.delete(query)
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)
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)
1271 def update_push_subscription(
1272 %{assigns: %{user: user, token: token}} = conn,
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)
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)
1287 def errors(conn, _) do
1290 |> json("Something went wrong")
1293 def suggestions(%{assigns: %{user: user}} = conn, _) do
1294 suggestions = Pleroma.Config.get(:suggestions)
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)
1301 host = Pleroma.Config.get([Pleroma.Web.Endpoint, :url, :host])
1303 user = user.nickname
1304 url = String.replace(api, "{{host}}", host) |> String.replace("{{user}}", user)
1306 with {:ok, %{status: 200, body: body}} <-
1312 recv_timeout: timeout
1315 {:ok, data} <- Jason.decode(body) do
1317 Enum.slice(data, 0, limit)
1322 case User.get_or_fetch(x["acct"]) do
1329 Map.put(x, "avatar", MediaProxy.url(x["avatar"]))
1332 Map.put(x, "avatar_static", MediaProxy.url(x["avatar_static"]))
1338 e -> Logger.error("Could not retrieve suggestions at fetch #{url}, #{inspect(e)}")
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
1355 |> Map.take([:image, :title, :description])
1356 |> Map.put(:type, "link")
1357 |> Map.put(:provider_name, site_name)
1358 |> Map.put(:url, page_url)
1364 def status_card(conn, %{"id" => status_id}) do
1365 json(conn, get_status_card(status_id))
1368 def try_render(conn, target, params)
1369 when is_binary(target) do
1370 res = render(conn, target, params)
1375 |> json(%{error: "Can't display this activity"})
1381 def try_render(conn, _, _) do
1384 |> json(%{error: "Can't display this activity"})