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_requests(%{assigns: %{user: followed}} = conn, _params) do
480 with {:ok, follow_requests} <- User.get_follow_requests(followed) do
481 render(conn, AccountView, "accounts.json", %{users: follow_requests, as: :user})
485 def follow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
486 with %User{} = followed <- Repo.get(User, id),
487 {:ok, follower} <- User.maybe_direct_follow(follower, followed),
488 {:ok, _activity} <- ActivityPub.follow(follower, followed) do
489 render(conn, AccountView, "relationship.json", %{user: follower, target: followed})
493 |> put_resp_content_type("application/json")
494 |> send_resp(403, Jason.encode!(%{"error" => message}))
498 def follow(%{assigns: %{user: follower}} = conn, %{"uri" => uri}) do
499 with %User{} = followed <- Repo.get_by(User, nickname: uri),
500 {:ok, follower} <- User.maybe_direct_follow(follower, followed),
501 {:ok, _activity} <- ActivityPub.follow(follower, followed) do
502 render(conn, AccountView, "account.json", %{user: followed})
506 |> put_resp_content_type("application/json")
507 |> send_resp(403, Jason.encode!(%{"error" => message}))
511 def unfollow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
512 with %User{} = followed <- Repo.get(User, id),
513 {:ok, _activity} <- ActivityPub.unfollow(follower, followed),
514 {:ok, follower, _} <- User.unfollow(follower, followed) do
515 render(conn, AccountView, "relationship.json", %{user: follower, target: followed})
519 def block(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
520 with %User{} = blocked <- Repo.get(User, id),
521 {:ok, blocker} <- User.block(blocker, blocked),
522 {:ok, _activity} <- ActivityPub.block(blocker, blocked) do
523 render(conn, AccountView, "relationship.json", %{user: blocker, target: blocked})
527 |> put_resp_content_type("application/json")
528 |> send_resp(403, Jason.encode!(%{"error" => message}))
532 def unblock(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
533 with %User{} = blocked <- Repo.get(User, id),
534 {:ok, blocker} <- User.unblock(blocker, blocked),
535 {:ok, _activity} <- ActivityPub.unblock(blocker, blocked) do
536 render(conn, AccountView, "relationship.json", %{user: blocker, target: blocked})
540 |> put_resp_content_type("application/json")
541 |> send_resp(403, Jason.encode!(%{"error" => message}))
545 # TODO: Use proper query
546 def blocks(%{assigns: %{user: user}} = conn, _) do
547 with blocked_users <- user.info["blocks"] || [],
548 accounts <- Enum.map(blocked_users, fn ap_id -> User.get_cached_by_ap_id(ap_id) end) do
549 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
554 def domain_blocks(%{assigns: %{user: %{info: info}}} = conn, _) do
555 json(conn, info["domain_blocks"] || [])
558 def block_domain(%{assigns: %{user: blocker}} = conn, %{"domain" => domain}) do
559 User.block_domain(blocker, domain)
563 def unblock_domain(%{assigns: %{user: blocker}} = conn, %{"domain" => domain}) do
564 User.unblock_domain(blocker, domain)
568 def search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
569 accounts = User.search(query, params["resolve"] == "true")
572 if Regex.match?(~r/https?:/, query) do
573 with {:ok, activities} <- OStatus.fetch_activity_from_url(query) do
576 %{data: %{"type" => "Create"}} -> true
587 where: fragment("?->>'type' = 'Create'", a.data),
588 where: "https://www.w3.org/ns/activitystreams#Public" in a.recipients,
591 "to_tsvector('english', ?->'object'->>'content') @@ plainto_tsquery('english', ?)",
596 order_by: [desc: :id]
599 statuses = Repo.all(q) ++ fetched
604 |> Enum.filter(fn tag -> String.starts_with?(tag, "#") end)
605 |> Enum.map(fn tag -> String.slice(tag, 1..-1) end)
608 "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
610 StatusView.render("index.json", activities: statuses, for: user, as: :activity),
617 def account_search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
618 accounts = User.search(query, params["resolve"] == "true")
620 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
625 def favourites(%{assigns: %{user: user}} = conn, _) do
628 |> Map.put("type", "Create")
629 |> Map.put("favorited_by", user.ap_id)
630 |> Map.put("blocking_user", user)
633 ActivityPub.fetch_public_activities(params)
637 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
640 def get_lists(%{assigns: %{user: user}} = conn, opts) do
641 lists = Pleroma.List.for_user(user, opts)
642 res = ListView.render("lists.json", lists: lists)
646 def get_list(%{assigns: %{user: user}} = conn, %{"id" => id}) do
647 with %Pleroma.List{} = list <- Pleroma.List.get(id, user) do
648 res = ListView.render("list.json", list: list)
651 _e -> json(conn, "error")
655 def delete_list(%{assigns: %{user: user}} = conn, %{"id" => id}) do
656 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
657 {:ok, _list} <- Pleroma.List.delete(list) do
665 def create_list(%{assigns: %{user: user}} = conn, %{"title" => title}) do
666 with {:ok, %Pleroma.List{} = list} <- Pleroma.List.create(title, user) do
667 res = ListView.render("list.json", list: list)
672 def add_to_list(%{assigns: %{user: user}} = conn, %{"id" => id, "account_ids" => accounts}) do
674 |> Enum.each(fn account_id ->
675 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
676 %User{} = followed <- Repo.get(User, account_id) do
677 Pleroma.List.follow(list, followed)
684 def remove_from_list(%{assigns: %{user: user}} = conn, %{"id" => id, "account_ids" => accounts}) do
686 |> Enum.each(fn account_id ->
687 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
688 %User{} = followed <- Repo.get(Pleroma.User, account_id) do
689 Pleroma.List.unfollow(list, followed)
696 def list_accounts(%{assigns: %{user: user}} = conn, %{"id" => id}) do
697 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
698 {:ok, users} = Pleroma.List.get_following(list) do
699 render(conn, AccountView, "accounts.json", %{users: users, as: :user})
703 def rename_list(%{assigns: %{user: user}} = conn, %{"id" => id, "title" => title}) do
704 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
705 {:ok, list} <- Pleroma.List.rename(list, title) do
706 res = ListView.render("list.json", list: list)
714 def list_timeline(%{assigns: %{user: user}} = conn, %{"list_id" => id} = params) do
715 with %Pleroma.List{title: title, following: following} <- Pleroma.List.get(id, user) do
718 |> Map.put("type", "Create")
719 |> Map.put("blocking_user", user)
721 # adding title is a hack to not make empty lists function like a public timeline
723 ActivityPub.fetch_activities([title | following], params)
727 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
732 |> json(%{error: "Error."})
736 def index(%{assigns: %{user: user}} = conn, _params) do
739 |> get_session(:oauth_token)
742 mastodon_emoji = mastodonized_emoji()
743 accounts = Map.put(%{}, user.id, AccountView.render("account.json", %{user: user}))
748 streaming_api_base_url:
749 String.replace(Pleroma.Web.Endpoint.static_url(), "http", "ws"),
752 domain: Pleroma.Web.Endpoint.host(),
755 unfollow_modal: false,
758 auto_play_gif: false,
763 default_privacy: "public",
764 default_sensitive: false
766 media_attachments: %{
767 accept_content_types: [
783 Map.get(user.info, "settings") ||
813 push_subscription: nil,
815 custom_emojis: mastodon_emoji,
816 char_limit: Keyword.get(@instance, :limit)
822 |> render(MastodonView, "index.html", %{initial_state: initial_state})
825 |> redirect(to: "/web/login")
829 def put_settings(%{assigns: %{user: user}} = conn, %{"data" => settings} = _params) do
830 with new_info <- Map.put(user.info, "settings", settings),
831 change <- User.info_changeset(user, %{info: new_info}),
832 {:ok, _user} <- User.update_and_set_cache(change) do
838 |> json(%{error: inspect(e)})
842 def login(conn, _) do
844 |> render(MastodonView, "login.html", %{error: false})
847 defp get_or_make_app() do
848 with %App{} = app <- Repo.get_by(App, client_name: "Mastodon-Local") do
853 App.register_changeset(%App{}, %{
854 client_name: "Mastodon-Local",
856 scopes: "read,write,follow"
863 def login_post(conn, %{"authorization" => %{"name" => name, "password" => password}}) do
864 with %User{} = user <- User.get_by_nickname_or_email(name),
865 true <- Pbkdf2.checkpw(password, user.password_hash),
866 {:ok, app} <- get_or_make_app(),
867 {:ok, auth} <- Authorization.create_authorization(app, user),
868 {:ok, token} <- Token.exchange_token(app, auth) do
870 |> put_session(:oauth_token, token.token)
871 |> redirect(to: "/web/getting-started")
875 |> render(MastodonView, "login.html", %{error: "Wrong username or password"})
879 def logout(conn, _) do
885 def relationship_noop(%{assigns: %{user: user}} = conn, %{"id" => id}) do
886 Logger.debug("Unimplemented, returning unmodified relationship")
888 with %User{} = target <- Repo.get(User, id) do
889 render(conn, AccountView, "relationship.json", %{user: user, target: target})
893 def empty_array(conn, _) do
894 Logger.debug("Unimplemented, returning an empty array")
898 def empty_object(conn, _) do
899 Logger.debug("Unimplemented, returning an empty object")
903 def render_notification(user, %{id: id, activity: activity, inserted_at: created_at} = _params) do
904 actor = User.get_cached_by_ap_id(activity.data["actor"])
907 NaiveDateTime.to_iso8601(created_at)
908 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
910 case activity.data["type"] do
915 created_at: created_at,
916 account: AccountView.render("account.json", %{user: actor}),
917 status: StatusView.render("status.json", %{activity: activity, for: user})
921 liked_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
926 created_at: created_at,
927 account: AccountView.render("account.json", %{user: actor}),
928 status: StatusView.render("status.json", %{activity: liked_activity, for: user})
932 announced_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
937 created_at: created_at,
938 account: AccountView.render("account.json", %{user: actor}),
939 status: StatusView.render("status.json", %{activity: announced_activity, for: user})
946 created_at: created_at,
947 account: AccountView.render("account.json", %{user: actor})
955 def errors(conn, _) do
958 |> json("Something went wrong")