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 def create_app(conn, params) do
14 with cs <- App.register_changeset(%App{}, params) |> IO.inspect(),
15 {:ok, app} <- Repo.insert(cs) |> IO.inspect() do
18 client_id: app.client_id,
19 client_secret: app.client_secret
26 def update_credentials(%{assigns: %{user: user}} = conn, params) do
30 if bio = params["note"] do
31 Map.put(params, "bio", bio)
37 if name = params["display_name"] do
38 Map.put(params, "name", name)
44 if avatar = params["avatar"] do
45 with %Plug.Upload{} <- avatar,
46 {:ok, object} <- ActivityPub.upload(avatar),
47 change = Ecto.Changeset.change(user, %{avatar: object.data}),
48 {:ok, user} = User.update_and_set_cache(change) do
58 if banner = params["header"] do
59 with %Plug.Upload{} <- banner,
60 {:ok, object} <- ActivityPub.upload(banner),
61 new_info <- Map.put(user.info, "banner", object.data),
62 change <- User.info_changeset(user, %{info: new_info}),
63 {:ok, user} <- User.update_and_set_cache(change) do
72 with changeset <- User.update_changeset(user, params),
73 {:ok, user} <- User.update_and_set_cache(changeset) do
74 if original_user != user do
75 CommonAPI.update(user)
78 json(conn, AccountView.render("account.json", %{user: user}))
83 |> json(%{error: "Invalid request"})
87 def verify_credentials(%{assigns: %{user: user}} = conn, _) do
88 account = AccountView.render("account.json", %{user: user})
92 def user(conn, %{"id" => id}) do
93 with %User{} = user <- Repo.get(User, id) do
94 account = AccountView.render("account.json", %{user: user})
100 |> json(%{error: "Can't find user"})
104 @instance Application.get_env(:pleroma, :instance)
105 @mastodon_api_level "2.3.3"
107 def masto_instance(conn, _params) do
110 title: Keyword.get(@instance, :name),
111 description: "A Pleroma instance, an alternative fediverse server",
112 version: "#{@mastodon_api_level} (compatible; #{Keyword.get(@instance, :version)})",
113 email: Keyword.get(@instance, :email),
115 streaming_api: String.replace(Pleroma.Web.Endpoint.static_url(), "http", "ws")
117 stats: Stats.get_stats(),
118 thumbnail: Web.base_url() <> "/instance/thumbnail.jpeg",
119 max_toot_chars: Keyword.get(@instance, :limit)
125 def peers(conn, _params) do
126 json(conn, Stats.get_peers())
129 defp mastodonized_emoji do
130 Pleroma.Formatter.get_custom_emoji()
131 |> Enum.map(fn {shortcode, relative_url} ->
132 url = to_string(URI.merge(Web.base_url(), relative_url))
135 "shortcode" => shortcode,
142 def custom_emojis(conn, _params) do
143 mastodon_emoji = mastodonized_emoji()
144 json(conn, mastodon_emoji)
147 defp add_link_headers(conn, method, activities, param \\ nil, params \\ %{}) do
148 last = List.last(activities)
149 first = List.first(activities)
155 {next_url, prev_url} =
159 Pleroma.Web.Endpoint,
162 Map.merge(params, %{max_id: min})
165 Pleroma.Web.Endpoint,
168 Map.merge(params, %{since_id: max})
174 Pleroma.Web.Endpoint,
176 Map.merge(params, %{max_id: min})
179 Pleroma.Web.Endpoint,
181 Map.merge(params, %{since_id: max})
187 |> put_resp_header("link", "<#{next_url}>; rel=\"next\", <#{prev_url}>; rel=\"prev\"")
193 def home_timeline(%{assigns: %{user: user}} = conn, params) do
196 |> Map.put("type", ["Create", "Announce"])
197 |> Map.put("blocking_user", user)
198 |> Map.put("user", user)
201 ActivityPub.fetch_activities([user.ap_id | user.following], params)
205 |> add_link_headers(:home_timeline, activities)
206 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
209 def public_timeline(%{assigns: %{user: user}} = conn, params) do
210 local_only = params["local"] in [true, "True", "true", "1"]
214 |> Map.put("type", ["Create", "Announce"])
215 |> Map.put("local_only", local_only)
216 |> Map.put("blocking_user", user)
219 ActivityPub.fetch_public_activities(params)
223 |> add_link_headers(:public_timeline, activities, false, %{"local" => local_only})
224 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
227 def user_statuses(%{assigns: %{user: reading_user}} = conn, params) do
228 with %User{} = user <- Repo.get(User, params["id"]) do
229 # Since Pleroma has no "pinned" posts feature, we'll just set an empty list here
231 if params["pinned"] == "true" do
234 ActivityPub.fetch_user_activities(user, reading_user, params)
238 |> add_link_headers(:user_statuses, activities, params["id"])
239 |> render(StatusView, "index.json", %{
240 activities: activities,
247 def dm_timeline(%{assigns: %{user: user}} = conn, params) do
249 ActivityPub.fetch_activities_query([user.ap_id], %{"type" => "Create", visibility: "direct"})
251 activities = Repo.all(query)
254 |> add_link_headers(:dm_timeline, activities)
255 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
258 def get_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
259 with %Activity{} = activity <- Repo.get(Activity, id),
260 true <- ActivityPub.visible_for_user?(activity, user) do
261 render(conn, StatusView, "status.json", %{activity: activity, for: user})
265 def get_context(%{assigns: %{user: user}} = conn, %{"id" => id}) do
266 with %Activity{} = activity <- Repo.get(Activity, id),
268 ActivityPub.fetch_activities_for_context(activity.data["context"], %{
269 "blocking_user" => user,
273 activities |> Enum.filter(fn %{id: aid} -> to_string(aid) != to_string(id) end),
275 activities |> Enum.filter(fn %{data: %{"type" => type}} -> type == "Create" end),
276 grouped_activities <- Enum.group_by(activities, fn %{id: id} -> id < activity.id end) do
282 activities: grouped_activities[true] || [],
290 activities: grouped_activities[false] || [],
300 def post_status(%{assigns: %{user: user}} = conn, %{"status" => _} = params) do
303 |> Map.put("in_reply_to_status_id", params["in_reply_to_id"])
304 |> Map.put("no_attachment_links", true)
307 case get_req_header(conn, "idempotency-key") do
309 _ -> Ecto.UUID.generate()
313 Cachex.fetch!(:idempotency_cache, idempotency_key, fn _ -> CommonAPI.post(user, params) end)
315 render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity})
318 def delete_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
319 with {:ok, %Activity{}} <- CommonAPI.delete(id, user) do
325 |> json(%{error: "Can't delete this post"})
329 def reblog_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
330 with {:ok, announce, _activity} = CommonAPI.repeat(ap_id_or_id, user) do
331 render(conn, StatusView, "status.json", %{activity: announce, for: user, as: :activity})
335 def unreblog_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
336 with {:ok, _, _, %{data: %{"id" => id}}} = CommonAPI.unrepeat(ap_id_or_id, user),
337 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
338 render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity})
342 def fav_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
343 with {:ok, _fav, %{data: %{"id" => id}}} = CommonAPI.favorite(ap_id_or_id, user),
344 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
345 render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity})
349 def unfav_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
350 with {:ok, _, _, %{data: %{"id" => id}}} = CommonAPI.unfavorite(ap_id_or_id, user),
351 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
352 render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity})
356 def notifications(%{assigns: %{user: user}} = conn, params) do
357 notifications = Notification.for_user(user, params)
360 Enum.map(notifications, fn x ->
361 render_notification(user, x)
366 |> add_link_headers(:notifications, notifications)
370 def get_notification(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
371 with {:ok, notification} <- Notification.get(user, id) do
372 json(conn, render_notification(user, notification))
376 |> put_resp_content_type("application/json")
377 |> send_resp(403, Jason.encode!(%{"error" => reason}))
381 def clear_notifications(%{assigns: %{user: user}} = conn, _params) do
382 Notification.clear(user)
386 def dismiss_notification(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
387 with {:ok, _notif} <- Notification.dismiss(user, id) do
392 |> put_resp_content_type("application/json")
393 |> send_resp(403, Jason.encode!(%{"error" => reason}))
397 def relationships(%{assigns: %{user: user}} = conn, %{"id" => id}) do
399 q = from(u in User, where: u.id in ^id)
400 targets = Repo.all(q)
401 render(conn, AccountView, "relationships.json", %{user: user, targets: targets})
404 def upload(%{assigns: %{user: _}} = conn, %{"file" => file}) do
405 with {:ok, object} <- ActivityPub.upload(file) do
408 |> Map.put("id", object.id)
410 render(conn, StatusView, "attachment.json", %{attachment: data})
414 def favourited_by(conn, %{"id" => id}) do
415 with %Activity{data: %{"object" => %{"likes" => likes}}} <- Repo.get(Activity, id) do
416 q = from(u in User, where: u.ap_id in ^likes)
418 render(conn, AccountView, "accounts.json", %{users: users, as: :user})
424 def reblogged_by(conn, %{"id" => id}) do
425 with %Activity{data: %{"object" => %{"announcements" => announces}}} <- Repo.get(Activity, id) do
426 q = from(u in User, where: u.ap_id in ^announces)
428 render(conn, AccountView, "accounts.json", %{users: users, as: :user})
434 def hashtag_timeline(%{assigns: %{user: user}} = conn, params) do
435 local_only = params["local"] in [true, "True", "true", "1"]
439 |> Map.put("type", "Create")
440 |> Map.put("local_only", local_only)
441 |> Map.put("blocking_user", user)
444 ActivityPub.fetch_public_activities(params)
448 |> add_link_headers(:hashtag_timeline, activities, params["tag"], %{"local" => local_only})
449 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
453 def followers(conn, %{"id" => id}) do
454 with %User{} = user <- Repo.get(User, id),
455 {:ok, followers} <- User.get_followers(user) do
456 render(conn, AccountView, "accounts.json", %{users: followers, as: :user})
460 def following(conn, %{"id" => id}) do
461 with %User{} = user <- Repo.get(User, id),
462 {:ok, followers} <- User.get_friends(user) do
463 render(conn, AccountView, "accounts.json", %{users: followers, as: :user})
467 def follow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
468 with %User{} = followed <- Repo.get(User, id),
469 {:ok, follower} <- User.maybe_direct_follow(follower, followed),
470 {:ok, _activity} <- ActivityPub.follow(follower, followed) do
471 render(conn, AccountView, "relationship.json", %{user: follower, target: followed})
475 |> put_resp_content_type("application/json")
476 |> send_resp(403, Jason.encode!(%{"error" => message}))
480 def follow(%{assigns: %{user: follower}} = conn, %{"uri" => uri}) do
481 with %User{} = followed <- Repo.get_by(User, nickname: uri),
482 {:ok, follower} <- User.maybe_direct_follow(follower, followed),
483 {:ok, _activity} <- ActivityPub.follow(follower, followed) do
484 render(conn, AccountView, "account.json", %{user: followed})
488 |> put_resp_content_type("application/json")
489 |> send_resp(403, Jason.encode!(%{"error" => message}))
493 def unfollow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
494 with %User{} = followed <- Repo.get(User, id),
495 {:ok, _activity} <- ActivityPub.unfollow(follower, followed),
496 {:ok, follower, _} <- User.unfollow(follower, followed) do
497 render(conn, AccountView, "relationship.json", %{user: follower, target: followed})
501 def block(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
502 with %User{} = blocked <- Repo.get(User, id),
503 {:ok, blocker} <- User.block(blocker, blocked),
504 {:ok, _activity} <- ActivityPub.block(blocker, blocked) do
505 render(conn, AccountView, "relationship.json", %{user: blocker, target: blocked})
509 |> put_resp_content_type("application/json")
510 |> send_resp(403, Jason.encode!(%{"error" => message}))
514 def unblock(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
515 with %User{} = blocked <- Repo.get(User, id),
516 {:ok, blocker} <- User.unblock(blocker, blocked),
517 {:ok, _activity} <- ActivityPub.unblock(blocker, blocked) do
518 render(conn, AccountView, "relationship.json", %{user: blocker, target: blocked})
522 |> put_resp_content_type("application/json")
523 |> send_resp(403, Jason.encode!(%{"error" => message}))
527 # TODO: Use proper query
528 def blocks(%{assigns: %{user: user}} = conn, _) do
529 with blocked_users <- user.info["blocks"] || [],
530 accounts <- Enum.map(blocked_users, fn ap_id -> User.get_cached_by_ap_id(ap_id) end) do
531 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
536 def domain_blocks(%{assigns: %{user: %{info: info}}} = conn, _) do
537 json(conn, info["domain_blocks"] || [])
540 def block_domain(%{assigns: %{user: blocker}} = conn, %{"domain" => domain}) do
541 User.block_domain(blocker, domain)
545 def unblock_domain(%{assigns: %{user: blocker}} = conn, %{"domain" => domain}) do
546 User.unblock_domain(blocker, domain)
550 def search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
551 accounts = User.search(query, params["resolve"] == "true")
554 if Regex.match?(~r/https?:/, query) do
555 with {:ok, activities} <- OStatus.fetch_activity_from_url(query) do
558 %{data: %{"type" => "Create"}} -> true
569 where: fragment("?->>'type' = 'Create'", a.data),
570 where: "https://www.w3.org/ns/activitystreams#Public" in a.recipients,
573 "to_tsvector('english', ?->'object'->>'content') @@ plainto_tsquery('english', ?)",
578 order_by: [desc: :id]
581 statuses = Repo.all(q) ++ fetched
586 |> Enum.filter(fn tag -> String.starts_with?(tag, "#") end)
587 |> Enum.map(fn tag -> String.slice(tag, 1..-1) end)
590 "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
592 StatusView.render("index.json", activities: statuses, for: user, as: :activity),
599 def account_search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
600 accounts = User.search(query, params["resolve"] == "true")
602 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
607 def favourites(%{assigns: %{user: user}} = conn, _) do
610 |> Map.put("type", "Create")
611 |> Map.put("favorited_by", user.ap_id)
612 |> Map.put("blocking_user", user)
615 ActivityPub.fetch_public_activities(params)
619 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
622 def get_lists(%{assigns: %{user: user}} = conn, opts) do
623 lists = Pleroma.List.for_user(user, opts)
624 res = ListView.render("lists.json", lists: lists)
628 def get_list(%{assigns: %{user: user}} = conn, %{"id" => id}) do
629 with %Pleroma.List{} = list <- Pleroma.List.get(id, user) do
630 res = ListView.render("list.json", list: list)
633 _e -> json(conn, "error")
637 def delete_list(%{assigns: %{user: user}} = conn, %{"id" => id}) do
638 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
639 {:ok, _list} <- Pleroma.List.delete(list) do
647 def create_list(%{assigns: %{user: user}} = conn, %{"title" => title}) do
648 with {:ok, %Pleroma.List{} = list} <- Pleroma.List.create(title, user) do
649 res = ListView.render("list.json", list: list)
654 def add_to_list(%{assigns: %{user: user}} = conn, %{"id" => id, "account_ids" => accounts}) do
656 |> Enum.each(fn account_id ->
657 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
658 %User{} = followed <- Repo.get(User, account_id) do
659 Pleroma.List.follow(list, followed)
666 def remove_from_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(Pleroma.User, account_id) do
671 Pleroma.List.unfollow(list, followed)
678 def list_accounts(%{assigns: %{user: user}} = conn, %{"id" => id}) do
679 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
680 {:ok, users} = Pleroma.List.get_following(list) do
681 render(conn, AccountView, "accounts.json", %{users: users, as: :user})
685 def rename_list(%{assigns: %{user: user}} = conn, %{"id" => id, "title" => title}) do
686 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
687 {:ok, list} <- Pleroma.List.rename(list, title) do
688 res = ListView.render("list.json", list: list)
696 def list_timeline(%{assigns: %{user: user}} = conn, %{"list_id" => id} = params) do
697 with %Pleroma.List{title: title, following: following} <- Pleroma.List.get(id, user) do
700 |> Map.put("type", "Create")
701 |> Map.put("blocking_user", user)
703 # adding title is a hack to not make empty lists function like a public timeline
705 ActivityPub.fetch_activities([title | following], params)
709 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
714 |> json(%{error: "Error."})
718 def index(%{assigns: %{user: user}} = conn, _params) do
721 |> get_session(:oauth_token)
724 mastodon_emoji = mastodonized_emoji()
725 accounts = Map.put(%{}, user.id, AccountView.render("account.json", %{user: user}))
730 streaming_api_base_url:
731 String.replace(Pleroma.Web.Endpoint.static_url(), "http", "ws"),
734 domain: Pleroma.Web.Endpoint.host(),
737 unfollow_modal: false,
740 auto_play_gif: false,
745 default_privacy: "public",
746 default_sensitive: false
748 media_attachments: %{
749 accept_content_types: [
765 Map.get(user.info, "settings") ||
795 push_subscription: nil,
797 custom_emojis: mastodon_emoji,
798 char_limit: Keyword.get(@instance, :limit)
804 |> render(MastodonView, "index.html", %{initial_state: initial_state})
807 |> redirect(to: "/web/login")
811 def put_settings(%{assigns: %{user: user}} = conn, %{"data" => settings} = _params) do
812 with new_info <- Map.put(user.info, "settings", settings),
813 change <- User.info_changeset(user, %{info: new_info}),
814 {:ok, _user} <- User.update_and_set_cache(change) do
820 |> json(%{error: inspect(e)})
824 def login(conn, _) do
826 |> render(MastodonView, "login.html", %{error: false})
829 defp get_or_make_app() do
830 with %App{} = app <- Repo.get_by(App, client_name: "Mastodon-Local") do
835 App.register_changeset(%App{}, %{
836 client_name: "Mastodon-Local",
838 scopes: "read,write,follow"
845 def login_post(conn, %{"authorization" => %{"name" => name, "password" => password}}) do
846 with %User{} = user <- User.get_by_nickname_or_email(name),
847 true <- Pbkdf2.checkpw(password, user.password_hash),
848 {:ok, app} <- get_or_make_app(),
849 {:ok, auth} <- Authorization.create_authorization(app, user),
850 {:ok, token} <- Token.exchange_token(app, auth) do
852 |> put_session(:oauth_token, token.token)
853 |> redirect(to: "/web/getting-started")
857 |> render(MastodonView, "login.html", %{error: "Wrong username or password"})
861 def logout(conn, _) do
867 def relationship_noop(%{assigns: %{user: user}} = conn, %{"id" => id}) do
868 Logger.debug("Unimplemented, returning unmodified relationship")
870 with %User{} = target <- Repo.get(User, id) do
871 render(conn, AccountView, "relationship.json", %{user: user, target: target})
875 def empty_array(conn, _) do
876 Logger.debug("Unimplemented, returning an empty array")
880 def empty_object(conn, _) do
881 Logger.debug("Unimplemented, returning an empty object")
885 def render_notification(user, %{id: id, activity: activity, inserted_at: created_at} = _params) do
886 actor = User.get_cached_by_ap_id(activity.data["actor"])
889 NaiveDateTime.to_iso8601(created_at)
890 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
892 case activity.data["type"] do
897 created_at: created_at,
898 account: AccountView.render("account.json", %{user: actor}),
899 status: StatusView.render("status.json", %{activity: activity, for: user})
903 liked_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
908 created_at: created_at,
909 account: AccountView.render("account.json", %{user: actor}),
910 status: StatusView.render("status.json", %{activity: liked_activity, for: user})
914 announced_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
919 created_at: created_at,
920 account: AccountView.render("account.json", %{user: actor}),
921 status: StatusView.render("status.json", %{activity: announced_activity, for: user})
928 created_at: created_at,
929 account: AccountView.render("account.json", %{user: actor})