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.ActivityPub.Utils
8 alias Pleroma.Web.{CommonAPI, OStatus}
9 alias Pleroma.Web.OAuth.{Authorization, Token, App}
14 action_fallback(:errors)
16 def create_app(conn, params) do
17 with cs <- App.register_changeset(%App{}, params) |> IO.inspect(),
18 {:ok, app} <- Repo.insert(cs) |> IO.inspect() do
21 client_id: app.client_id,
22 client_secret: app.client_secret
29 def update_credentials(%{assigns: %{user: user}} = conn, params) do
33 if bio = params["note"] do
34 Map.put(params, "bio", bio)
40 if name = params["display_name"] do
41 Map.put(params, "name", name)
47 if avatar = params["avatar"] do
48 with %Plug.Upload{} <- avatar,
49 {:ok, object} <- ActivityPub.upload(avatar),
50 change = Ecto.Changeset.change(user, %{avatar: object.data}),
51 {:ok, user} = User.update_and_set_cache(change) do
61 if banner = params["header"] do
62 with %Plug.Upload{} <- banner,
63 {:ok, object} <- ActivityPub.upload(banner),
64 new_info <- Map.put(user.info, "banner", object.data),
65 change <- User.info_changeset(user, %{info: new_info}),
66 {:ok, user} <- User.update_and_set_cache(change) do
75 with changeset <- User.update_changeset(user, params),
76 {:ok, user} <- User.update_and_set_cache(changeset) do
77 if original_user != user do
78 CommonAPI.update(user)
81 json(conn, AccountView.render("account.json", %{user: user}))
86 |> json(%{error: "Invalid request"})
90 def verify_credentials(%{assigns: %{user: user}} = conn, _) do
91 account = AccountView.render("account.json", %{user: user})
95 def user(conn, %{"id" => id}) do
96 with %User{} = user <- Repo.get(User, id) do
97 account = AccountView.render("account.json", %{user: user})
103 |> json(%{error: "Can't find user"})
107 @instance Application.get_env(:pleroma, :instance)
108 @mastodon_api_level "2.3.3"
110 def masto_instance(conn, _params) do
113 title: Keyword.get(@instance, :name),
114 description: "A Pleroma instance, an alternative fediverse server",
115 version: "#{@mastodon_api_level} (compatible; #{Keyword.get(@instance, :version)})",
116 email: Keyword.get(@instance, :email),
118 streaming_api: String.replace(Pleroma.Web.Endpoint.static_url(), "http", "ws")
120 stats: Stats.get_stats(),
121 thumbnail: Web.base_url() <> "/instance/thumbnail.jpeg",
122 max_toot_chars: Keyword.get(@instance, :limit)
128 def peers(conn, _params) do
129 json(conn, Stats.get_peers())
132 defp mastodonized_emoji do
133 Pleroma.Formatter.get_custom_emoji()
134 |> Enum.map(fn {shortcode, relative_url} ->
135 url = to_string(URI.merge(Web.base_url(), relative_url))
138 "shortcode" => shortcode,
140 "visible_in_picker" => true,
146 def custom_emojis(conn, _params) do
147 mastodon_emoji = mastodonized_emoji()
148 json(conn, mastodon_emoji)
151 defp add_link_headers(conn, method, activities, param \\ nil, params \\ %{}) do
152 last = List.last(activities)
153 first = List.first(activities)
159 {next_url, prev_url} =
163 Pleroma.Web.Endpoint,
166 Map.merge(params, %{max_id: min})
169 Pleroma.Web.Endpoint,
172 Map.merge(params, %{since_id: max})
178 Pleroma.Web.Endpoint,
180 Map.merge(params, %{max_id: min})
183 Pleroma.Web.Endpoint,
185 Map.merge(params, %{since_id: max})
191 |> put_resp_header("link", "<#{next_url}>; rel=\"next\", <#{prev_url}>; rel=\"prev\"")
197 def home_timeline(%{assigns: %{user: user}} = conn, params) do
200 |> Map.put("type", ["Create", "Announce"])
201 |> Map.put("blocking_user", user)
202 |> Map.put("user", user)
205 ActivityPub.fetch_activities([user.ap_id | user.following], params)
209 |> add_link_headers(:home_timeline, activities)
210 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
213 def public_timeline(%{assigns: %{user: user}} = conn, params) do
214 local_only = params["local"] in [true, "True", "true", "1"]
218 |> Map.put("type", ["Create", "Announce"])
219 |> Map.put("local_only", local_only)
220 |> Map.put("blocking_user", user)
223 ActivityPub.fetch_public_activities(params)
227 |> add_link_headers(:public_timeline, activities, false, %{"local" => local_only})
228 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
231 def user_statuses(%{assigns: %{user: reading_user}} = conn, params) do
232 with %User{} = user <- Repo.get(User, params["id"]) do
233 # Since Pleroma has no "pinned" posts feature, we'll just set an empty list here
235 if params["pinned"] == "true" do
238 ActivityPub.fetch_user_activities(user, reading_user, params)
242 |> add_link_headers(:user_statuses, activities, params["id"])
243 |> render(StatusView, "index.json", %{
244 activities: activities,
251 def dm_timeline(%{assigns: %{user: user}} = conn, _params) do
253 ActivityPub.fetch_activities_query([user.ap_id], %{"type" => "Create", visibility: "direct"})
255 activities = Repo.all(query)
258 |> add_link_headers(:dm_timeline, activities)
259 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
262 def get_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
263 with %Activity{} = activity <- Repo.get(Activity, id),
264 true <- ActivityPub.visible_for_user?(activity, user) do
265 render(conn, StatusView, "status.json", %{activity: activity, for: user})
269 def get_context(%{assigns: %{user: user}} = conn, %{"id" => id}) do
270 with %Activity{} = activity <- Repo.get(Activity, id),
272 ActivityPub.fetch_activities_for_context(activity.data["context"], %{
273 "blocking_user" => user,
277 activities |> Enum.filter(fn %{id: aid} -> to_string(aid) != to_string(id) end),
279 activities |> Enum.filter(fn %{data: %{"type" => type}} -> type == "Create" end),
280 grouped_activities <- Enum.group_by(activities, fn %{id: id} -> id < activity.id end) do
286 activities: grouped_activities[true] || [],
294 activities: grouped_activities[false] || [],
304 def post_status(conn, %{"status" => "", "media_ids" => media_ids} = params)
305 when length(media_ids) > 0 do
308 |> Map.put("status", ".")
310 post_status(conn, params)
313 def post_status(%{assigns: %{user: user}} = conn, %{"status" => _} = params) do
316 |> Map.put("in_reply_to_status_id", params["in_reply_to_id"])
317 |> Map.put("no_attachment_links", true)
320 case get_req_header(conn, "idempotency-key") do
322 _ -> Ecto.UUID.generate()
326 Cachex.fetch!(:idempotency_cache, idempotency_key, fn _ -> CommonAPI.post(user, params) end)
328 render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity})
331 def delete_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
332 with {:ok, %Activity{}} <- CommonAPI.delete(id, user) do
338 |> json(%{error: "Can't delete this post"})
342 def reblog_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
343 with {:ok, announce, _activity} <- CommonAPI.repeat(ap_id_or_id, user) do
344 render(conn, StatusView, "status.json", %{activity: announce, for: user, as: :activity})
348 def unreblog_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
349 with {:ok, _, _, %{data: %{"id" => id}}} <- CommonAPI.unrepeat(ap_id_or_id, user),
350 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
351 render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity})
355 def fav_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
356 with {:ok, _fav, %{data: %{"id" => id}}} <- CommonAPI.favorite(ap_id_or_id, user),
357 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
358 render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity})
362 def unfav_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
363 with {:ok, _, _, %{data: %{"id" => id}}} <- CommonAPI.unfavorite(ap_id_or_id, user),
364 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
365 render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity})
369 def notifications(%{assigns: %{user: user}} = conn, params) do
370 notifications = Notification.for_user(user, params)
373 Enum.map(notifications, fn x ->
374 render_notification(user, x)
379 |> add_link_headers(:notifications, notifications)
383 def get_notification(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
384 with {:ok, notification} <- Notification.get(user, id) do
385 json(conn, render_notification(user, notification))
389 |> put_resp_content_type("application/json")
390 |> send_resp(403, Jason.encode!(%{"error" => reason}))
394 def clear_notifications(%{assigns: %{user: user}} = conn, _params) do
395 Notification.clear(user)
399 def dismiss_notification(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
400 with {:ok, _notif} <- Notification.dismiss(user, id) do
405 |> put_resp_content_type("application/json")
406 |> send_resp(403, Jason.encode!(%{"error" => reason}))
410 def relationships(%{assigns: %{user: user}} = conn, %{"id" => id}) do
412 q = from(u in User, where: u.id in ^id)
413 targets = Repo.all(q)
414 render(conn, AccountView, "relationships.json", %{user: user, targets: targets})
417 def upload(%{assigns: %{user: _}} = conn, %{"file" => file}) do
418 with {:ok, object} <- ActivityPub.upload(file) do
421 |> Map.put("id", object.id)
423 render(conn, StatusView, "attachment.json", %{attachment: data})
427 def favourited_by(conn, %{"id" => id}) do
428 with %Activity{data: %{"object" => %{"likes" => likes}}} <- Repo.get(Activity, id) do
429 q = from(u in User, where: u.ap_id in ^likes)
431 render(conn, AccountView, "accounts.json", %{users: users, as: :user})
437 def reblogged_by(conn, %{"id" => id}) do
438 with %Activity{data: %{"object" => %{"announcements" => announces}}} <- Repo.get(Activity, id) do
439 q = from(u in User, where: u.ap_id in ^announces)
441 render(conn, AccountView, "accounts.json", %{users: users, as: :user})
447 def hashtag_timeline(%{assigns: %{user: user}} = conn, params) do
448 local_only = params["local"] in [true, "True", "true", "1"]
452 |> Map.put("type", "Create")
453 |> Map.put("local_only", local_only)
454 |> Map.put("blocking_user", user)
457 ActivityPub.fetch_public_activities(params)
461 |> add_link_headers(:hashtag_timeline, activities, params["tag"], %{"local" => local_only})
462 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
466 def followers(conn, %{"id" => id}) do
467 with %User{} = user <- Repo.get(User, id),
468 {:ok, followers} <- User.get_followers(user) do
469 render(conn, AccountView, "accounts.json", %{users: followers, as: :user})
473 def following(conn, %{"id" => id}) do
474 with %User{} = user <- Repo.get(User, id),
475 {:ok, followers} <- User.get_friends(user) do
476 render(conn, AccountView, "accounts.json", %{users: followers, as: :user})
480 def follow_requests(%{assigns: %{user: followed}} = conn, _params) do
481 with {:ok, follow_requests} <- User.get_follow_requests(followed) do
482 render(conn, AccountView, "accounts.json", %{users: follow_requests, as: :user})
486 def authorize_follow_request(%{assigns: %{user: followed}} = conn, %{"id" => id}) do
487 with %User{} = follower <- Repo.get(User, id),
488 {:ok, follower} <- User.follow(follower, followed),
489 %Activity{} = follow_activity <- Utils.fetch_latest_follow(follower, followed),
491 ActivityPub.accept(%{
493 actor: followed.ap_id,
494 object: follow_activity.data["id"],
497 render(conn, AccountView, "relationship.json", %{user: followed, target: follower})
501 |> put_resp_content_type("application/json")
502 |> send_resp(403, Jason.encode!(%{"error" => message}))
506 # def reject_follow_request(%{assigns: %{user: followed}} = conn, %{"id" => id}) do
509 def follow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
510 with %User{} = followed <- Repo.get(User, id),
511 {:ok, follower} <- User.maybe_direct_follow(follower, followed),
512 {:ok, _activity} <- ActivityPub.follow(follower, followed) do
513 render(conn, AccountView, "relationship.json", %{user: follower, target: followed})
517 |> put_resp_content_type("application/json")
518 |> send_resp(403, Jason.encode!(%{"error" => message}))
522 def follow(%{assigns: %{user: follower}} = conn, %{"uri" => uri}) do
523 with %User{} = followed <- Repo.get_by(User, nickname: uri),
524 {:ok, follower} <- User.maybe_direct_follow(follower, followed),
525 {:ok, _activity} <- ActivityPub.follow(follower, followed) do
526 render(conn, AccountView, "account.json", %{user: followed})
530 |> put_resp_content_type("application/json")
531 |> send_resp(403, Jason.encode!(%{"error" => message}))
535 def unfollow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
536 with %User{} = followed <- Repo.get(User, id),
537 {:ok, _activity} <- ActivityPub.unfollow(follower, followed),
538 {:ok, follower, _} <- User.unfollow(follower, followed) do
539 render(conn, AccountView, "relationship.json", %{user: follower, target: followed})
543 def block(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
544 with %User{} = blocked <- Repo.get(User, id),
545 {:ok, blocker} <- User.block(blocker, blocked),
546 {:ok, _activity} <- ActivityPub.block(blocker, blocked) do
547 render(conn, AccountView, "relationship.json", %{user: blocker, target: blocked})
551 |> put_resp_content_type("application/json")
552 |> send_resp(403, Jason.encode!(%{"error" => message}))
556 def unblock(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
557 with %User{} = blocked <- Repo.get(User, id),
558 {:ok, blocker} <- User.unblock(blocker, blocked),
559 {:ok, _activity} <- ActivityPub.unblock(blocker, blocked) do
560 render(conn, AccountView, "relationship.json", %{user: blocker, target: blocked})
564 |> put_resp_content_type("application/json")
565 |> send_resp(403, Jason.encode!(%{"error" => message}))
569 # TODO: Use proper query
570 def blocks(%{assigns: %{user: user}} = conn, _) do
571 with blocked_users <- user.info["blocks"] || [],
572 accounts <- Enum.map(blocked_users, fn ap_id -> User.get_cached_by_ap_id(ap_id) end) do
573 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
578 def domain_blocks(%{assigns: %{user: %{info: info}}} = conn, _) do
579 json(conn, info["domain_blocks"] || [])
582 def block_domain(%{assigns: %{user: blocker}} = conn, %{"domain" => domain}) do
583 User.block_domain(blocker, domain)
587 def unblock_domain(%{assigns: %{user: blocker}} = conn, %{"domain" => domain}) do
588 User.unblock_domain(blocker, domain)
592 def search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
593 accounts = User.search(query, params["resolve"] == "true")
596 if Regex.match?(~r/https?:/, query) do
597 with {:ok, activities} <- OStatus.fetch_activity_from_url(query) do
600 %{data: %{"type" => "Create"}} -> true
611 where: fragment("?->>'type' = 'Create'", a.data),
612 where: "https://www.w3.org/ns/activitystreams#Public" in a.recipients,
615 "to_tsvector('english', ?->'object'->>'content') @@ plainto_tsquery('english', ?)",
620 order_by: [desc: :id]
623 statuses = Repo.all(q) ++ fetched
628 |> Enum.filter(fn tag -> String.starts_with?(tag, "#") end)
629 |> Enum.map(fn tag -> String.slice(tag, 1..-1) end)
632 "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
634 StatusView.render("index.json", activities: statuses, for: user, as: :activity),
641 def account_search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
642 accounts = User.search(query, params["resolve"] == "true")
644 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
649 def favourites(%{assigns: %{user: user}} = conn, _) do
652 |> Map.put("type", "Create")
653 |> Map.put("favorited_by", user.ap_id)
654 |> Map.put("blocking_user", user)
657 ActivityPub.fetch_public_activities(params)
661 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
664 def get_lists(%{assigns: %{user: user}} = conn, opts) do
665 lists = Pleroma.List.for_user(user, opts)
666 res = ListView.render("lists.json", lists: lists)
670 def get_list(%{assigns: %{user: user}} = conn, %{"id" => id}) do
671 with %Pleroma.List{} = list <- Pleroma.List.get(id, user) do
672 res = ListView.render("list.json", list: list)
675 _e -> json(conn, "error")
679 def delete_list(%{assigns: %{user: user}} = conn, %{"id" => id}) do
680 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
681 {:ok, _list} <- Pleroma.List.delete(list) do
689 def create_list(%{assigns: %{user: user}} = conn, %{"title" => title}) do
690 with {:ok, %Pleroma.List{} = list} <- Pleroma.List.create(title, user) do
691 res = ListView.render("list.json", list: list)
696 def add_to_list(%{assigns: %{user: user}} = conn, %{"id" => id, "account_ids" => accounts}) do
698 |> Enum.each(fn account_id ->
699 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
700 %User{} = followed <- Repo.get(User, account_id) do
701 Pleroma.List.follow(list, followed)
708 def remove_from_list(%{assigns: %{user: user}} = conn, %{"id" => id, "account_ids" => accounts}) do
710 |> Enum.each(fn account_id ->
711 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
712 %User{} = followed <- Repo.get(Pleroma.User, account_id) do
713 Pleroma.List.unfollow(list, followed)
720 def list_accounts(%{assigns: %{user: user}} = conn, %{"id" => id}) do
721 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
722 {:ok, users} = Pleroma.List.get_following(list) do
723 render(conn, AccountView, "accounts.json", %{users: users, as: :user})
727 def rename_list(%{assigns: %{user: user}} = conn, %{"id" => id, "title" => title}) do
728 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
729 {:ok, list} <- Pleroma.List.rename(list, title) do
730 res = ListView.render("list.json", list: list)
738 def list_timeline(%{assigns: %{user: user}} = conn, %{"list_id" => id} = params) do
739 with %Pleroma.List{title: title, following: following} <- Pleroma.List.get(id, user) do
742 |> Map.put("type", "Create")
743 |> Map.put("blocking_user", user)
745 # adding title is a hack to not make empty lists function like a public timeline
747 ActivityPub.fetch_activities([title | following], params)
751 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
756 |> json(%{error: "Error."})
760 def index(%{assigns: %{user: user}} = conn, _params) do
763 |> get_session(:oauth_token)
766 mastodon_emoji = mastodonized_emoji()
767 accounts = Map.put(%{}, user.id, AccountView.render("account.json", %{user: user}))
772 streaming_api_base_url:
773 String.replace(Pleroma.Web.Endpoint.static_url(), "http", "ws"),
776 domain: Pleroma.Web.Endpoint.host(),
779 unfollow_modal: false,
782 auto_play_gif: false,
787 default_privacy: "public",
788 default_sensitive: false
790 media_attachments: %{
791 accept_content_types: [
807 Map.get(user.info, "settings") ||
837 push_subscription: nil,
839 custom_emojis: mastodon_emoji,
840 char_limit: Keyword.get(@instance, :limit)
846 |> render(MastodonView, "index.html", %{initial_state: initial_state})
849 |> redirect(to: "/web/login")
853 def put_settings(%{assigns: %{user: user}} = conn, %{"data" => settings} = _params) do
854 with new_info <- Map.put(user.info, "settings", settings),
855 change <- User.info_changeset(user, %{info: new_info}),
856 {:ok, _user} <- User.update_and_set_cache(change) do
862 |> json(%{error: inspect(e)})
866 def login(conn, _) do
868 |> render(MastodonView, "login.html", %{error: false})
871 defp get_or_make_app() do
872 with %App{} = app <- Repo.get_by(App, client_name: "Mastodon-Local") do
877 App.register_changeset(%App{}, %{
878 client_name: "Mastodon-Local",
880 scopes: "read,write,follow"
887 def login_post(conn, %{"authorization" => %{"name" => name, "password" => password}}) do
888 with %User{} = user <- User.get_by_nickname_or_email(name),
889 true <- Pbkdf2.checkpw(password, user.password_hash),
890 {:ok, app} <- get_or_make_app(),
891 {:ok, auth} <- Authorization.create_authorization(app, user),
892 {:ok, token} <- Token.exchange_token(app, auth) do
894 |> put_session(:oauth_token, token.token)
895 |> redirect(to: "/web/getting-started")
899 |> render(MastodonView, "login.html", %{error: "Wrong username or password"})
903 def logout(conn, _) do
909 def relationship_noop(%{assigns: %{user: user}} = conn, %{"id" => id}) do
910 Logger.debug("Unimplemented, returning unmodified relationship")
912 with %User{} = target <- Repo.get(User, id) do
913 render(conn, AccountView, "relationship.json", %{user: user, target: target})
917 def empty_array(conn, _) do
918 Logger.debug("Unimplemented, returning an empty array")
922 def empty_object(conn, _) do
923 Logger.debug("Unimplemented, returning an empty object")
927 def render_notification(user, %{id: id, activity: activity, inserted_at: created_at} = _params) do
928 actor = User.get_cached_by_ap_id(activity.data["actor"])
931 NaiveDateTime.to_iso8601(created_at)
932 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
934 case activity.data["type"] do
939 created_at: created_at,
940 account: AccountView.render("account.json", %{user: actor}),
941 status: StatusView.render("status.json", %{activity: activity, for: user})
945 liked_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
950 created_at: created_at,
951 account: AccountView.render("account.json", %{user: actor}),
952 status: StatusView.render("status.json", %{activity: liked_activity, for: user})
956 announced_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
961 created_at: created_at,
962 account: AccountView.render("account.json", %{user: actor}),
963 status: StatusView.render("status.json", %{activity: announced_activity, for: user})
970 created_at: created_at,
971 account: AccountView.render("account.json", %{user: actor})
979 def errors(conn, _) do
982 |> json("Something went wrong")