1 defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do
2 use Pleroma.Web, :controller
3 alias Pleroma.{Repo, Activity, User, Notification}
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
27 params = if bio = params["note"] do
28 Map.put(params, "bio", bio)
33 params = if name = params["display_name"] do
34 Map.put(params, "name", name)
39 user = if avatar = params["avatar"] do
40 with %Plug.Upload{} <- avatar,
41 {:ok, object} <- ActivityPub.upload(avatar),
42 change = Ecto.Changeset.change(user, %{avatar: object.data}),
43 {:ok, user} = Repo.update(change) do
52 user = if banner = params["header"] do
53 with %Plug.Upload{} <- banner,
54 {:ok, object} <- ActivityPub.upload(banner),
55 new_info <- Map.put(user.info, "banner", object.data),
56 change <- User.info_changeset(user, %{info: new_info}),
57 {:ok, user} <- Repo.update(change) do
66 with changeset <- User.update_changeset(user, params),
67 {:ok, user} <- Repo.update(changeset) do
68 json conn, AccountView.render("account.json", %{user: user})
73 |> json(%{error: "Invalid request"})
77 def verify_credentials(%{assigns: %{user: user}} = conn, _) do
78 account = AccountView.render("account.json", %{user: user})
82 def user(conn, %{"id" => id}) do
83 with %User{} = user <- Repo.get(User, id) do
84 account = AccountView.render("account.json", %{user: user})
89 |> json(%{error: "Can't find user"})
93 @instance Application.get_env(:pleroma, :instance)
95 def masto_instance(conn, _params) do
96 user_count = Repo.aggregate(User.local_user_query, :count, :id)
99 title: Keyword.get(@instance, :name),
100 description: "A Pleroma instance, an alternative fediverse server",
101 version: Keyword.get(@instance, :version),
102 email: Keyword.get(@instance, :email),
104 streaming_api: String.replace(Web.base_url, ["http","https"], "wss")
108 user_count: user_count,
111 max_toot_chars: Keyword.get(@instance, :limit)
117 defp mastodonized_emoji do
118 Pleroma.Formatter.get_custom_emoji()
119 |> Enum.map(fn {shortcode, relative_url} ->
120 url = to_string URI.merge(Web.base_url(), relative_url)
122 "shortcode" => shortcode,
129 def custom_emojis(conn, _params) do
130 mastodon_emoji = mastodonized_emoji()
131 json conn, mastodon_emoji
134 defp add_link_headers(conn, method, activities) do
135 last = List.last(activities)
136 first = List.first(activities)
140 next_url = mastodon_api_url(Pleroma.Web.Endpoint, method, max_id: min)
141 prev_url = mastodon_api_url(Pleroma.Web.Endpoint, method, since_id: max)
143 |> put_resp_header("link", "<#{next_url}>; rel=\"next\", <#{prev_url}>; rel=\"prev\"")
149 def home_timeline(%{assigns: %{user: user}} = conn, params) do
151 |> Map.put("type", ["Create", "Announce"])
152 |> Map.put("blocking_user", user)
154 activities = ActivityPub.fetch_activities([user.ap_id | user.following], params)
158 |> add_link_headers(:home_timeline, activities)
159 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
162 def public_timeline(%{assigns: %{user: user}} = conn, params) do
164 |> Map.put("type", ["Create", "Announce"])
165 |> Map.put("local_only", params["local"] in [true, "True", "true"])
166 |> Map.put("blocking_user", user)
168 activities = ActivityPub.fetch_public_activities(params)
172 |> add_link_headers(:public_timeline, activities)
173 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
177 def user_statuses(%{assigns: %{user: user}} = conn, params) do
178 with %User{ap_id: ap_id} <- Repo.get(User, params["id"]) do
180 |> Map.put("type", ["Create", "Announce"])
181 |> Map.put("actor_id", ap_id)
182 |> Map.put("whole_db", true)
184 activities = ActivityPub.fetch_activities([], params)
187 render conn, StatusView, "index.json", %{activities: activities, for: user, as: :activity}
191 def get_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
192 with %Activity{} = activity <- Repo.get(Activity, id) do
193 render conn, StatusView, "status.json", %{activity: activity, for: user}
197 def get_context(%{assigns: %{user: user}} = conn, %{"id" => id}) do
198 with %Activity{} = activity <- Repo.get(Activity, id),
199 activities <- ActivityPub.fetch_activities_for_context(activity.data["object"]["context"], %{"blocking_user" => user}),
200 activities <- activities |> Enum.filter(fn (%{id: aid}) -> to_string(aid) != to_string(id) end),
201 activities <- activities |> Enum.filter(fn (%{data: %{"type" => type}}) -> type == "Create" end),
202 grouped_activities <- Enum.group_by(activities, fn (%{id: id}) -> id < activity.id end) do
204 ancestors: StatusView.render("index.json", for: user, activities: grouped_activities[true] || [], as: :activity) |> Enum.reverse,
205 descendants: StatusView.render("index.json", for: user, activities: grouped_activities[false] || [], as: :activity) |> Enum.reverse,
212 def post_status(%{assigns: %{user: user}} = conn, %{"status" => _} = params) do
214 |> Map.put("in_reply_to_status_id", params["in_reply_to_id"])
215 |> Map.put("no_attachment_links", true)
217 {:ok, activity} = CommonAPI.post(user, params)
218 render conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity}
221 def delete_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
222 with {:ok, %Activity{}} <- CommonAPI.delete(id, user) do
228 |> json(%{error: "Can't delete this post"})
232 def reblog_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
233 with {:ok, announce, _activity} = CommonAPI.repeat(ap_id_or_id, user) do
234 render conn, StatusView, "status.json", %{activity: announce, for: user, as: :activity}
238 def fav_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
239 with {:ok, _fav, %{data: %{"id" => id}}} = CommonAPI.favorite(ap_id_or_id, user),
240 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
241 render conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity}
245 def unfav_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
246 with {:ok, %{data: %{"id" => id}}} = CommonAPI.unfavorite(ap_id_or_id, user),
247 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
248 render conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity}
252 def notifications(%{assigns: %{user: user}} = conn, params) do
253 notifications = Notification.for_user(user, params)
254 result = Enum.map(notifications, fn x ->
255 render_notification(user, x)
257 |> Enum.filter(&(&1))
260 |> add_link_headers(:notifications, notifications)
264 def get_notification(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
265 with {:ok, notification} <- Notification.get(user, id) do
266 json(conn, render_notification(user, notification))
270 |> put_resp_content_type("application/json")
271 |> send_resp(403, Poison.encode!(%{"error" => reason}))
275 def clear_notifications(%{assigns: %{user: user}} = conn, _params) do
276 Notification.clear(user)
280 def dismiss_notification(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
281 with {:ok, _notif} <- Notification.dismiss(user, id) do
286 |> put_resp_content_type("application/json")
287 |> send_resp(403, Poison.encode!(%{"error" => reason}))
291 def relationships(%{assigns: %{user: user}} = conn, %{"id" => id}) do
295 targets = Repo.all(q)
296 render conn, AccountView, "relationships.json", %{user: user, targets: targets}
299 def upload(%{assigns: %{user: _}} = conn, %{"file" => file}) do
300 with {:ok, object} <- ActivityPub.upload(file) do
302 |> Map.put("id", object.id)
304 render conn, StatusView, "attachment.json", %{attachment: data}
308 def favourited_by(conn, %{"id" => id}) do
309 with %Activity{data: %{"object" => %{"likes" => likes}}} <- Repo.get(Activity, id) do
311 where: u.ap_id in ^likes
313 render conn, AccountView, "accounts.json", %{users: users, as: :user}
319 def reblogged_by(conn, %{"id" => id}) do
320 with %Activity{data: %{"object" => %{"announcements" => announces}}} <- Repo.get(Activity, id) do
322 where: u.ap_id in ^announces
324 render conn, AccountView, "accounts.json", %{users: users, as: :user}
331 def hashtag_timeline(%{assigns: %{user: user}} = conn, params) do
333 |> Map.put("type", "Create")
334 |> Map.put("local_only", !!params["local"])
335 |> Map.put("blocking_user", user)
337 activities = ActivityPub.fetch_public_activities(params)
341 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
345 def followers(conn, %{"id" => id}) do
346 with %User{} = user <- Repo.get(User, id),
347 {:ok, followers} <- User.get_followers(user) do
348 render conn, AccountView, "accounts.json", %{users: followers, as: :user}
352 def following(conn, %{"id" => id}) do
353 with %User{} = user <- Repo.get(User, id),
354 {:ok, followers} <- User.get_friends(user) do
355 render conn, AccountView, "accounts.json", %{users: followers, as: :user}
359 def follow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
360 with %User{} = followed <- Repo.get(User, id),
361 {:ok, follower} <- User.follow(follower, followed),
362 {:ok, _activity} <- ActivityPub.follow(follower, followed) do
363 render conn, AccountView, "relationship.json", %{user: follower, target: followed}
367 |> put_resp_content_type("application/json")
368 |> send_resp(403, Poison.encode!(%{"error" => message}))
372 def follow(%{assigns: %{user: follower}} = conn, %{"uri" => uri}) do
373 with %User{} = followed <- Repo.get_by(User, nickname: uri),
374 {:ok, follower} <- User.follow(follower, followed),
375 {:ok, _activity} <- ActivityPub.follow(follower, followed) do
376 render conn, AccountView, "account.json", %{user: followed}
380 |> put_resp_content_type("application/json")
381 |> send_resp(403, Poison.encode!(%{"error" => message}))
385 # TODO: Clean up and unify
386 def unfollow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
387 with %User{} = followed <- Repo.get(User, id),
388 { :ok, follower, follow_activity } <- User.unfollow(follower, followed),
389 { :ok, _activity } <- ActivityPub.insert(%{
391 "actor" => follower.ap_id,
392 "object" => follow_activity.data["id"] # get latest Follow for these users
394 render conn, AccountView, "relationship.json", %{user: follower, target: followed}
398 def block(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
399 with %User{} = blocked <- Repo.get(User, id),
400 {:ok, blocker} <- User.block(blocker, blocked) do
401 render conn, AccountView, "relationship.json", %{user: blocker, target: blocked}
405 |> put_resp_content_type("application/json")
406 |> send_resp(403, Poison.encode!(%{"error" => message}))
410 def unblock(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
411 with %User{} = blocked <- Repo.get(User, id),
412 {:ok, blocker} <- User.unblock(blocker, blocked) do
413 render conn, AccountView, "relationship.json", %{user: blocker, target: blocked}
417 |> put_resp_content_type("application/json")
418 |> send_resp(403, Poison.encode!(%{"error" => message}))
422 # TODO: Use proper query
423 def blocks(%{assigns: %{user: user}} = conn, _) do
424 with blocked_users <- user.info["blocks"] || [],
425 accounts <- Enum.map(blocked_users, fn (ap_id) -> User.get_cached_by_ap_id(ap_id) end) do
426 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
431 def search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
432 accounts = User.search(query, params["resolve"] == "true")
434 fetched = if Regex.match?(~r/https?:/, query) do
435 with {:ok, activities} <- OStatus.fetch_activity_from_url(query) do
442 q = from a in Activity,
443 where: fragment("?->>'type' = 'Create'", a.data),
444 where: fragment("to_tsvector('english', ?->'object'->>'content') @@ plainto_tsquery('english', ?)", a.data, ^query),
446 statuses = Repo.all(q) ++ fetched
449 "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
450 "statuses" => StatusView.render("index.json", activities: statuses, for: user, as: :activity),
457 def account_search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
458 accounts = User.search(query, params["resolve"] == "true")
460 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
465 def favourites(%{assigns: %{user: user}} = conn, _) do
467 |> Map.put("type", "Create")
468 |> Map.put("favorited_by", user.ap_id)
469 |> Map.put("blocking_user", user)
471 activities = ActivityPub.fetch_activities([], params)
475 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
478 def index(%{assigns: %{user: user}} = conn, _params) do
480 |> get_session(:oauth_token)
483 mastodon_emoji = mastodonized_emoji()
484 accounts = Map.put(%{}, user.id, AccountView.render("account.json", %{user: user}))
487 streaming_api_base_url: String.replace(Pleroma.Web.Endpoint.static_url(), "http", "ws"),
490 domain: Pleroma.Web.Endpoint.host(),
493 unfollow_modal: false,
496 auto_play_gif: false,
501 default_privacy: "public",
502 default_sensitive: false
504 media_attachments: %{
505 accept_content_types: [
549 push_subscription: nil,
551 custom_emojis: mastodon_emoji
555 |> render(MastodonView, "index.html", %{initial_state: initial_state})
558 |> redirect(to: "/web/login")
562 def login(conn, _) do
564 |> render(MastodonView, "login.html", %{error: false})
567 defp get_or_make_app() do
568 with %App{} = app <- Repo.get_by(App, client_name: "Mastodon-Local") do
572 cs = App.register_changeset(%App{}, %{client_name: "Mastodon-Local", redirect_uris: ".", scopes: "read,write,follow"})
577 def login_post(conn, %{"authorization" => %{ "name" => name, "password" => password}}) do
578 with %User{} = user <- User.get_cached_by_nickname(name),
579 true <- Pbkdf2.checkpw(password, user.password_hash),
580 {:ok, app} <- get_or_make_app(),
581 {:ok, auth} <- Authorization.create_authorization(app, user),
582 {:ok, token} <- Token.exchange_token(app, auth) do
584 |> put_session(:oauth_token, token.token)
585 |> redirect(to: "/web/getting-started")
589 |> render(MastodonView, "login.html", %{error: "Wrong username or password"})
593 def logout(conn, _) do
599 def relationship_noop(%{assigns: %{user: user}} = conn, %{"id" => id}) do
600 Logger.debug("Unimplemented, returning unmodified relationship")
601 with %User{} = target <- Repo.get(User, id) do
602 render conn, AccountView, "relationship.json", %{user: user, target: target}
606 def empty_array(conn, _) do
607 Logger.debug("Unimplemented, returning an empty array")
611 def render_notification(user, %{id: id, activity: activity, inserted_at: created_at} = _params) do
612 actor = User.get_cached_by_ap_id(activity.data["actor"])
613 created_at = NaiveDateTime.to_iso8601(created_at)
614 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
615 case activity.data["type"] do
617 %{id: id, type: "mention", created_at: created_at, account: AccountView.render("account.json", %{user: actor}), status: StatusView.render("status.json", %{activity: activity, for: user})}
619 liked_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
620 %{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})}
622 announced_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
623 %{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})}
625 %{id: id, type: "follow", created_at: created_at, account: AccountView.render("account.json", %{user: actor})}