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, _activity} = CommonAPI.repeat(ap_id_or_id, user) do
227 render conn, StatusView, "status.json", %{activity: announce, for: user, as: :activity}
231 def fav_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
232 with {:ok, _fav, %{data: %{"id" => id}}} = CommonAPI.favorite(ap_id_or_id, user),
233 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
234 render conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity}
238 def unfav_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
239 with {:ok, %{data: %{"id" => id}}} = CommonAPI.unfavorite(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 notifications(%{assigns: %{user: user}} = conn, params) do
246 notifications = Notification.for_user(user, params)
247 result = Enum.map(notifications, fn x ->
248 render_notification(user, x)
250 |> Enum.filter(&(&1))
253 |> add_link_headers(:notifications, notifications)
257 def get_notification(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
258 with {:ok, notification} <- Notification.get(user, id) do
259 json(conn, render_notification(user, notification))
263 |> put_resp_content_type("application/json")
264 |> send_resp(403, Poison.encode!(%{"error" => reason}))
268 def clear_notifications(%{assigns: %{user: user}} = conn, _params) do
269 Notification.clear(user)
273 def dismiss_notification(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
274 with {:ok, _notif} <- Notification.dismiss(user, id) do
279 |> put_resp_content_type("application/json")
280 |> send_resp(403, Poison.encode!(%{"error" => reason}))
284 def relationships(%{assigns: %{user: user}} = conn, %{"id" => id}) do
288 targets = Repo.all(q)
289 render conn, AccountView, "relationships.json", %{user: user, targets: targets}
292 def upload(%{assigns: %{user: user}} = conn, %{"file" => file}) do
293 with {:ok, object} <- ActivityPub.upload(file) do
295 |> Map.put("id", object.id)
297 render conn, StatusView, "attachment.json", %{attachment: data}
301 def favourited_by(conn, %{"id" => id}) do
302 with %Activity{data: %{"object" => %{"likes" => likes} = data}} <- Repo.get(Activity, id) do
304 where: u.ap_id in ^likes
306 render conn, AccountView, "accounts.json", %{users: users, as: :user}
312 def reblogged_by(conn, %{"id" => id}) do
313 with %Activity{data: %{"object" => %{"announcements" => announces}}} <- Repo.get(Activity, id) do
315 where: u.ap_id in ^announces
317 render conn, AccountView, "accounts.json", %{users: users, as: :user}
324 def hashtag_timeline(%{assigns: %{user: user}} = conn, params) do
326 |> Map.put("type", "Create")
327 |> Map.put("local_only", !!params["local"])
328 |> Map.put("blocking_user", user)
330 activities = ActivityPub.fetch_public_activities(params)
334 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
338 def followers(conn, %{"id" => id}) do
339 with %User{} = user <- Repo.get(User, id),
340 {:ok, followers} <- User.get_followers(user) do
341 render conn, AccountView, "accounts.json", %{users: followers, as: :user}
345 def following(conn, %{"id" => id}) do
346 with %User{} = user <- Repo.get(User, id),
347 {:ok, followers} <- User.get_friends(user) do
348 render conn, AccountView, "accounts.json", %{users: followers, as: :user}
352 def follow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
353 with %User{} = followed <- Repo.get(User, id),
354 {:ok, follower} <- User.follow(follower, followed),
355 {:ok, activity} <- ActivityPub.follow(follower, followed) do
356 render conn, AccountView, "relationship.json", %{user: follower, target: followed}
358 {:error, message} = err ->
360 |> put_resp_content_type("application/json")
361 |> send_resp(403, Poison.encode!(%{"error" => message}))
365 def follow(%{assigns: %{user: follower}} = conn, %{"uri" => uri}) do
366 with %User{} = followed <- Repo.get_by(User, nickname: uri),
367 {:ok, follower} <- User.follow(follower, followed),
368 {:ok, activity} <- ActivityPub.follow(follower, followed) do
369 render conn, AccountView, "account.json", %{user: followed}
371 {:error, message} = err ->
373 |> put_resp_content_type("application/json")
374 |> send_resp(403, Poison.encode!(%{"error" => message}))
378 # TODO: Clean up and unify
379 def unfollow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
380 with %User{} = followed <- Repo.get(User, id),
381 { :ok, follower, follow_activity } <- User.unfollow(follower, followed),
382 { :ok, _activity } <- ActivityPub.insert(%{
384 "actor" => follower.ap_id,
385 "object" => follow_activity.data["id"] # get latest Follow for these users
387 render conn, AccountView, "relationship.json", %{user: follower, target: followed}
391 def block(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
392 with %User{} = blocked <- Repo.get(User, id),
393 {:ok, blocker} <- User.block(blocker, blocked) do
394 render conn, AccountView, "relationship.json", %{user: blocker, target: blocked}
396 {:error, message} = err ->
398 |> put_resp_content_type("application/json")
399 |> send_resp(403, Poison.encode!(%{"error" => message}))
403 def unblock(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
404 with %User{} = blocked <- Repo.get(User, id),
405 {:ok, blocker} <- User.unblock(blocker, blocked) do
406 render conn, AccountView, "relationship.json", %{user: blocker, target: blocked}
408 {:error, message} = err ->
410 |> put_resp_content_type("application/json")
411 |> send_resp(403, Poison.encode!(%{"error" => message}))
415 # TODO: Use proper query
416 def blocks(%{assigns: %{user: user}} = conn, _) do
417 with blocked_users <- user.info["blocks"] || [],
418 accounts <- Enum.map(blocked_users, fn (ap_id) -> User.get_cached_by_ap_id(ap_id) end) do
419 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
424 def search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
425 accounts = User.search(query, params["resolve"] == "true")
427 fetched = if Regex.match?(~r/https?:/, query) do
428 with {:ok, activities} <- OStatus.fetch_activity_from_url(query) do
435 q = from a in Activity,
436 where: fragment("?->>'type' = 'Create'", a.data),
437 where: fragment("to_tsvector('english', ?->'object'->>'content') @@ plainto_tsquery('english', ?)", a.data, ^query),
439 statuses = Repo.all(q) ++ fetched
442 "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
443 "statuses" => StatusView.render("index.json", activities: statuses, for: user, as: :activity),
450 def account_search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
451 accounts = User.search(query, params["resolve"] == "true")
453 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
458 def favourites(%{assigns: %{user: user}} = conn, params) do
460 |> Map.put("type", "Create")
461 |> Map.put("favorited_by", user.ap_id)
462 |> Map.put("blocking_user", user)
464 activities = ActivityPub.fetch_activities([], params)
468 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
471 def index(%{assigns: %{user: user}} = conn, _params) do
473 |> get_session(:oauth_token)
476 accounts = Map.put(%{}, user.id, AccountView.render("account.json", %{user: user}))
479 streaming_api_base_url: String.replace(Pleroma.Web.Endpoint.static_url(), "http", "ws"),
482 domain: Pleroma.Web.Endpoint.host(),
485 unfollow_modal: false,
488 auto_play_gif: false,
493 default_privacy: "public",
494 default_sensitive: false
496 media_attachments: %{
497 accept_content_types: [
541 push_subscription: nil,
547 |> render(MastodonView, "index.html", %{initial_state: initial_state})
550 |> redirect(to: "/web/login")
554 def login(conn, params) do
556 |> render(MastodonView, "login.html")
559 defp get_or_make_app() do
560 with %App{} = app <- Repo.get_by(App, client_name: "Mastodon-Local") do
564 cs = App.register_changeset(%App{}, %{client_name: "Mastodon-Local", redirect_uris: ".", scopes: "read,write,follow"})
569 def login_post(conn, %{"authorization" => %{ "name" => name, "password" => password}}) do
570 with %User{} = user <- User.get_cached_by_nickname(name),
571 true <- Pbkdf2.checkpw(password, user.password_hash),
572 {:ok, app} <- get_or_make_app(),
573 {:ok, auth} <- Authorization.create_authorization(app, user),
574 {:ok, token} <- Token.exchange_token(app, auth) do
576 |> put_session(:oauth_token, token.token)
577 |> redirect(to: "/web/timelines/public")
581 def relationship_noop(%{assigns: %{user: user}} = conn, %{"id" => id}) do
582 Logger.debug("Unimplemented, returning unmodified relationship")
583 with %User{} = target <- Repo.get(User, id) do
584 render conn, AccountView, "relationship.json", %{user: user, target: target}
588 def empty_array(conn, _) do
589 Logger.debug("Unimplemented, returning an empty array")
593 defp render_notification(user, %{id: id, activity: activity, inserted_at: created_at} = _params) do
594 actor = User.get_cached_by_ap_id(activity.data["actor"])
595 created_at = NaiveDateTime.to_iso8601(created_at)
596 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
597 case activity.data["type"] do
599 %{id: id, type: "mention", created_at: created_at, account: AccountView.render("account.json", %{user: actor}), status: StatusView.render("status.json", %{activity: activity, for: user})}
601 liked_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
602 %{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})}
604 announced_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
605 %{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})}
607 %{id: id, type: "follow", created_at: created_at, account: AccountView.render("account.json", %{user: actor})}