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}
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 \\ false) do
148 last = List.last(activities)
149 first = List.first(activities)
155 {next_url, prev_url} =
158 mastodon_api_url(Pleroma.Web.Endpoint, method, param, max_id: min),
159 mastodon_api_url(Pleroma.Web.Endpoint, method, param, since_id: max)
163 mastodon_api_url(Pleroma.Web.Endpoint, method, max_id: min),
164 mastodon_api_url(Pleroma.Web.Endpoint, method, since_id: max)
169 |> put_resp_header("link", "<#{next_url}>; rel=\"next\", <#{prev_url}>; rel=\"prev\"")
175 def home_timeline(%{assigns: %{user: user}} = conn, params) do
178 |> Map.put("type", ["Create", "Announce"])
179 |> Map.put("blocking_user", user)
180 |> Map.put("user", user)
183 ActivityPub.fetch_activities([user.ap_id | user.following], params)
187 |> add_link_headers(:home_timeline, activities)
188 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
191 def public_timeline(%{assigns: %{user: user}} = conn, params) do
194 |> Map.put("type", ["Create", "Announce"])
195 |> Map.put("local_only", params["local"] in [true, "True", "true", "1"])
196 |> Map.put("blocking_user", user)
199 ActivityPub.fetch_public_activities(params)
203 |> add_link_headers(:public_timeline, activities)
204 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
207 def user_statuses(%{assigns: %{user: user}} = conn, params) do
208 with %User{ap_id: ap_id} <- Repo.get(User, params["id"]) do
211 |> Map.put("type", ["Create", "Announce"])
212 |> Map.put("actor_id", ap_id)
213 |> Map.put("whole_db", true)
216 if params["pinned"] == "true" do
217 # Since Pleroma has no "pinned" posts feature, we'll just set an empty list here
220 ActivityPub.fetch_public_activities(params)
225 |> add_link_headers(:user_statuses, activities, params["id"])
226 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
230 def get_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
231 with %Activity{} = activity <- Repo.get(Activity, id),
232 true <- ActivityPub.visible_for_user?(activity, user) do
233 render(conn, StatusView, "status.json", %{activity: activity, for: user})
237 def get_context(%{assigns: %{user: user}} = conn, %{"id" => id}) do
238 with %Activity{} = activity <- Repo.get(Activity, id),
240 ActivityPub.fetch_activities_for_context(activity.data["context"], %{
241 "blocking_user" => user,
245 activities |> Enum.filter(fn %{id: aid} -> to_string(aid) != to_string(id) end),
247 activities |> Enum.filter(fn %{data: %{"type" => type}} -> type == "Create" end),
248 grouped_activities <- Enum.group_by(activities, fn %{id: id} -> id < activity.id end) do
254 activities: grouped_activities[true] || [],
262 activities: grouped_activities[false] || [],
272 def post_status(%{assigns: %{user: user}} = conn, %{"status" => _} = params) do
275 |> Map.put("in_reply_to_status_id", params["in_reply_to_id"])
276 |> Map.put("no_attachment_links", true)
279 case get_req_header(conn, "idempotency-key") do
281 _ -> Ecto.UUID.generate()
288 fallback: fn _ -> CommonAPI.post(user, params) end
291 render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity})
294 def delete_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
295 with {:ok, %Activity{}} <- CommonAPI.delete(id, user) do
301 |> json(%{error: "Can't delete this post"})
305 def reblog_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
306 with {:ok, announce, _activity} = CommonAPI.repeat(ap_id_or_id, user) do
307 render(conn, StatusView, "status.json", %{activity: announce, for: user, as: :activity})
311 def unreblog_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
312 with {:ok, _, _, %{data: %{"id" => id}}} = CommonAPI.unrepeat(ap_id_or_id, user),
313 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
314 render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity})
318 def fav_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
319 with {:ok, _fav, %{data: %{"id" => id}}} = CommonAPI.favorite(ap_id_or_id, user),
320 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
321 render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity})
325 def unfav_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
326 with {:ok, %{data: %{"id" => id}}} = CommonAPI.unfavorite(ap_id_or_id, user),
327 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
328 render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity})
332 def notifications(%{assigns: %{user: user}} = conn, params) do
333 notifications = Notification.for_user(user, params)
336 Enum.map(notifications, fn x ->
337 render_notification(user, x)
342 |> add_link_headers(:notifications, notifications)
346 def get_notification(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
347 with {:ok, notification} <- Notification.get(user, id) do
348 json(conn, render_notification(user, notification))
352 |> put_resp_content_type("application/json")
353 |> send_resp(403, Jason.encode!(%{"error" => reason}))
357 def clear_notifications(%{assigns: %{user: user}} = conn, _params) do
358 Notification.clear(user)
362 def dismiss_notification(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
363 with {:ok, _notif} <- Notification.dismiss(user, id) do
368 |> put_resp_content_type("application/json")
369 |> send_resp(403, Jason.encode!(%{"error" => reason}))
373 def relationships(%{assigns: %{user: user}} = conn, %{"id" => id}) do
375 q = from(u in User, where: u.id in ^id)
376 targets = Repo.all(q)
377 render(conn, AccountView, "relationships.json", %{user: user, targets: targets})
380 def upload(%{assigns: %{user: _}} = conn, %{"file" => file}) do
381 with {:ok, object} <- ActivityPub.upload(file) do
384 |> Map.put("id", object.id)
386 render(conn, StatusView, "attachment.json", %{attachment: data})
390 def favourited_by(conn, %{"id" => id}) do
391 with %Activity{data: %{"object" => %{"likes" => likes}}} <- Repo.get(Activity, id) do
392 q = from(u in User, where: u.ap_id in ^likes)
394 render(conn, AccountView, "accounts.json", %{users: users, as: :user})
400 def reblogged_by(conn, %{"id" => id}) do
401 with %Activity{data: %{"object" => %{"announcements" => announces}}} <- Repo.get(Activity, id) do
402 q = from(u in User, where: u.ap_id in ^announces)
404 render(conn, AccountView, "accounts.json", %{users: users, as: :user})
410 def hashtag_timeline(%{assigns: %{user: user}} = conn, params) do
413 |> Map.put("type", "Create")
414 |> Map.put("local_only", !!params["local"])
415 |> Map.put("blocking_user", user)
418 ActivityPub.fetch_public_activities(params)
422 |> add_link_headers(:hashtag_timeline, activities, params["tag"])
423 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
427 def followers(conn, %{"id" => id}) do
428 with %User{} = user <- Repo.get(User, id),
429 {:ok, followers} <- User.get_followers(user) do
430 render(conn, AccountView, "accounts.json", %{users: followers, as: :user})
434 def following(conn, %{"id" => id}) do
435 with %User{} = user <- Repo.get(User, id),
436 {:ok, followers} <- User.get_friends(user) do
437 render(conn, AccountView, "accounts.json", %{users: followers, as: :user})
441 def follow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
442 with %User{} = followed <- Repo.get(User, id),
443 {:ok, follower} <- User.follow(follower, followed),
444 {:ok, _activity} <- ActivityPub.follow(follower, followed) do
445 render(conn, AccountView, "relationship.json", %{user: follower, target: followed})
449 |> put_resp_content_type("application/json")
450 |> send_resp(403, Jason.encode!(%{"error" => message}))
454 def follow(%{assigns: %{user: follower}} = conn, %{"uri" => uri}) do
455 with %User{} = followed <- Repo.get_by(User, nickname: uri),
456 {:ok, follower} <- User.follow(follower, followed),
457 {:ok, _activity} <- ActivityPub.follow(follower, followed) do
458 render(conn, AccountView, "account.json", %{user: followed})
462 |> put_resp_content_type("application/json")
463 |> send_resp(403, Jason.encode!(%{"error" => message}))
467 # TODO: Clean up and unify
468 def unfollow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
469 with %User{} = followed <- Repo.get(User, id),
470 {:ok, follower, follow_activity} <- User.unfollow(follower, followed),
472 ActivityPub.insert(%{
474 "actor" => follower.ap_id,
475 # get latest Follow for these users
476 "object" => follow_activity.data["id"]
478 render(conn, AccountView, "relationship.json", %{user: follower, target: followed})
482 def block(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
483 with %User{} = blocked <- Repo.get(User, id),
484 {:ok, blocker} <- User.block(blocker, blocked) do
485 render(conn, AccountView, "relationship.json", %{user: blocker, target: blocked})
489 |> put_resp_content_type("application/json")
490 |> send_resp(403, Jason.encode!(%{"error" => message}))
494 def unblock(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
495 with %User{} = blocked <- Repo.get(User, id),
496 {:ok, blocker} <- User.unblock(blocker, blocked) do
497 render(conn, AccountView, "relationship.json", %{user: blocker, target: blocked})
501 |> put_resp_content_type("application/json")
502 |> send_resp(403, Jason.encode!(%{"error" => message}))
506 # TODO: Use proper query
507 def blocks(%{assigns: %{user: user}} = conn, _) do
508 with blocked_users <- user.info["blocks"] || [],
509 accounts <- Enum.map(blocked_users, fn ap_id -> User.get_cached_by_ap_id(ap_id) end) do
510 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
515 def search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
516 accounts = User.search(query, params["resolve"] == "true")
519 if Regex.match?(~r/https?:/, query) do
520 with {:ok, activities} <- OStatus.fetch_activity_from_url(query) do
523 %{data: %{"type" => "Create"}} -> true
534 where: fragment("?->>'type' = 'Create'", a.data),
535 where: "https://www.w3.org/ns/activitystreams#Public" in a.recipients,
538 "to_tsvector('english', ?->'object'->>'content') @@ plainto_tsquery('english', ?)",
543 order_by: [desc: :id]
546 statuses = Repo.all(q) ++ fetched
551 |> Enum.filter(fn tag -> String.starts_with?(tag, "#") end)
552 |> Enum.map(fn tag -> String.slice(tag, 1..-1) end)
555 "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
557 StatusView.render("index.json", activities: statuses, for: user, as: :activity),
564 def account_search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
565 accounts = User.search(query, params["resolve"] == "true")
567 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
572 def favourites(%{assigns: %{user: user}} = conn, _) do
575 |> Map.put("type", "Create")
576 |> Map.put("favorited_by", user.ap_id)
577 |> Map.put("blocking_user", user)
580 ActivityPub.fetch_public_activities(params)
584 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
587 def index(%{assigns: %{user: user}} = conn, _params) do
590 |> get_session(:oauth_token)
593 mastodon_emoji = mastodonized_emoji()
594 accounts = Map.put(%{}, user.id, AccountView.render("account.json", %{user: user}))
599 streaming_api_base_url:
600 String.replace(Pleroma.Web.Endpoint.static_url(), "http", "ws"),
603 domain: Pleroma.Web.Endpoint.host(),
606 unfollow_modal: false,
609 auto_play_gif: false,
614 default_privacy: "public",
615 default_sensitive: false
617 media_attachments: %{
618 accept_content_types: [
634 Map.get(user.info, "settings") ||
664 push_subscription: nil,
666 custom_emojis: mastodon_emoji,
667 char_limit: Keyword.get(@instance, :limit)
673 |> render(MastodonView, "index.html", %{initial_state: initial_state})
676 |> redirect(to: "/web/login")
680 def put_settings(%{assigns: %{user: user}} = conn, %{"data" => settings} = _params) do
681 with new_info <- Map.put(user.info, "settings", settings),
682 change <- User.info_changeset(user, %{info: new_info}),
683 {:ok, _user} <- User.update_and_set_cache(change) do
689 |> json(%{error: inspect(e)})
693 def login(conn, _) do
695 |> render(MastodonView, "login.html", %{error: false})
698 defp get_or_make_app() do
699 with %App{} = app <- Repo.get_by(App, client_name: "Mastodon-Local") do
704 App.register_changeset(%App{}, %{
705 client_name: "Mastodon-Local",
707 scopes: "read,write,follow"
714 def login_post(conn, %{"authorization" => %{"name" => name, "password" => password}}) do
715 with %User{} = user <- User.get_by_nickname_or_email(name),
716 true <- Pbkdf2.checkpw(password, user.password_hash),
717 {:ok, app} <- get_or_make_app(),
718 {:ok, auth} <- Authorization.create_authorization(app, user),
719 {:ok, token} <- Token.exchange_token(app, auth) do
721 |> put_session(:oauth_token, token.token)
722 |> redirect(to: "/web/getting-started")
726 |> render(MastodonView, "login.html", %{error: "Wrong username or password"})
730 def logout(conn, _) do
736 def relationship_noop(%{assigns: %{user: user}} = conn, %{"id" => id}) do
737 Logger.debug("Unimplemented, returning unmodified relationship")
739 with %User{} = target <- Repo.get(User, id) do
740 render(conn, AccountView, "relationship.json", %{user: user, target: target})
744 def empty_array(conn, _) do
745 Logger.debug("Unimplemented, returning an empty array")
749 def empty_object(conn, _) do
750 Logger.debug("Unimplemented, returning an empty object")
754 def render_notification(user, %{id: id, activity: activity, inserted_at: created_at} = _params) do
755 actor = User.get_cached_by_ap_id(activity.data["actor"])
758 NaiveDateTime.to_iso8601(created_at)
759 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
761 case activity.data["type"] do
766 created_at: created_at,
767 account: AccountView.render("account.json", %{user: actor}),
768 status: StatusView.render("status.json", %{activity: activity, for: user})
772 liked_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
777 created_at: created_at,
778 account: AccountView.render("account.json", %{user: actor}),
779 status: StatusView.render("status.json", %{activity: liked_activity, for: user})
783 announced_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
788 created_at: created_at,
789 account: AccountView.render("account.json", %{user: actor}),
790 status: StatusView.render("status.json", %{activity: announced_activity, for: user})
797 created_at: created_at,
798 account: AccountView.render("account.json", %{user: actor})