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.TwitterAPI.TwitterAPI
8 alias Pleroma.Web.{CommonAPI, OStatus}
9 alias Pleroma.Web.OAuth.{Authorization, Token, App}
14 def create_app(conn, params) do
15 with cs <- App.register_changeset(%App{}, params) |> IO.inspect,
16 {:ok, app} <- Repo.insert(cs) |> IO.inspect do
19 client_id: app.client_id,
20 client_secret: app.client_secret
27 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} = Repo.update(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} <- Repo.update(change) do
67 with changeset <- User.update_changeset(user, params),
68 {:ok, user} <- Repo.update(changeset) do
69 json conn, AccountView.render("account.json", %{user: user})
74 |> json(%{error: "Invalid request"})
78 def verify_credentials(%{assigns: %{user: user}} = conn, params) do
79 account = AccountView.render("account.json", %{user: user})
83 def user(conn, %{"id" => id}) do
84 with %User{} = user <- Repo.get(User, id) do
85 account = AccountView.render("account.json", %{user: user})
90 |> json(%{error: "Can't find user"})
94 @instance Application.get_env(:pleroma, :instance)
96 def masto_instance(conn, _params) do
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")
116 def custom_emojis(conn, _params) do
117 mastodon_emoji = Pleroma.Formatter.get_custom_emoji()
118 |> Enum.map(fn {shortcode, relative_url} ->
119 url = to_string URI.merge(Web.base_url(), relative_url)
121 "shortcode" => shortcode,
126 json conn, mastodon_emoji
129 defp add_link_headers(conn, method, activities) do
130 last = List.last(activities)
131 first = List.first(activities)
135 next_url = mastodon_api_url(Pleroma.Web.Endpoint, method, max_id: min)
136 prev_url = mastodon_api_url(Pleroma.Web.Endpoint, method, since_id: max)
138 |> put_resp_header("link", "<#{next_url}>; rel=\"next\", <#{prev_url}>; rel=\"prev\"")
144 def home_timeline(%{assigns: %{user: user}} = conn, params) do
146 |> Map.put("type", ["Create", "Announce"])
147 |> Map.put("blocking_user", user)
149 activities = ActivityPub.fetch_activities([user.ap_id | user.following], params)
153 |> add_link_headers(:home_timeline, activities)
154 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
157 def public_timeline(%{assigns: %{user: user}} = conn, params) do
159 |> Map.put("type", ["Create", "Announce"])
160 |> Map.put("local_only", !!params["local"])
161 |> Map.put("blocking_user", user)
163 activities = ActivityPub.fetch_public_activities(params)
167 |> add_link_headers(:public_timeline, activities)
168 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
172 def user_statuses(%{assigns: %{user: user}} = conn, params) do
173 with %User{ap_id: ap_id} <- Repo.get(User, params["id"]) do
175 |> Map.put("type", ["Create", "Announce"])
176 |> Map.put("actor_id", ap_id)
177 |> Map.put("whole_db", true)
179 activities = ActivityPub.fetch_activities([], params)
182 render conn, StatusView, "index.json", %{activities: activities, for: user, as: :activity}
186 def get_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
187 with %Activity{} = activity <- Repo.get(Activity, id) do
188 render conn, StatusView, "status.json", %{activity: activity, for: user}
192 def get_context(%{assigns: %{user: user}} = conn, %{"id" => id}) do
193 with %Activity{} = activity <- Repo.get(Activity, id),
194 activities <- ActivityPub.fetch_activities_for_context(activity.data["object"]["context"], %{"blocking_user" => user}),
195 activities <- activities |> Enum.filter(fn (%{id: aid}) -> to_string(aid) != to_string(id) end),
196 grouped_activities <- Enum.group_by(activities, fn (%{id: id}) -> id < activity.id end) do
198 ancestors: StatusView.render("index.json", for: user, activities: grouped_activities[true] || [], as: :activity) |> Enum.reverse,
199 descendants: StatusView.render("index.json", for: user, activities: grouped_activities[false] || [], as: :activity) |> Enum.reverse,
206 def post_status(%{assigns: %{user: user}} = conn, %{"status" => status} = params) do
208 |> Map.put("in_reply_to_status_id", params["in_reply_to_id"])
210 {:ok, activity} = CommonAPI.post(user, params)
211 render conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity}
214 def delete_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
215 with {:ok, %Activity{}} <- CommonAPI.delete(id, user) do
221 |> json(%{error: "Can't delete this post"})
225 def reblog_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
226 with {:ok, _announce, %{data: %{"id" => id}}} = CommonAPI.repeat(ap_id_or_id, user),
227 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
228 render conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity}
232 def fav_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
233 with {:ok, _fav, %{data: %{"id" => id}}} = CommonAPI.favorite(ap_id_or_id, user),
234 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
235 render conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity}
239 def unfav_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
240 with {:ok, %{data: %{"id" => id}}} = CommonAPI.unfavorite(ap_id_or_id, user),
241 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
242 render conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity}
246 def notifications(%{assigns: %{user: user}} = conn, params) do
247 notifications = Notification.for_user(user, params)
248 result = Enum.map(notifications, fn x ->
249 render_notification(user, x)
251 |> Enum.filter(&(&1))
254 |> add_link_headers(:notifications, notifications)
258 def get_notification(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
259 with {:ok, notification} <- Notification.get(user, id) do
260 json(conn, render_notification(user, notification))
264 |> put_resp_content_type("application/json")
265 |> send_resp(403, Poison.encode!(%{"error" => reason}))
269 def clear_notifications(%{assigns: %{user: user}} = conn, _params) do
270 Notification.clear(user)
274 def dismiss_notification(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
275 with {:ok, _notif} <- Notification.dismiss(user, id) do
280 |> put_resp_content_type("application/json")
281 |> send_resp(403, Poison.encode!(%{"error" => reason}))
285 def relationships(%{assigns: %{user: user}} = conn, %{"id" => id}) do
289 targets = Repo.all(q)
290 render conn, AccountView, "relationships.json", %{user: user, targets: targets}
293 def upload(%{assigns: %{user: user}} = conn, %{"file" => file}) do
294 with {:ok, object} <- ActivityPub.upload(file) do
296 |> Map.put("id", object.id)
298 render conn, StatusView, "attachment.json", %{attachment: data}
302 def favourited_by(conn, %{"id" => id}) do
303 with %Activity{data: %{"object" => %{"likes" => likes} = data}} <- Repo.get(Activity, id) do
305 where: u.ap_id in ^likes
307 render conn, AccountView, "accounts.json", %{users: users, as: :user}
313 def reblogged_by(conn, %{"id" => id}) do
314 with %Activity{data: %{"object" => %{"announcements" => announces}}} <- Repo.get(Activity, id) do
316 where: u.ap_id in ^announces
318 render conn, AccountView, "accounts.json", %{users: users, as: :user}
325 def hashtag_timeline(%{assigns: %{user: user}} = conn, params) do
327 |> Map.put("type", "Create")
328 |> Map.put("local_only", !!params["local"])
329 |> Map.put("blocking_user", user)
331 activities = ActivityPub.fetch_public_activities(params)
335 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
339 def followers(conn, %{"id" => id}) do
340 with %User{} = user <- Repo.get(User, id),
341 {:ok, followers} <- User.get_followers(user) do
342 render conn, AccountView, "accounts.json", %{users: followers, as: :user}
346 def following(conn, %{"id" => id}) do
347 with %User{} = user <- Repo.get(User, id),
348 {:ok, followers} <- User.get_friends(user) do
349 render conn, AccountView, "accounts.json", %{users: followers, as: :user}
353 def follow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
354 with %User{} = followed <- Repo.get(User, id),
355 {:ok, follower} <- User.follow(follower, followed),
356 {:ok, activity} <- ActivityPub.follow(follower, followed) do
357 render conn, AccountView, "relationship.json", %{user: follower, target: followed}
359 {:error, message} = err ->
361 |> put_resp_content_type("application/json")
362 |> send_resp(403, Poison.encode!(%{"error" => message}))
366 def follow(%{assigns: %{user: follower}} = conn, %{"uri" => uri}) do
367 with %User{} = followed <- Repo.get_by(User, nickname: uri),
368 {:ok, follower} <- User.follow(follower, followed),
369 {:ok, activity} <- ActivityPub.follow(follower, followed) do
370 render conn, AccountView, "account.json", %{user: followed}
372 {:error, message} = err ->
374 |> put_resp_content_type("application/json")
375 |> send_resp(403, Poison.encode!(%{"error" => message}))
379 # TODO: Clean up and unify
380 def unfollow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
381 with %User{} = followed <- Repo.get(User, id),
382 { :ok, follower, follow_activity } <- User.unfollow(follower, followed),
383 { :ok, _activity } <- ActivityPub.insert(%{
385 "actor" => follower.ap_id,
386 "object" => follow_activity.data["id"] # get latest Follow for these users
388 render conn, AccountView, "relationship.json", %{user: follower, target: followed}
392 def block(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
393 with %User{} = blocked <- Repo.get(User, id),
394 {:ok, blocker} <- User.block(blocker, blocked) do
395 render conn, AccountView, "relationship.json", %{user: blocker, target: blocked}
397 {:error, message} = err ->
399 |> put_resp_content_type("application/json")
400 |> send_resp(403, Poison.encode!(%{"error" => message}))
404 def unblock(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
405 with %User{} = blocked <- Repo.get(User, id),
406 {:ok, blocker} <- User.unblock(blocker, blocked) do
407 render conn, AccountView, "relationship.json", %{user: blocker, target: blocked}
409 {:error, message} = err ->
411 |> put_resp_content_type("application/json")
412 |> send_resp(403, Poison.encode!(%{"error" => message}))
416 # TODO: Use proper query
417 def blocks(%{assigns: %{user: user}} = conn, _) do
418 with blocked_users <- user.info["blocks"] || [],
419 accounts <- Enum.map(blocked_users, fn (ap_id) -> User.get_cached_by_ap_id(ap_id) end) do
420 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
425 def search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
426 accounts = User.search(query, params["resolve"] == "true")
428 fetched = if Regex.match?(~r/https?:/, query) do
429 with {:ok, activities} <- OStatus.fetch_activity_from_url(query) do
436 q = from a in Activity,
437 where: fragment("?->>'type' = 'Create'", a.data),
438 where: fragment("to_tsvector('english', ?->'object'->>'content') @@ plainto_tsquery('english', ?)", a.data, ^query),
440 statuses = Repo.all(q) ++ fetched
443 "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
444 "statuses" => StatusView.render("index.json", activities: statuses, for: user, as: :activity),
451 def account_search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
452 accounts = User.search(query, params["resolve"] == "true")
454 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
459 def favourites(%{assigns: %{user: user}} = conn, params) do
461 |> Map.put("type", "Create")
462 |> Map.put("favorited_by", user.ap_id)
463 |> Map.put("blocking_user", user)
465 activities = ActivityPub.fetch_activities([], params)
469 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
472 def index(%{assigns: %{user: user}} = conn, _params) do
474 |> get_session(:oauth_token)
477 accounts = Map.put(%{}, user.id, AccountView.render("account.json", %{user: user}))
480 streaming_api_base_url: String.replace(Pleroma.Web.Endpoint.static_url(), "http", "ws"),
483 domain: Pleroma.Web.Endpoint.host(),
486 unfollow_modal: false,
489 auto_play_gif: false,
494 default_privacy: "public",
495 default_sensitive: false
497 media_attachments: %{
498 accept_content_types: [
542 push_subscription: nil,
548 |> render(MastodonView, "index.html", %{initial_state: initial_state})
551 |> redirect(to: "/web/login")
555 def login(conn, params) do
557 |> render(MastodonView, "login.html")
560 defp get_or_make_app() do
561 with %App{} = app <- Repo.get_by(App, client_name: "Mastodon-Local") do
565 cs = App.register_changeset(%App{}, %{client_name: "Mastodon-Local", redirect_uris: ".", scopes: "read,write,follow"})
570 def login_post(conn, %{"authorization" => %{ "name" => name, "password" => password}}) do
571 with %User{} = user <- User.get_cached_by_nickname(name),
572 true <- Pbkdf2.checkpw(password, user.password_hash),
573 {:ok, app} <- get_or_make_app(),
574 {:ok, auth} <- Authorization.create_authorization(app, user),
575 {:ok, token} <- Token.exchange_token(app, auth) do
577 |> put_session(:oauth_token, token.token)
578 |> redirect(to: "/web/timelines/public")
582 def relationship_noop(%{assigns: %{user: user}} = conn, %{"id" => id}) do
583 Logger.debug("Unimplemented, returning unmodified relationship")
584 with %User{} = target <- Repo.get(User, id) do
585 render conn, AccountView, "relationship.json", %{user: user, target: target}
589 def empty_array(conn, _) do
590 Logger.debug("Unimplemented, returning an empty array")
594 defp render_notification(user, %{id: id, activity: activity, inserted_at: created_at} = _params) do
595 actor = User.get_cached_by_ap_id(activity.data["actor"])
596 created_at = NaiveDateTime.to_iso8601(created_at)
597 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
598 case activity.data["type"] do
600 %{id: id, type: "mention", created_at: created_at, account: AccountView.render("account.json", %{user: actor}), status: StatusView.render("status.json", %{activity: activity, for: user})}
602 liked_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
603 %{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})}
605 announced_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
606 %{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})}
608 %{id: id, type: "follow", created_at: created_at, account: AccountView.render("account.json", %{user: actor})}