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
28 params = if bio = params["note"] do
29 Map.put(params, "bio", bio)
34 params = if name = params["display_name"] do
35 Map.put(params, "name", name)
40 user = if avatar = params["avatar"] do
41 with %Plug.Upload{} <- avatar,
42 {:ok, object} <- ActivityPub.upload(avatar),
43 change = Ecto.Changeset.change(user, %{avatar: object.data}),
44 {:ok, user} = User.update_and_set_cache(change) do
53 user = if banner = params["header"] do
54 with %Plug.Upload{} <- banner,
55 {:ok, object} <- ActivityPub.upload(banner),
56 new_info <- Map.put(user.info, "banner", object.data),
57 change <- User.info_changeset(user, %{info: new_info}),
58 {:ok, user} <- User.update_and_set_cache(change) do
67 with changeset <- User.update_changeset(user, params),
68 {:ok, user} <- User.update_and_set_cache(changeset) do
69 if original_user != user do
70 CommonAPI.update(user)
72 json conn, AccountView.render("account.json", %{user: user})
77 |> json(%{error: "Invalid request"})
81 def verify_credentials(%{assigns: %{user: user}} = conn, _) do
82 account = AccountView.render("account.json", %{user: user})
86 def user(conn, %{"id" => id}) do
87 with %User{} = user <- Repo.get(User, id) do
88 account = AccountView.render("account.json", %{user: user})
93 |> json(%{error: "Can't find user"})
97 @instance Application.get_env(:pleroma, :instance)
99 def masto_instance(conn, _params) do
102 title: Keyword.get(@instance, :name),
103 description: "A Pleroma instance, an alternative fediverse server",
104 version: Keyword.get(@instance, :version),
105 email: Keyword.get(@instance, :email),
107 streaming_api: String.replace(Web.base_url, ["http","https"], "wss")
109 stats: Stats.get_stats,
110 thumbnail: Web.base_url <> "/instance/thumbnail.jpeg",
111 max_toot_chars: Keyword.get(@instance, :limit)
117 def peers(conn, _params) do
118 json(conn, Stats.get_peers)
121 defp mastodonized_emoji do
122 Pleroma.Formatter.get_custom_emoji()
123 |> Enum.map(fn {shortcode, relative_url} ->
124 url = to_string URI.merge(Web.base_url(), relative_url)
126 "shortcode" => shortcode,
133 def custom_emojis(conn, _params) do
134 mastodon_emoji = mastodonized_emoji()
135 json conn, mastodon_emoji
138 defp add_link_headers(conn, method, activities, param \\ false) do
139 last = List.last(activities)
140 first = List.first(activities)
144 {next_url, prev_url} = if param do
146 mastodon_api_url(Pleroma.Web.Endpoint, method, param, max_id: min),
147 mastodon_api_url(Pleroma.Web.Endpoint, method, param, since_id: max)
151 mastodon_api_url(Pleroma.Web.Endpoint, method, max_id: min),
152 mastodon_api_url(Pleroma.Web.Endpoint, method, since_id: max)
156 |> put_resp_header("link", "<#{next_url}>; rel=\"next\", <#{prev_url}>; rel=\"prev\"")
162 def home_timeline(%{assigns: %{user: user}} = conn, params) do
164 |> Map.put("type", ["Create", "Announce"])
165 |> Map.put("blocking_user", user)
166 |> Map.put("user", user)
168 activities = ActivityPub.fetch_activities([user.ap_id | user.following], params)
172 |> add_link_headers(:home_timeline, activities)
173 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
176 def public_timeline(%{assigns: %{user: user}} = conn, params) do
178 |> Map.put("type", ["Create", "Announce"])
179 |> Map.put("local_only", params["local"] in [true, "True", "true", "1"])
180 |> Map.put("blocking_user", user)
182 activities = ActivityPub.fetch_public_activities(params)
186 |> add_link_headers(:public_timeline, activities)
187 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
190 def user_statuses(%{assigns: %{user: user}} = conn, params) do
191 with %User{ap_id: ap_id} <- Repo.get(User, params["id"]) do
193 |> Map.put("type", ["Create", "Announce"])
194 |> Map.put("actor_id", ap_id)
195 |> Map.put("whole_db", true)
197 activities = ActivityPub.fetch_public_activities(params)
201 |> add_link_headers(:user_statuses, activities, params["id"])
202 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
206 def get_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
207 with %Activity{} = activity <- Repo.get(Activity, id),
208 true <- ActivityPub.visible_for_user?(activity, user) do
209 render conn, StatusView, "status.json", %{activity: activity, for: user}
213 def get_context(%{assigns: %{user: user}} = conn, %{"id" => id}) do
214 with %Activity{} = activity <- Repo.get(Activity, id),
215 activities <- ActivityPub.fetch_activities_for_context(activity.data["context"], %{"blocking_user" => user, "user" => user}),
216 activities <- activities |> Enum.filter(fn (%{id: aid}) -> to_string(aid) != to_string(id) end),
217 activities <- activities |> Enum.filter(fn (%{data: %{"type" => type}}) -> type == "Create" end),
218 grouped_activities <- Enum.group_by(activities, fn (%{id: id}) -> id < activity.id end) do
220 ancestors: StatusView.render("index.json", for: user, activities: grouped_activities[true] || [], as: :activity) |> Enum.reverse,
221 descendants: StatusView.render("index.json", for: user, activities: grouped_activities[false] || [], as: :activity) |> Enum.reverse,
228 def post_status(%{assigns: %{user: user}} = conn, %{"status" => _} = params) do
230 |> Map.put("in_reply_to_status_id", params["in_reply_to_id"])
231 |> Map.put("no_attachment_links", true)
233 {:ok, activity} = CommonAPI.post(user, params)
234 render conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity}
237 def delete_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
238 with {:ok, %Activity{}} <- CommonAPI.delete(id, user) do
244 |> json(%{error: "Can't delete this post"})
248 def reblog_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
249 with {:ok, announce, _activity} = CommonAPI.repeat(ap_id_or_id, user) do
250 render conn, StatusView, "status.json", %{activity: announce, for: user, as: :activity}
254 def fav_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
255 with {:ok, _fav, %{data: %{"id" => id}}} = CommonAPI.favorite(ap_id_or_id, user),
256 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
257 render conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity}
261 def unfav_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
262 with {:ok, %{data: %{"id" => id}}} = CommonAPI.unfavorite(ap_id_or_id, user),
263 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
264 render conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity}
268 def notifications(%{assigns: %{user: user}} = conn, params) do
269 notifications = Notification.for_user(user, params)
270 result = Enum.map(notifications, fn x ->
271 render_notification(user, x)
273 |> Enum.filter(&(&1))
276 |> add_link_headers(:notifications, notifications)
280 def get_notification(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
281 with {:ok, notification} <- Notification.get(user, id) do
282 json(conn, render_notification(user, notification))
286 |> put_resp_content_type("application/json")
287 |> send_resp(403, Poison.encode!(%{"error" => reason}))
291 def clear_notifications(%{assigns: %{user: user}} = conn, _params) do
292 Notification.clear(user)
296 def dismiss_notification(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
297 with {:ok, _notif} <- Notification.dismiss(user, id) do
302 |> put_resp_content_type("application/json")
303 |> send_resp(403, Poison.encode!(%{"error" => reason}))
307 def relationships(%{assigns: %{user: user}} = conn, %{"id" => id}) do
311 targets = Repo.all(q)
312 render conn, AccountView, "relationships.json", %{user: user, targets: targets}
315 def upload(%{assigns: %{user: _}} = conn, %{"file" => file}) do
316 with {:ok, object} <- ActivityPub.upload(file) do
318 |> Map.put("id", object.id)
320 render conn, StatusView, "attachment.json", %{attachment: data}
324 def favourited_by(conn, %{"id" => id}) do
325 with %Activity{data: %{"object" => %{"likes" => likes}}} <- Repo.get(Activity, id) do
327 where: u.ap_id in ^likes
329 render conn, AccountView, "accounts.json", %{users: users, as: :user}
335 def reblogged_by(conn, %{"id" => id}) do
336 with %Activity{data: %{"object" => %{"announcements" => announces}}} <- Repo.get(Activity, id) do
338 where: u.ap_id in ^announces
340 render conn, AccountView, "accounts.json", %{users: users, as: :user}
346 def hashtag_timeline(%{assigns: %{user: user}} = conn, params) do
348 |> Map.put("type", "Create")
349 |> Map.put("local_only", !!params["local"])
350 |> Map.put("blocking_user", user)
352 activities = ActivityPub.fetch_public_activities(params)
356 |> add_link_headers(:hashtag_timeline, activities, params["tag"])
357 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
361 def followers(conn, %{"id" => id}) do
362 with %User{} = user <- Repo.get(User, id),
363 {:ok, followers} <- User.get_followers(user) do
364 render conn, AccountView, "accounts.json", %{users: followers, as: :user}
368 def following(conn, %{"id" => id}) do
369 with %User{} = user <- Repo.get(User, id),
370 {:ok, followers} <- User.get_friends(user) do
371 render conn, AccountView, "accounts.json", %{users: followers, as: :user}
375 def follow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
376 with %User{} = followed <- Repo.get(User, id),
377 {:ok, follower} <- User.follow(follower, followed),
378 {:ok, _activity} <- ActivityPub.follow(follower, followed) do
379 render conn, AccountView, "relationship.json", %{user: follower, target: followed}
383 |> put_resp_content_type("application/json")
384 |> send_resp(403, Poison.encode!(%{"error" => message}))
388 def follow(%{assigns: %{user: follower}} = conn, %{"uri" => uri}) do
389 with %User{} = followed <- Repo.get_by(User, nickname: uri),
390 {:ok, follower} <- User.follow(follower, followed),
391 {:ok, _activity} <- ActivityPub.follow(follower, followed) do
392 render conn, AccountView, "account.json", %{user: followed}
396 |> put_resp_content_type("application/json")
397 |> send_resp(403, Poison.encode!(%{"error" => message}))
401 # TODO: Clean up and unify
402 def unfollow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
403 with %User{} = followed <- Repo.get(User, id),
404 { :ok, follower, follow_activity } <- User.unfollow(follower, followed),
405 { :ok, _activity } <- ActivityPub.insert(%{
407 "actor" => follower.ap_id,
408 "object" => follow_activity.data["id"] # get latest Follow for these users
410 render conn, AccountView, "relationship.json", %{user: follower, target: followed}
414 def block(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
415 with %User{} = blocked <- Repo.get(User, id),
416 {:ok, blocker} <- User.block(blocker, blocked) do
417 render conn, AccountView, "relationship.json", %{user: blocker, target: blocked}
421 |> put_resp_content_type("application/json")
422 |> send_resp(403, Poison.encode!(%{"error" => message}))
426 def unblock(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
427 with %User{} = blocked <- Repo.get(User, id),
428 {:ok, blocker} <- User.unblock(blocker, blocked) do
429 render conn, AccountView, "relationship.json", %{user: blocker, target: blocked}
433 |> put_resp_content_type("application/json")
434 |> send_resp(403, Poison.encode!(%{"error" => message}))
438 # TODO: Use proper query
439 def blocks(%{assigns: %{user: user}} = conn, _) do
440 with blocked_users <- user.info["blocks"] || [],
441 accounts <- Enum.map(blocked_users, fn (ap_id) -> User.get_cached_by_ap_id(ap_id) end) do
442 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
447 def search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
448 accounts = User.search(query, params["resolve"] == "true")
450 fetched = if Regex.match?(~r/https?:/, query) do
451 with {:ok, activities} <- OStatus.fetch_activity_from_url(query) do
458 q = from a in Activity,
459 where: fragment("?->>'type' = 'Create'", a.data),
460 where: fragment("to_tsvector('english', ?->'object'->>'content') @@ plainto_tsquery('english', ?)", a.data, ^query),
462 statuses = Repo.all(q) ++ fetched
465 "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
466 "statuses" => StatusView.render("index.json", activities: statuses, for: user, as: :activity),
473 def account_search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
474 accounts = User.search(query, params["resolve"] == "true")
476 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
481 def favourites(%{assigns: %{user: user}} = conn, _) do
483 |> Map.put("type", "Create")
484 |> Map.put("favorited_by", user.ap_id)
485 |> Map.put("blocking_user", user)
487 activities = ActivityPub.fetch_public_activities(params)
491 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
494 def index(%{assigns: %{user: user}} = conn, _params) do
496 |> get_session(:oauth_token)
499 mastodon_emoji = mastodonized_emoji()
500 accounts = Map.put(%{}, user.id, AccountView.render("account.json", %{user: user}))
503 streaming_api_base_url: String.replace(Pleroma.Web.Endpoint.static_url(), "http", "ws"),
506 domain: Pleroma.Web.Endpoint.host(),
509 unfollow_modal: false,
512 auto_play_gif: false,
517 default_privacy: "public",
518 default_sensitive: false
520 media_attachments: %{
521 accept_content_types: [
565 push_subscription: nil,
567 custom_emojis: mastodon_emoji
571 |> render(MastodonView, "index.html", %{initial_state: initial_state})
574 |> redirect(to: "/web/login")
578 def login(conn, _) do
580 |> render(MastodonView, "login.html", %{error: false})
583 defp get_or_make_app() do
584 with %App{} = app <- Repo.get_by(App, client_name: "Mastodon-Local") do
588 cs = App.register_changeset(%App{}, %{client_name: "Mastodon-Local", redirect_uris: ".", scopes: "read,write,follow"})
593 def login_post(conn, %{"authorization" => %{ "name" => name, "password" => password}}) do
594 with %User{} = user <- User.get_cached_by_nickname(name),
595 true <- Pbkdf2.checkpw(password, user.password_hash),
596 {:ok, app} <- get_or_make_app(),
597 {:ok, auth} <- Authorization.create_authorization(app, user),
598 {:ok, token} <- Token.exchange_token(app, auth) do
600 |> put_session(:oauth_token, token.token)
601 |> redirect(to: "/web/getting-started")
605 |> render(MastodonView, "login.html", %{error: "Wrong username or password"})
609 def logout(conn, _) do
615 def relationship_noop(%{assigns: %{user: user}} = conn, %{"id" => id}) do
616 Logger.debug("Unimplemented, returning unmodified relationship")
617 with %User{} = target <- Repo.get(User, id) do
618 render conn, AccountView, "relationship.json", %{user: user, target: target}
622 def empty_array(conn, _) do
623 Logger.debug("Unimplemented, returning an empty array")
627 def empty_object(conn, _) do
628 Logger.debug("Unimplemented, returning an empty object")
632 def render_notification(user, %{id: id, activity: activity, inserted_at: created_at} = _params) do
633 actor = User.get_cached_by_ap_id(activity.data["actor"])
634 created_at = NaiveDateTime.to_iso8601(created_at)
635 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
636 case activity.data["type"] do
638 %{id: id, type: "mention", created_at: created_at, account: AccountView.render("account.json", %{user: actor}), status: StatusView.render("status.json", %{activity: activity, for: user})}
640 liked_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
641 %{id: id, type: "favourite", created_at: created_at, account: AccountView.render("account.json", %{user: actor}), status: StatusView.render("status.json", %{activity: liked_activity, for: user})}
643 announced_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
644 %{id: id, type: "reblog", created_at: created_at, account: AccountView.render("account.json", %{user: actor}), status: StatusView.render("status.json", %{activity: announced_activity, for: user})}
646 %{id: id, type: "follow", created_at: created_at, account: AccountView.render("account.json", %{user: actor})}