1 defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do
2 use Pleroma.Web, :controller
3 alias Pleroma.{Repo, Activity, User, Notification, Stats}
5 alias Pleroma.Web.MastodonAPI.{StatusView, AccountView, MastodonView, ListView}
6 alias Pleroma.Web.ActivityPub.ActivityPub
7 alias Pleroma.Web.{CommonAPI, OStatus}
8 alias Pleroma.Web.OAuth.{Authorization, Token, App}
13 action_fallback(:errors)
15 def create_app(conn, params) do
16 with cs <- App.register_changeset(%App{}, params) |> IO.inspect(),
17 {:ok, app} <- Repo.insert(cs) |> IO.inspect() do
20 client_id: app.client_id,
21 client_secret: app.client_secret
28 def update_credentials(%{assigns: %{user: user}} = conn, params) do
32 if bio = params["note"] do
33 Map.put(params, "bio", bio)
39 if name = params["display_name"] do
40 Map.put(params, "name", name)
46 if avatar = params["avatar"] do
47 with %Plug.Upload{} <- avatar,
48 {:ok, object} <- ActivityPub.upload(avatar),
49 change = Ecto.Changeset.change(user, %{avatar: object.data}),
50 {:ok, user} = User.update_and_set_cache(change) do
60 if banner = params["header"] do
61 with %Plug.Upload{} <- banner,
62 {:ok, object} <- ActivityPub.upload(banner),
63 new_info <- Map.put(user.info, "banner", object.data),
64 change <- User.info_changeset(user, %{info: new_info}),
65 {:ok, user} <- User.update_and_set_cache(change) do
74 with changeset <- User.update_changeset(user, params),
75 {:ok, user} <- User.update_and_set_cache(changeset) do
76 if original_user != user do
77 CommonAPI.update(user)
80 json(conn, AccountView.render("account.json", %{user: user}))
85 |> json(%{error: "Invalid request"})
89 def verify_credentials(%{assigns: %{user: user}} = conn, _) do
90 account = AccountView.render("account.json", %{user: user})
94 def user(conn, %{"id" => id}) do
95 with %User{} = user <- Repo.get(User, id) do
96 account = AccountView.render("account.json", %{user: user})
102 |> json(%{error: "Can't find user"})
106 @instance Application.get_env(:pleroma, :instance)
107 @mastodon_api_level "2.3.3"
109 def masto_instance(conn, _params) do
112 title: Keyword.get(@instance, :name),
113 description: "A Pleroma instance, an alternative fediverse server",
114 version: "#{@mastodon_api_level} (compatible; #{Keyword.get(@instance, :version)})",
115 email: Keyword.get(@instance, :email),
117 streaming_api: String.replace(Pleroma.Web.Endpoint.static_url(), "http", "ws")
119 stats: Stats.get_stats(),
120 thumbnail: Web.base_url() <> "/instance/thumbnail.jpeg",
121 max_toot_chars: Keyword.get(@instance, :limit)
127 def peers(conn, _params) do
128 json(conn, Stats.get_peers())
131 defp mastodonized_emoji do
132 Pleroma.Formatter.get_custom_emoji()
133 |> Enum.map(fn {shortcode, relative_url} ->
134 url = to_string(URI.merge(Web.base_url(), relative_url))
137 "shortcode" => shortcode,
139 "visible_in_picker" => true,
145 def custom_emojis(conn, _params) do
146 mastodon_emoji = mastodonized_emoji()
147 json(conn, mastodon_emoji)
150 defp add_link_headers(conn, method, activities, param \\ nil, params \\ %{}) do
151 last = List.last(activities)
152 first = List.first(activities)
158 {next_url, prev_url} =
162 Pleroma.Web.Endpoint,
165 Map.merge(params, %{max_id: min})
168 Pleroma.Web.Endpoint,
171 Map.merge(params, %{since_id: max})
177 Pleroma.Web.Endpoint,
179 Map.merge(params, %{max_id: min})
182 Pleroma.Web.Endpoint,
184 Map.merge(params, %{since_id: max})
190 |> put_resp_header("link", "<#{next_url}>; rel=\"next\", <#{prev_url}>; rel=\"prev\"")
196 def home_timeline(%{assigns: %{user: user}} = conn, params) do
199 |> Map.put("type", ["Create", "Announce"])
200 |> Map.put("blocking_user", user)
201 |> Map.put("user", user)
204 ActivityPub.fetch_activities([user.ap_id | user.following], params)
208 |> add_link_headers(:home_timeline, activities)
209 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
212 def public_timeline(%{assigns: %{user: user}} = conn, params) do
213 local_only = params["local"] in [true, "True", "true", "1"]
217 |> Map.put("type", ["Create", "Announce"])
218 |> Map.put("local_only", local_only)
219 |> Map.put("blocking_user", user)
222 ActivityPub.fetch_public_activities(params)
226 |> add_link_headers(:public_timeline, activities, false, %{"local" => local_only})
227 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
230 def user_statuses(%{assigns: %{user: reading_user}} = conn, params) do
231 with %User{} = user <- Repo.get(User, params["id"]) do
232 # Since Pleroma has no "pinned" posts feature, we'll just set an empty list here
234 if params["pinned"] == "true" do
237 ActivityPub.fetch_user_activities(user, reading_user, params)
241 |> add_link_headers(:user_statuses, activities, params["id"])
242 |> render(StatusView, "index.json", %{
243 activities: activities,
250 def dm_timeline(%{assigns: %{user: user}} = conn, _params) do
252 ActivityPub.fetch_activities_query([user.ap_id], %{"type" => "Create", visibility: "direct"})
254 activities = Repo.all(query)
257 |> add_link_headers(:dm_timeline, activities)
258 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
261 def get_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
262 with %Activity{} = activity <- Repo.get(Activity, id),
263 true <- ActivityPub.visible_for_user?(activity, user) do
264 render(conn, StatusView, "status.json", %{activity: activity, for: user})
268 def get_context(%{assigns: %{user: user}} = conn, %{"id" => id}) do
269 with %Activity{} = activity <- Repo.get(Activity, id),
271 ActivityPub.fetch_activities_for_context(activity.data["context"], %{
272 "blocking_user" => user,
276 activities |> Enum.filter(fn %{id: aid} -> to_string(aid) != to_string(id) end),
278 activities |> Enum.filter(fn %{data: %{"type" => type}} -> type == "Create" end),
279 grouped_activities <- Enum.group_by(activities, fn %{id: id} -> id < activity.id end) do
285 activities: grouped_activities[true] || [],
293 activities: grouped_activities[false] || [],
303 def post_status(conn, %{"status" => "", "media_ids" => media_ids} = params)
304 when length(media_ids) > 0 do
307 |> Map.put("status", ".")
309 post_status(conn, params)
312 def post_status(%{assigns: %{user: user}} = conn, %{"status" => _} = params) do
315 |> Map.put("in_reply_to_status_id", params["in_reply_to_id"])
316 |> Map.put("no_attachment_links", true)
319 case get_req_header(conn, "idempotency-key") do
321 _ -> Ecto.UUID.generate()
325 Cachex.fetch!(:idempotency_cache, idempotency_key, fn _ -> CommonAPI.post(user, params) end)
327 render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity})
330 def delete_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
331 with {:ok, %Activity{}} <- CommonAPI.delete(id, user) do
337 |> json(%{error: "Can't delete this post"})
341 def reblog_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
342 with {:ok, announce, _activity} <- CommonAPI.repeat(ap_id_or_id, user) do
343 render(conn, StatusView, "status.json", %{activity: announce, for: user, as: :activity})
347 def unreblog_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
348 with {:ok, _, _, %{data: %{"id" => id}}} <- CommonAPI.unrepeat(ap_id_or_id, user),
349 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
350 render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity})
354 def fav_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
355 with {:ok, _fav, %{data: %{"id" => id}}} <- CommonAPI.favorite(ap_id_or_id, user),
356 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
357 render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity})
361 def unfav_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
362 with {:ok, _, _, %{data: %{"id" => id}}} <- CommonAPI.unfavorite(ap_id_or_id, user),
363 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
364 render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity})
368 def notifications(%{assigns: %{user: user}} = conn, params) do
369 notifications = Notification.for_user(user, params)
372 Enum.map(notifications, fn x ->
373 render_notification(user, x)
378 |> add_link_headers(:notifications, notifications)
382 def get_notification(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
383 with {:ok, notification} <- Notification.get(user, id) do
384 json(conn, render_notification(user, notification))
388 |> put_resp_content_type("application/json")
389 |> send_resp(403, Jason.encode!(%{"error" => reason}))
393 def clear_notifications(%{assigns: %{user: user}} = conn, _params) do
394 Notification.clear(user)
398 def dismiss_notification(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
399 with {:ok, _notif} <- Notification.dismiss(user, id) do
404 |> put_resp_content_type("application/json")
405 |> send_resp(403, Jason.encode!(%{"error" => reason}))
409 def relationships(%{assigns: %{user: user}} = conn, %{"id" => id}) do
411 q = from(u in User, where: u.id in ^id)
412 targets = Repo.all(q)
413 render(conn, AccountView, "relationships.json", %{user: user, targets: targets})
416 def upload(%{assigns: %{user: _}} = conn, %{"file" => file}) do
417 with {:ok, object} <- ActivityPub.upload(file) do
420 |> Map.put("id", object.id)
422 render(conn, StatusView, "attachment.json", %{attachment: data})
426 def favourited_by(conn, %{"id" => id}) do
427 with %Activity{data: %{"object" => %{"likes" => likes}}} <- Repo.get(Activity, id) do
428 q = from(u in User, where: u.ap_id in ^likes)
430 render(conn, AccountView, "accounts.json", %{users: users, as: :user})
436 def reblogged_by(conn, %{"id" => id}) do
437 with %Activity{data: %{"object" => %{"announcements" => announces}}} <- Repo.get(Activity, id) do
438 q = from(u in User, where: u.ap_id in ^announces)
440 render(conn, AccountView, "accounts.json", %{users: users, as: :user})
446 def hashtag_timeline(%{assigns: %{user: user}} = conn, params) do
447 local_only = params["local"] in [true, "True", "true", "1"]
451 |> Map.put("type", "Create")
452 |> Map.put("local_only", local_only)
453 |> Map.put("blocking_user", user)
456 ActivityPub.fetch_public_activities(params)
460 |> add_link_headers(:hashtag_timeline, activities, params["tag"], %{"local" => local_only})
461 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
465 def followers(conn, %{"id" => id}) do
466 with %User{} = user <- Repo.get(User, id),
467 {:ok, followers} <- User.get_followers(user) do
468 render(conn, AccountView, "accounts.json", %{users: followers, as: :user})
472 def following(conn, %{"id" => id}) do
473 with %User{} = user <- Repo.get(User, id),
474 {:ok, followers} <- User.get_friends(user) do
475 render(conn, AccountView, "accounts.json", %{users: followers, as: :user})
479 def follow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
480 with %User{} = followed <- Repo.get(User, id),
481 {:ok, follower} <- User.maybe_direct_follow(follower, followed),
482 {:ok, _activity} <- ActivityPub.follow(follower, followed) do
483 render(conn, AccountView, "relationship.json", %{user: follower, target: followed})
487 |> put_resp_content_type("application/json")
488 |> send_resp(403, Jason.encode!(%{"error" => message}))
492 def follow(%{assigns: %{user: follower}} = conn, %{"uri" => uri}) do
493 with %User{} = followed <- Repo.get_by(User, nickname: uri),
494 {:ok, follower} <- User.maybe_direct_follow(follower, followed),
495 {:ok, _activity} <- ActivityPub.follow(follower, followed) do
496 render(conn, AccountView, "account.json", %{user: followed})
500 |> put_resp_content_type("application/json")
501 |> send_resp(403, Jason.encode!(%{"error" => message}))
505 def unfollow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
506 with %User{} = followed <- Repo.get(User, id),
507 {:ok, _activity} <- ActivityPub.unfollow(follower, followed),
508 {:ok, follower, _} <- User.unfollow(follower, followed) do
509 render(conn, AccountView, "relationship.json", %{user: follower, target: followed})
513 def block(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
514 with %User{} = blocked <- Repo.get(User, id),
515 {:ok, blocker} <- User.block(blocker, blocked),
516 {:ok, _activity} <- ActivityPub.block(blocker, blocked) do
517 render(conn, AccountView, "relationship.json", %{user: blocker, target: blocked})
521 |> put_resp_content_type("application/json")
522 |> send_resp(403, Jason.encode!(%{"error" => message}))
526 def unblock(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
527 with %User{} = blocked <- Repo.get(User, id),
528 {:ok, blocker} <- User.unblock(blocker, blocked),
529 {:ok, _activity} <- ActivityPub.unblock(blocker, blocked) do
530 render(conn, AccountView, "relationship.json", %{user: blocker, target: blocked})
534 |> put_resp_content_type("application/json")
535 |> send_resp(403, Jason.encode!(%{"error" => message}))
539 # TODO: Use proper query
540 def blocks(%{assigns: %{user: user}} = conn, _) do
541 with blocked_users <- user.info["blocks"] || [],
542 accounts <- Enum.map(blocked_users, fn ap_id -> User.get_cached_by_ap_id(ap_id) end) do
543 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
548 def domain_blocks(%{assigns: %{user: %{info: info}}} = conn, _) do
549 json(conn, info["domain_blocks"] || [])
552 def block_domain(%{assigns: %{user: blocker}} = conn, %{"domain" => domain}) do
553 User.block_domain(blocker, domain)
557 def unblock_domain(%{assigns: %{user: blocker}} = conn, %{"domain" => domain}) do
558 User.unblock_domain(blocker, domain)
562 def search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
563 accounts = User.search(query, params["resolve"] == "true")
566 if Regex.match?(~r/https?:/, query) do
567 with {:ok, activities} <- OStatus.fetch_activity_from_url(query) do
570 %{data: %{"type" => "Create"}} -> true
581 where: fragment("?->>'type' = 'Create'", a.data),
582 where: "https://www.w3.org/ns/activitystreams#Public" in a.recipients,
585 "to_tsvector('english', ?->'object'->>'content') @@ plainto_tsquery('english', ?)",
590 order_by: [desc: :id]
593 statuses = Repo.all(q) ++ fetched
598 |> Enum.filter(fn tag -> String.starts_with?(tag, "#") end)
599 |> Enum.map(fn tag -> String.slice(tag, 1..-1) end)
602 "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
604 StatusView.render("index.json", activities: statuses, for: user, as: :activity),
611 def account_search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
612 accounts = User.search(query, params["resolve"] == "true")
614 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
619 def favourites(%{assigns: %{user: user}} = conn, _) do
622 |> Map.put("type", "Create")
623 |> Map.put("favorited_by", user.ap_id)
624 |> Map.put("blocking_user", user)
627 ActivityPub.fetch_public_activities(params)
631 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
634 def get_lists(%{assigns: %{user: user}} = conn, opts) do
635 lists = Pleroma.List.for_user(user, opts)
636 res = ListView.render("lists.json", lists: lists)
640 def get_list(%{assigns: %{user: user}} = conn, %{"id" => id}) do
641 with %Pleroma.List{} = list <- Pleroma.List.get(id, user) do
642 res = ListView.render("list.json", list: list)
645 _e -> json(conn, "error")
649 def delete_list(%{assigns: %{user: user}} = conn, %{"id" => id}) do
650 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
651 {:ok, _list} <- Pleroma.List.delete(list) do
659 def create_list(%{assigns: %{user: user}} = conn, %{"title" => title}) do
660 with {:ok, %Pleroma.List{} = list} <- Pleroma.List.create(title, user) do
661 res = ListView.render("list.json", list: list)
666 def add_to_list(%{assigns: %{user: user}} = conn, %{"id" => id, "account_ids" => accounts}) do
668 |> Enum.each(fn account_id ->
669 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
670 %User{} = followed <- Repo.get(User, account_id) do
671 Pleroma.List.follow(list, followed)
678 def remove_from_list(%{assigns: %{user: user}} = conn, %{"id" => id, "account_ids" => accounts}) do
680 |> Enum.each(fn account_id ->
681 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
682 %User{} = followed <- Repo.get(Pleroma.User, account_id) do
683 Pleroma.List.unfollow(list, followed)
690 def list_accounts(%{assigns: %{user: user}} = conn, %{"id" => id}) do
691 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
692 {:ok, users} = Pleroma.List.get_following(list) do
693 render(conn, AccountView, "accounts.json", %{users: users, as: :user})
697 def rename_list(%{assigns: %{user: user}} = conn, %{"id" => id, "title" => title}) do
698 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
699 {:ok, list} <- Pleroma.List.rename(list, title) do
700 res = ListView.render("list.json", list: list)
708 def list_timeline(%{assigns: %{user: user}} = conn, %{"list_id" => id} = params) do
709 with %Pleroma.List{title: title, following: following} <- Pleroma.List.get(id, user) do
712 |> Map.put("type", "Create")
713 |> Map.put("blocking_user", user)
715 # adding title is a hack to not make empty lists function like a public timeline
717 ActivityPub.fetch_activities([title | following], params)
721 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
726 |> json(%{error: "Error."})
730 def index(%{assigns: %{user: user}} = conn, _params) do
733 |> get_session(:oauth_token)
736 mastodon_emoji = mastodonized_emoji()
737 accounts = Map.put(%{}, user.id, AccountView.render("account.json", %{user: user}))
742 streaming_api_base_url:
743 String.replace(Pleroma.Web.Endpoint.static_url(), "http", "ws"),
746 domain: Pleroma.Web.Endpoint.host(),
749 unfollow_modal: false,
752 auto_play_gif: false,
757 default_privacy: "public",
758 default_sensitive: false
760 media_attachments: %{
761 accept_content_types: [
777 Map.get(user.info, "settings") ||
807 push_subscription: nil,
809 custom_emojis: mastodon_emoji,
810 char_limit: Keyword.get(@instance, :limit)
816 |> render(MastodonView, "index.html", %{initial_state: initial_state})
819 |> redirect(to: "/web/login")
823 def put_settings(%{assigns: %{user: user}} = conn, %{"data" => settings} = _params) do
824 with new_info <- Map.put(user.info, "settings", settings),
825 change <- User.info_changeset(user, %{info: new_info}),
826 {:ok, _user} <- User.update_and_set_cache(change) do
832 |> json(%{error: inspect(e)})
836 def login(conn, _) do
838 |> render(MastodonView, "login.html", %{error: false})
841 defp get_or_make_app() do
842 with %App{} = app <- Repo.get_by(App, client_name: "Mastodon-Local") do
847 App.register_changeset(%App{}, %{
848 client_name: "Mastodon-Local",
850 scopes: "read,write,follow"
857 def login_post(conn, %{"authorization" => %{"name" => name, "password" => password}}) do
858 with %User{} = user <- User.get_by_nickname_or_email(name),
859 true <- Pbkdf2.checkpw(password, user.password_hash),
860 {:ok, app} <- get_or_make_app(),
861 {:ok, auth} <- Authorization.create_authorization(app, user),
862 {:ok, token} <- Token.exchange_token(app, auth) do
864 |> put_session(:oauth_token, token.token)
865 |> redirect(to: "/web/getting-started")
869 |> render(MastodonView, "login.html", %{error: "Wrong username or password"})
873 def logout(conn, _) do
879 def relationship_noop(%{assigns: %{user: user}} = conn, %{"id" => id}) do
880 Logger.debug("Unimplemented, returning unmodified relationship")
882 with %User{} = target <- Repo.get(User, id) do
883 render(conn, AccountView, "relationship.json", %{user: user, target: target})
887 def empty_array(conn, _) do
888 Logger.debug("Unimplemented, returning an empty array")
892 def empty_object(conn, _) do
893 Logger.debug("Unimplemented, returning an empty object")
897 def render_notification(user, %{id: id, activity: activity, inserted_at: created_at} = _params) do
898 actor = User.get_cached_by_ap_id(activity.data["actor"])
901 NaiveDateTime.to_iso8601(created_at)
902 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
904 case activity.data["type"] do
909 created_at: created_at,
910 account: AccountView.render("account.json", %{user: actor}),
911 status: StatusView.render("status.json", %{activity: activity, for: user})
915 liked_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
920 created_at: created_at,
921 account: AccountView.render("account.json", %{user: actor}),
922 status: StatusView.render("status.json", %{activity: liked_activity, for: user})
926 announced_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
931 created_at: created_at,
932 account: AccountView.render("account.json", %{user: actor}),
933 status: StatusView.render("status.json", %{activity: announced_activity, for: user})
940 created_at: created_at,
941 account: AccountView.render("account.json", %{user: actor})
949 def errors(conn, _) do
952 |> json("Something went wrong")