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
98 title: Keyword.get(@instance, :name),
99 description: "A Pleroma instance, an alternative fediverse server",
100 version: Keyword.get(@instance, :version),
101 email: Keyword.get(@instance, :email),
103 streaming_api: String.replace(Web.base_url, ["http","https"], "wss")
115 defp mastodonized_emoji do
116 Pleroma.Formatter.get_custom_emoji()
117 |> Enum.map(fn {shortcode, relative_url} ->
118 url = to_string URI.merge(Web.base_url(), relative_url)
120 "shortcode" => shortcode,
127 def custom_emojis(conn, _params) do
128 mastodon_emoji = mastodonized_emoji()
129 json conn, mastodon_emoji
132 defp add_link_headers(conn, method, activities) do
133 last = List.last(activities)
134 first = List.first(activities)
138 next_url = mastodon_api_url(Pleroma.Web.Endpoint, method, max_id: min)
139 prev_url = mastodon_api_url(Pleroma.Web.Endpoint, method, since_id: max)
141 |> put_resp_header("link", "<#{next_url}>; rel=\"next\", <#{prev_url}>; rel=\"prev\"")
147 def home_timeline(%{assigns: %{user: user}} = conn, params) do
149 |> Map.put("type", ["Create", "Announce"])
150 |> Map.put("blocking_user", user)
152 activities = ActivityPub.fetch_activities([user.ap_id | user.following], params)
156 |> add_link_headers(:home_timeline, activities)
157 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
160 def public_timeline(%{assigns: %{user: user}} = conn, params) do
162 |> Map.put("type", ["Create", "Announce"])
163 |> Map.put("local_only", !!params["local"])
164 |> Map.put("blocking_user", user)
166 activities = ActivityPub.fetch_public_activities(params)
170 |> add_link_headers(:public_timeline, activities)
171 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
175 def user_statuses(%{assigns: %{user: user}} = conn, params) do
176 with %User{ap_id: ap_id} <- Repo.get(User, params["id"]) do
178 |> Map.put("type", ["Create", "Announce"])
179 |> Map.put("actor_id", ap_id)
180 |> Map.put("whole_db", true)
182 activities = ActivityPub.fetch_activities([], params)
185 render conn, StatusView, "index.json", %{activities: activities, for: user, as: :activity}
189 def get_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
190 with %Activity{} = activity <- Repo.get(Activity, id) do
191 render conn, StatusView, "status.json", %{activity: activity, for: user}
195 def get_context(%{assigns: %{user: user}} = conn, %{"id" => id}) do
196 with %Activity{} = activity <- Repo.get(Activity, id),
197 activities <- ActivityPub.fetch_activities_for_context(activity.data["object"]["context"], %{"blocking_user" => user}),
198 activities <- activities |> Enum.filter(fn (%{id: aid}) -> to_string(aid) != to_string(id) end),
199 activities <- activities |> Enum.filter(fn (%{data: %{"type" => type}}) -> type == "Create" end),
200 grouped_activities <- Enum.group_by(activities, fn (%{id: id}) -> id < activity.id end) do
202 ancestors: StatusView.render("index.json", for: user, activities: grouped_activities[true] || [], as: :activity) |> Enum.reverse,
203 descendants: StatusView.render("index.json", for: user, activities: grouped_activities[false] || [], as: :activity) |> Enum.reverse,
210 def post_status(%{assigns: %{user: user}} = conn, %{"status" => _} = params) do
212 |> Map.put("in_reply_to_status_id", params["in_reply_to_id"])
214 {:ok, activity} = CommonAPI.post(user, params)
215 render conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity}
218 def delete_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
219 with {:ok, %Activity{}} <- CommonAPI.delete(id, user) do
225 |> json(%{error: "Can't delete this post"})
229 def reblog_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
230 with {:ok, announce, _activity} = CommonAPI.repeat(ap_id_or_id, user) do
231 render conn, StatusView, "status.json", %{activity: announce, for: user, as: :activity}
235 def fav_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
236 with {:ok, _fav, %{data: %{"id" => id}}} = CommonAPI.favorite(ap_id_or_id, user),
237 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
238 render conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity}
242 def unfav_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
243 with {:ok, %{data: %{"id" => id}}} = CommonAPI.unfavorite(ap_id_or_id, user),
244 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
245 render conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity}
249 def notifications(%{assigns: %{user: user}} = conn, params) do
250 notifications = Notification.for_user(user, params)
251 result = Enum.map(notifications, fn x ->
252 render_notification(user, x)
254 |> Enum.filter(&(&1))
257 |> add_link_headers(:notifications, notifications)
261 def get_notification(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
262 with {:ok, notification} <- Notification.get(user, id) do
263 json(conn, render_notification(user, notification))
267 |> put_resp_content_type("application/json")
268 |> send_resp(403, Poison.encode!(%{"error" => reason}))
272 def clear_notifications(%{assigns: %{user: user}} = conn, _params) do
273 Notification.clear(user)
277 def dismiss_notification(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
278 with {:ok, _notif} <- Notification.dismiss(user, id) do
283 |> put_resp_content_type("application/json")
284 |> send_resp(403, Poison.encode!(%{"error" => reason}))
288 def relationships(%{assigns: %{user: user}} = conn, %{"id" => id}) do
292 targets = Repo.all(q)
293 render conn, AccountView, "relationships.json", %{user: user, targets: targets}
296 def upload(%{assigns: %{user: _}} = conn, %{"file" => file}) do
297 with {:ok, object} <- ActivityPub.upload(file) do
299 |> Map.put("id", object.id)
301 render conn, StatusView, "attachment.json", %{attachment: data}
305 def favourited_by(conn, %{"id" => id}) do
306 with %Activity{data: %{"object" => %{"likes" => likes}}} <- Repo.get(Activity, id) do
308 where: u.ap_id in ^likes
310 render conn, AccountView, "accounts.json", %{users: users, as: :user}
316 def reblogged_by(conn, %{"id" => id}) do
317 with %Activity{data: %{"object" => %{"announcements" => announces}}} <- Repo.get(Activity, id) do
319 where: u.ap_id in ^announces
321 render conn, AccountView, "accounts.json", %{users: users, as: :user}
328 def hashtag_timeline(%{assigns: %{user: user}} = conn, params) do
330 |> Map.put("type", "Create")
331 |> Map.put("local_only", !!params["local"])
332 |> Map.put("blocking_user", user)
334 activities = ActivityPub.fetch_public_activities(params)
338 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
342 def followers(conn, %{"id" => id}) do
343 with %User{} = user <- Repo.get(User, id),
344 {:ok, followers} <- User.get_followers(user) do
345 render conn, AccountView, "accounts.json", %{users: followers, as: :user}
349 def following(conn, %{"id" => id}) do
350 with %User{} = user <- Repo.get(User, id),
351 {:ok, followers} <- User.get_friends(user) do
352 render conn, AccountView, "accounts.json", %{users: followers, as: :user}
356 def follow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
357 with %User{} = followed <- Repo.get(User, id),
358 {:ok, follower} <- User.follow(follower, followed),
359 {:ok, _activity} <- ActivityPub.follow(follower, followed) do
360 render conn, AccountView, "relationship.json", %{user: follower, target: followed}
364 |> put_resp_content_type("application/json")
365 |> send_resp(403, Poison.encode!(%{"error" => message}))
369 def follow(%{assigns: %{user: follower}} = conn, %{"uri" => uri}) do
370 with %User{} = followed <- Repo.get_by(User, nickname: uri),
371 {:ok, follower} <- User.follow(follower, followed),
372 {:ok, _activity} <- ActivityPub.follow(follower, followed) do
373 render conn, AccountView, "account.json", %{user: followed}
377 |> put_resp_content_type("application/json")
378 |> send_resp(403, Poison.encode!(%{"error" => message}))
382 # TODO: Clean up and unify
383 def unfollow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
384 with %User{} = followed <- Repo.get(User, id),
385 { :ok, follower, follow_activity } <- User.unfollow(follower, followed),
386 { :ok, _activity } <- ActivityPub.insert(%{
388 "actor" => follower.ap_id,
389 "object" => follow_activity.data["id"] # get latest Follow for these users
391 render conn, AccountView, "relationship.json", %{user: follower, target: followed}
395 def block(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
396 with %User{} = blocked <- Repo.get(User, id),
397 {:ok, blocker} <- User.block(blocker, blocked) do
398 render conn, AccountView, "relationship.json", %{user: blocker, target: blocked}
402 |> put_resp_content_type("application/json")
403 |> send_resp(403, Poison.encode!(%{"error" => message}))
407 def unblock(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
408 with %User{} = blocked <- Repo.get(User, id),
409 {:ok, blocker} <- User.unblock(blocker, blocked) do
410 render conn, AccountView, "relationship.json", %{user: blocker, target: blocked}
414 |> put_resp_content_type("application/json")
415 |> send_resp(403, Poison.encode!(%{"error" => message}))
419 # TODO: Use proper query
420 def blocks(%{assigns: %{user: user}} = conn, _) do
421 with blocked_users <- user.info["blocks"] || [],
422 accounts <- Enum.map(blocked_users, fn (ap_id) -> User.get_cached_by_ap_id(ap_id) end) do
423 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
428 def search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
429 accounts = User.search(query, params["resolve"] == "true")
431 fetched = if Regex.match?(~r/https?:/, query) do
432 with {:ok, activities} <- OStatus.fetch_activity_from_url(query) do
439 q = from a in Activity,
440 where: fragment("?->>'type' = 'Create'", a.data),
441 where: fragment("to_tsvector('english', ?->'object'->>'content') @@ plainto_tsquery('english', ?)", a.data, ^query),
443 statuses = Repo.all(q) ++ fetched
446 "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
447 "statuses" => StatusView.render("index.json", activities: statuses, for: user, as: :activity),
454 def account_search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
455 accounts = User.search(query, params["resolve"] == "true")
457 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
462 def favourites(%{assigns: %{user: user}} = conn, _) do
464 |> Map.put("type", "Create")
465 |> Map.put("favorited_by", user.ap_id)
466 |> Map.put("blocking_user", user)
468 activities = ActivityPub.fetch_activities([], params)
472 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
475 def index(%{assigns: %{user: user}} = conn, _params) do
477 |> get_session(:oauth_token)
480 mastodon_emoji = mastodonized_emoji()
481 accounts = Map.put(%{}, user.id, AccountView.render("account.json", %{user: user}))
484 streaming_api_base_url: String.replace(Pleroma.Web.Endpoint.static_url(), "http", "ws"),
487 domain: Pleroma.Web.Endpoint.host(),
490 unfollow_modal: false,
493 auto_play_gif: false,
498 default_privacy: "public",
499 default_sensitive: false
501 media_attachments: %{
502 accept_content_types: [
546 push_subscription: nil,
548 custom_emojis: mastodon_emoji
552 |> render(MastodonView, "index.html", %{initial_state: initial_state})
555 |> redirect(to: "/web/login")
559 def login(conn, _) do
561 |> render(MastodonView, "login.html")
564 defp get_or_make_app() do
565 with %App{} = app <- Repo.get_by(App, client_name: "Mastodon-Local") do
569 cs = App.register_changeset(%App{}, %{client_name: "Mastodon-Local", redirect_uris: ".", scopes: "read,write,follow"})
574 def login_post(conn, %{"authorization" => %{ "name" => name, "password" => password}}) do
575 with %User{} = user <- User.get_cached_by_nickname(name),
576 true <- Pbkdf2.checkpw(password, user.password_hash),
577 {:ok, app} <- get_or_make_app(),
578 {:ok, auth} <- Authorization.create_authorization(app, user),
579 {:ok, token} <- Token.exchange_token(app, auth) do
581 |> put_session(:oauth_token, token.token)
582 |> redirect(to: "/web/getting-started")
586 def relationship_noop(%{assigns: %{user: user}} = conn, %{"id" => id}) do
587 Logger.debug("Unimplemented, returning unmodified relationship")
588 with %User{} = target <- Repo.get(User, id) do
589 render conn, AccountView, "relationship.json", %{user: user, target: target}
593 def empty_array(conn, _) do
594 Logger.debug("Unimplemented, returning an empty array")
598 def render_notification(user, %{id: id, activity: activity, inserted_at: created_at} = _params) do
599 actor = User.get_cached_by_ap_id(activity.data["actor"])
600 created_at = NaiveDateTime.to_iso8601(created_at)
601 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
602 case activity.data["type"] do
604 %{id: id, type: "mention", created_at: created_at, account: AccountView.render("account.json", %{user: actor}), status: StatusView.render("status.json", %{activity: activity, for: user})}
606 liked_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
607 %{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})}
609 announced_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
610 %{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})}
612 %{id: id, type: "follow", created_at: created_at, account: AccountView.render("account.json", %{user: actor})}