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)
106 def masto_instance(conn, _params) do
109 title: Keyword.get(@instance, :name),
110 description: "A Pleroma instance, an alternative fediverse server",
111 version: Keyword.get(@instance, :version),
112 email: Keyword.get(@instance, :email),
114 streaming_api: String.replace(Web.base_url(), ["http", "https"], "wss")
116 stats: Stats.get_stats(),
117 thumbnail: Web.base_url() <> "/instance/thumbnail.jpeg",
118 max_toot_chars: Keyword.get(@instance, :limit)
124 def peers(conn, _params) do
125 json(conn, Stats.get_peers())
128 defp mastodonized_emoji do
129 Pleroma.Formatter.get_custom_emoji()
130 |> Enum.map(fn {shortcode, relative_url} ->
131 url = to_string(URI.merge(Web.base_url(), relative_url))
134 "shortcode" => shortcode,
141 def custom_emojis(conn, _params) do
142 mastodon_emoji = mastodonized_emoji()
143 json(conn, mastodon_emoji)
146 defp add_link_headers(conn, method, activities, param \\ false) do
147 last = List.last(activities)
148 first = List.first(activities)
154 {next_url, prev_url} =
157 mastodon_api_url(Pleroma.Web.Endpoint, method, param, max_id: min),
158 mastodon_api_url(Pleroma.Web.Endpoint, method, param, since_id: max)
162 mastodon_api_url(Pleroma.Web.Endpoint, method, max_id: min),
163 mastodon_api_url(Pleroma.Web.Endpoint, method, since_id: max)
168 |> put_resp_header("link", "<#{next_url}>; rel=\"next\", <#{prev_url}>; rel=\"prev\"")
174 def home_timeline(%{assigns: %{user: user}} = conn, params) do
177 |> Map.put("type", ["Create", "Announce"])
178 |> Map.put("blocking_user", user)
179 |> Map.put("user", user)
182 ActivityPub.fetch_activities([user.ap_id | user.following], params)
186 |> add_link_headers(:home_timeline, activities)
187 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
190 def public_timeline(%{assigns: %{user: user}} = conn, params) do
193 |> Map.put("type", ["Create", "Announce"])
194 |> Map.put("local_only", params["local"] in [true, "True", "true", "1"])
195 |> Map.put("blocking_user", user)
198 ActivityPub.fetch_public_activities(params)
202 |> add_link_headers(:public_timeline, activities)
203 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
206 def user_statuses(%{assigns: %{user: user}} = conn, params) do
207 with %User{ap_id: ap_id} <- Repo.get(User, params["id"]) do
210 |> Map.put("type", ["Create", "Announce"])
211 |> Map.put("actor_id", ap_id)
212 |> Map.put("whole_db", true)
215 ActivityPub.fetch_public_activities(params)
219 |> add_link_headers(:user_statuses, activities, params["id"])
220 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
224 def get_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
225 with %Activity{} = activity <- Repo.get(Activity, id),
226 true <- ActivityPub.visible_for_user?(activity, user) do
227 render(conn, StatusView, "status.json", %{activity: activity, for: user})
231 def get_context(%{assigns: %{user: user}} = conn, %{"id" => id}) do
232 with %Activity{} = activity <- Repo.get(Activity, id),
234 ActivityPub.fetch_activities_for_context(activity.data["context"], %{
235 "blocking_user" => user,
239 activities |> Enum.filter(fn %{id: aid} -> to_string(aid) != to_string(id) end),
241 activities |> Enum.filter(fn %{data: %{"type" => type}} -> type == "Create" end),
242 grouped_activities <- Enum.group_by(activities, fn %{id: id} -> id < activity.id end) do
248 activities: grouped_activities[true] || [],
256 activities: grouped_activities[false] || [],
266 def post_status(%{assigns: %{user: user}} = conn, %{"status" => _} = params) do
269 |> Map.put("in_reply_to_status_id", params["in_reply_to_id"])
270 |> Map.put("no_attachment_links", true)
272 {:ok, activity} = CommonAPI.post(user, params)
273 render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity})
276 def delete_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
277 with {:ok, %Activity{}} <- CommonAPI.delete(id, user) do
283 |> json(%{error: "Can't delete this post"})
287 def reblog_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
288 with {:ok, announce, _activity} = CommonAPI.repeat(ap_id_or_id, user) do
289 render(conn, StatusView, "status.json", %{activity: announce, for: user, as: :activity})
293 def fav_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
294 with {:ok, _fav, %{data: %{"id" => id}}} = CommonAPI.favorite(ap_id_or_id, user),
295 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
296 render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity})
300 def unfav_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
301 with {:ok, %{data: %{"id" => id}}} = CommonAPI.unfavorite(ap_id_or_id, user),
302 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
303 render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity})
307 def notifications(%{assigns: %{user: user}} = conn, params) do
308 notifications = Notification.for_user(user, params)
311 Enum.map(notifications, fn x ->
312 render_notification(user, x)
317 |> add_link_headers(:notifications, notifications)
321 def get_notification(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
322 with {:ok, notification} <- Notification.get(user, id) do
323 json(conn, render_notification(user, notification))
327 |> put_resp_content_type("application/json")
328 |> send_resp(403, Jason.encode!(%{"error" => reason}))
332 def clear_notifications(%{assigns: %{user: user}} = conn, _params) do
333 Notification.clear(user)
337 def dismiss_notification(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
338 with {:ok, _notif} <- Notification.dismiss(user, id) do
343 |> put_resp_content_type("application/json")
344 |> send_resp(403, Jason.encode!(%{"error" => reason}))
348 def relationships(%{assigns: %{user: user}} = conn, %{"id" => id}) do
350 q = from(u in User, where: u.id in ^id)
351 targets = Repo.all(q)
352 render(conn, AccountView, "relationships.json", %{user: user, targets: targets})
355 def upload(%{assigns: %{user: _}} = conn, %{"file" => file}) do
356 with {:ok, object} <- ActivityPub.upload(file) do
359 |> Map.put("id", object.id)
361 render(conn, StatusView, "attachment.json", %{attachment: data})
365 def favourited_by(conn, %{"id" => id}) do
366 with %Activity{data: %{"object" => %{"likes" => likes}}} <- Repo.get(Activity, id) do
367 q = from(u in User, where: u.ap_id in ^likes)
369 render(conn, AccountView, "accounts.json", %{users: users, as: :user})
375 def reblogged_by(conn, %{"id" => id}) do
376 with %Activity{data: %{"object" => %{"announcements" => announces}}} <- Repo.get(Activity, id) do
377 q = from(u in User, where: u.ap_id in ^announces)
379 render(conn, AccountView, "accounts.json", %{users: users, as: :user})
385 def hashtag_timeline(%{assigns: %{user: user}} = conn, params) do
388 |> Map.put("type", "Create")
389 |> Map.put("local_only", !!params["local"])
390 |> Map.put("blocking_user", user)
393 ActivityPub.fetch_public_activities(params)
397 |> add_link_headers(:hashtag_timeline, activities, params["tag"])
398 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
402 def followers(conn, %{"id" => id}) do
403 with %User{} = user <- Repo.get(User, id),
404 {:ok, followers} <- User.get_followers(user) do
405 render(conn, AccountView, "accounts.json", %{users: followers, as: :user})
409 def following(conn, %{"id" => id}) do
410 with %User{} = user <- Repo.get(User, id),
411 {:ok, followers} <- User.get_friends(user) do
412 render(conn, AccountView, "accounts.json", %{users: followers, as: :user})
416 def follow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
417 with %User{} = followed <- Repo.get(User, id),
418 {:ok, follower} <- User.follow(follower, followed),
419 {:ok, _activity} <- ActivityPub.follow(follower, followed) do
420 render(conn, AccountView, "relationship.json", %{user: follower, target: followed})
424 |> put_resp_content_type("application/json")
425 |> send_resp(403, Jason.encode!(%{"error" => message}))
429 def follow(%{assigns: %{user: follower}} = conn, %{"uri" => uri}) do
430 with %User{} = followed <- Repo.get_by(User, nickname: uri),
431 {:ok, follower} <- User.follow(follower, followed),
432 {:ok, _activity} <- ActivityPub.follow(follower, followed) do
433 render(conn, AccountView, "account.json", %{user: followed})
437 |> put_resp_content_type("application/json")
438 |> send_resp(403, Jason.encode!(%{"error" => message}))
442 # TODO: Clean up and unify
443 def unfollow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
444 with %User{} = followed <- Repo.get(User, id),
445 {:ok, follower, follow_activity} <- User.unfollow(follower, followed),
447 ActivityPub.insert(%{
449 "actor" => follower.ap_id,
450 # get latest Follow for these users
451 "object" => follow_activity.data["id"]
453 render(conn, AccountView, "relationship.json", %{user: follower, target: followed})
457 def block(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
458 with %User{} = blocked <- Repo.get(User, id),
459 {:ok, blocker} <- User.block(blocker, blocked) do
460 render(conn, AccountView, "relationship.json", %{user: blocker, target: blocked})
464 |> put_resp_content_type("application/json")
465 |> send_resp(403, Jason.encode!(%{"error" => message}))
469 def unblock(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
470 with %User{} = blocked <- Repo.get(User, id),
471 {:ok, blocker} <- User.unblock(blocker, blocked) do
472 render(conn, AccountView, "relationship.json", %{user: blocker, target: blocked})
476 |> put_resp_content_type("application/json")
477 |> send_resp(403, Jason.encode!(%{"error" => message}))
481 # TODO: Use proper query
482 def blocks(%{assigns: %{user: user}} = conn, _) do
483 with blocked_users <- user.info["blocks"] || [],
484 accounts <- Enum.map(blocked_users, fn ap_id -> User.get_cached_by_ap_id(ap_id) end) do
485 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
490 def search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
491 accounts = User.search(query, params["resolve"] == "true")
494 if Regex.match?(~r/https?:/, query) do
495 with {:ok, activities} <- OStatus.fetch_activity_from_url(query) do
498 %{data: %{"type" => "Create"}} -> true
509 where: fragment("?->>'type' = 'Create'", a.data),
512 "to_tsvector('english', ?->'object'->>'content') @@ plainto_tsquery('english', ?)",
519 statuses = Repo.all(q) ++ fetched
524 |> Enum.filter(fn tag -> String.starts_with?(tag, "#") end)
525 |> Enum.map(fn tag -> String.slice(tag, 1..-1) end)
528 "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
530 StatusView.render("index.json", activities: statuses, for: user, as: :activity),
537 def account_search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
538 accounts = User.search(query, params["resolve"] == "true")
540 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
545 def favourites(%{assigns: %{user: user}} = conn, _) do
548 |> Map.put("type", "Create")
549 |> Map.put("favorited_by", user.ap_id)
550 |> Map.put("blocking_user", user)
553 ActivityPub.fetch_public_activities(params)
557 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
560 def index(%{assigns: %{user: user}} = conn, _params) do
563 |> get_session(:oauth_token)
566 mastodon_emoji = mastodonized_emoji()
567 accounts = Map.put(%{}, user.id, AccountView.render("account.json", %{user: user}))
572 streaming_api_base_url:
573 String.replace(Pleroma.Web.Endpoint.static_url(), "http", "ws"),
576 domain: Pleroma.Web.Endpoint.host(),
579 unfollow_modal: false,
582 auto_play_gif: false,
587 default_privacy: "public",
588 default_sensitive: false
590 media_attachments: %{
591 accept_content_types: [
606 settings: Map.get(user.info, "settings") || %{
635 push_subscription: nil,
637 custom_emojis: mastodon_emoji,
638 char_limit: Keyword.get(@instance, :limit)
644 |> render(MastodonView, "index.html", %{initial_state: initial_state})
647 |> redirect(to: "/web/login")
651 def put_settings(%{assigns: %{user: user}} = conn, %{"data" => settings} = _params) do
652 with new_info <- Map.put(user.info, "settings", settings),
653 change <- User.info_changeset(user, %{info: new_info}),
654 {:ok, _user} <- User.update_and_set_cache(change) do
659 |> json(%{error: inspect(e)})
663 def login(conn, _) do
665 |> render(MastodonView, "login.html", %{error: false})
668 defp get_or_make_app() do
669 with %App{} = app <- Repo.get_by(App, client_name: "Mastodon-Local") do
674 App.register_changeset(%App{}, %{
675 client_name: "Mastodon-Local",
677 scopes: "read,write,follow"
684 def login_post(conn, %{"authorization" => %{"name" => name, "password" => password}}) do
685 with %User{} = user <- User.get_cached_by_nickname(name),
686 true <- Pbkdf2.checkpw(password, user.password_hash),
687 {:ok, app} <- get_or_make_app(),
688 {:ok, auth} <- Authorization.create_authorization(app, user),
689 {:ok, token} <- Token.exchange_token(app, auth) do
691 |> put_session(:oauth_token, token.token)
692 |> redirect(to: "/web/getting-started")
696 |> render(MastodonView, "login.html", %{error: "Wrong username or password"})
700 def logout(conn, _) do
706 def relationship_noop(%{assigns: %{user: user}} = conn, %{"id" => id}) do
707 Logger.debug("Unimplemented, returning unmodified relationship")
709 with %User{} = target <- Repo.get(User, id) do
710 render(conn, AccountView, "relationship.json", %{user: user, target: target})
714 def empty_array(conn, _) do
715 Logger.debug("Unimplemented, returning an empty array")
719 def empty_object(conn, _) do
720 Logger.debug("Unimplemented, returning an empty object")
724 def render_notification(user, %{id: id, activity: activity, inserted_at: created_at} = _params) do
725 actor = User.get_cached_by_ap_id(activity.data["actor"])
728 NaiveDateTime.to_iso8601(created_at)
729 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
731 case activity.data["type"] do
736 created_at: created_at,
737 account: AccountView.render("account.json", %{user: actor}),
738 status: StatusView.render("status.json", %{activity: activity, for: user})
742 liked_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
747 created_at: created_at,
748 account: AccountView.render("account.json", %{user: actor}),
749 status: StatusView.render("status.json", %{activity: liked_activity, for: user})
753 announced_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
758 created_at: created_at,
759 account: AccountView.render("account.json", %{user: actor}),
760 status: StatusView.render("status.json", %{activity: announced_activity, for: user})
767 created_at: created_at,
768 account: AccountView.render("account.json", %{user: actor})