c039412547610962114eb7e94357b7d45236fa8e
[akkoma] / lib / pleroma / web / mastodon_api / mastodon_api_controller.ex
1 defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do
2 use Pleroma.Web, :controller
3 alias Pleroma.{Repo, Activity, User, Notification, Stats}
4 alias Pleroma.Web
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}
9 alias Comeonin.Pbkdf2
10 import Ecto.Query
11 require Logger
12
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
16 res = %{
17 id: app.id,
18 client_id: app.client_id,
19 client_secret: app.client_secret
20 }
21
22 json(conn, res)
23 end
24 end
25
26 def update_credentials(%{assigns: %{user: user}} = conn, params) do
27 original_user = user
28 params = if bio = params["note"] do
29 Map.put(params, "bio", bio)
30 else
31 params
32 end
33
34 params = if name = params["display_name"] do
35 Map.put(params, "name", name)
36 else
37 params
38 end
39
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
45 user
46 else
47 _e -> user
48 end
49 else
50 user
51 end
52
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
59 user
60 else
61 _e -> user
62 end
63 else
64 user
65 end
66
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)
71 end
72 json conn, AccountView.render("account.json", %{user: user})
73 else
74 _e ->
75 conn
76 |> put_status(403)
77 |> json(%{error: "Invalid request"})
78 end
79 end
80
81 def verify_credentials(%{assigns: %{user: user}} = conn, _) do
82 account = AccountView.render("account.json", %{user: user})
83 json(conn, account)
84 end
85
86 def user(conn, %{"id" => id}) do
87 with %User{} = user <- Repo.get(User, id) do
88 account = AccountView.render("account.json", %{user: user})
89 json(conn, account)
90 else
91 _e -> conn
92 |> put_status(404)
93 |> json(%{error: "Can't find user"})
94 end
95 end
96
97 @instance Application.get_env(:pleroma, :instance)
98
99 def masto_instance(conn, _params) do
100 response = %{
101 uri: Web.base_url,
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),
106 urls: %{
107 streaming_api: String.replace(Web.base_url, ["http","https"], "wss")
108 },
109 stats: Stats.get_stats,
110 thumbnail: Web.base_url <> "/instance/thumbnail.jpeg",
111 max_toot_chars: Keyword.get(@instance, :limit)
112 }
113
114 json(conn, response)
115 end
116
117 def peers(conn, _params) do
118 json(conn, Stats.get_peers)
119 end
120
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)
125 %{
126 "shortcode" => shortcode,
127 "static_url" => url,
128 "url" => url
129 }
130 end)
131 end
132
133 def custom_emojis(conn, _params) do
134 mastodon_emoji = mastodonized_emoji()
135 json conn, mastodon_emoji
136 end
137
138 defp add_link_headers(conn, method, activities, param \\ false) do
139 last = List.last(activities)
140 first = List.first(activities)
141 if last do
142 min = last.id
143 max = first.id
144 {next_url, prev_url} = if param do
145 {
146 mastodon_api_url(Pleroma.Web.Endpoint, method, param, max_id: min),
147 mastodon_api_url(Pleroma.Web.Endpoint, method, param, since_id: max)
148 }
149 else
150 {
151 mastodon_api_url(Pleroma.Web.Endpoint, method, max_id: min),
152 mastodon_api_url(Pleroma.Web.Endpoint, method, since_id: max)
153 }
154 end
155 conn
156 |> put_resp_header("link", "<#{next_url}>; rel=\"next\", <#{prev_url}>; rel=\"prev\"")
157 else
158 conn
159 end
160 end
161
162 def home_timeline(%{assigns: %{user: user}} = conn, params) do
163 params = params
164 |> Map.put("type", ["Create", "Announce"])
165 |> Map.put("blocking_user", user)
166 |> Map.put("user", user)
167
168 activities = ActivityPub.fetch_activities([user.ap_id | user.following], params)
169 |> Enum.reverse
170
171 conn
172 |> add_link_headers(:home_timeline, activities)
173 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
174 end
175
176 def public_timeline(%{assigns: %{user: user}} = conn, params) do
177 params = params
178 |> Map.put("type", ["Create", "Announce"])
179 |> Map.put("local_only", params["local"] in [true, "True", "true", "1"])
180 |> Map.put("blocking_user", user)
181
182 activities = ActivityPub.fetch_public_activities(params)
183 |> Enum.reverse
184
185 conn
186 |> add_link_headers(:public_timeline, activities)
187 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
188 end
189
190 def user_statuses(%{assigns: %{user: user}} = conn, params) do
191 with %User{ap_id: ap_id} <- Repo.get(User, params["id"]) do
192 params = params
193 |> Map.put("type", ["Create", "Announce"])
194 |> Map.put("actor_id", ap_id)
195 |> Map.put("whole_db", true)
196
197 activities = ActivityPub.fetch_public_activities(params)
198 |> Enum.reverse
199
200 conn
201 |> add_link_headers(:user_statuses, activities, params["id"])
202 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
203 end
204 end
205
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}
210 end
211 end
212
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
219 result = %{
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,
222 }
223
224 json(conn, result)
225 end
226 end
227
228 def post_status(%{assigns: %{user: user}} = conn, %{"status" => _} = params) do
229 params = params
230 |> Map.put("in_reply_to_status_id", params["in_reply_to_id"])
231 |> Map.put("no_attachment_links", true)
232
233 {:ok, activity} = CommonAPI.post(user, params)
234 render conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity}
235 end
236
237 def delete_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
238 with {:ok, %Activity{}} <- CommonAPI.delete(id, user) do
239 json(conn, %{})
240 else
241 _e ->
242 conn
243 |> put_status(403)
244 |> json(%{error: "Can't delete this post"})
245 end
246 end
247
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}
251 end
252 end
253
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}
258 end
259 end
260
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}
265 end
266 end
267
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)
272 end)
273 |> Enum.filter(&(&1))
274
275 conn
276 |> add_link_headers(:notifications, notifications)
277 |> json(result)
278 end
279
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))
283 else
284 {:error, reason} ->
285 conn
286 |> put_resp_content_type("application/json")
287 |> send_resp(403, Poison.encode!(%{"error" => reason}))
288 end
289 end
290
291 def clear_notifications(%{assigns: %{user: user}} = conn, _params) do
292 Notification.clear(user)
293 json(conn, %{})
294 end
295
296 def dismiss_notification(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
297 with {:ok, _notif} <- Notification.dismiss(user, id) do
298 json(conn, %{})
299 else
300 {:error, reason} ->
301 conn
302 |> put_resp_content_type("application/json")
303 |> send_resp(403, Poison.encode!(%{"error" => reason}))
304 end
305 end
306
307 def relationships(%{assigns: %{user: user}} = conn, %{"id" => id}) do
308 id = List.wrap(id)
309 q = from u in User,
310 where: u.id in ^id
311 targets = Repo.all(q)
312 render conn, AccountView, "relationships.json", %{user: user, targets: targets}
313 end
314
315 def upload(%{assigns: %{user: _}} = conn, %{"file" => file}) do
316 with {:ok, object} <- ActivityPub.upload(file) do
317 data = object.data
318 |> Map.put("id", object.id)
319
320 render conn, StatusView, "attachment.json", %{attachment: data}
321 end
322 end
323
324 def favourited_by(conn, %{"id" => id}) do
325 with %Activity{data: %{"object" => %{"likes" => likes}}} <- Repo.get(Activity, id) do
326 q = from u in User,
327 where: u.ap_id in ^likes
328 users = Repo.all(q)
329 render conn, AccountView, "accounts.json", %{users: users, as: :user}
330 else
331 _ -> json(conn, [])
332 end
333 end
334
335 def reblogged_by(conn, %{"id" => id}) do
336 with %Activity{data: %{"object" => %{"announcements" => announces}}} <- Repo.get(Activity, id) do
337 q = from u in User,
338 where: u.ap_id in ^announces
339 users = Repo.all(q)
340 render conn, AccountView, "accounts.json", %{users: users, as: :user}
341 else
342 _ -> json(conn, [])
343 end
344 end
345
346 def hashtag_timeline(%{assigns: %{user: user}} = conn, params) do
347 params = params
348 |> Map.put("type", "Create")
349 |> Map.put("local_only", !!params["local"])
350 |> Map.put("blocking_user", user)
351
352 activities = ActivityPub.fetch_public_activities(params)
353 |> Enum.reverse
354
355 conn
356 |> add_link_headers(:hashtag_timeline, activities, params["tag"])
357 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
358 end
359
360 # TODO: Pagination
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}
365 end
366 end
367
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}
372 end
373 end
374
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}
380 else
381 {:error, message} ->
382 conn
383 |> put_resp_content_type("application/json")
384 |> send_resp(403, Poison.encode!(%{"error" => message}))
385 end
386 end
387
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}
393 else
394 {:error, message} ->
395 conn
396 |> put_resp_content_type("application/json")
397 |> send_resp(403, Poison.encode!(%{"error" => message}))
398 end
399 end
400
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(%{
406 "type" => "Undo",
407 "actor" => follower.ap_id,
408 "object" => follow_activity.data["id"] # get latest Follow for these users
409 }) do
410 render conn, AccountView, "relationship.json", %{user: follower, target: followed}
411 end
412 end
413
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}
418 else
419 {:error, message} ->
420 conn
421 |> put_resp_content_type("application/json")
422 |> send_resp(403, Poison.encode!(%{"error" => message}))
423 end
424 end
425
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}
430 else
431 {:error, message} ->
432 conn
433 |> put_resp_content_type("application/json")
434 |> send_resp(403, Poison.encode!(%{"error" => message}))
435 end
436 end
437
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)
443 json(conn, res)
444 end
445 end
446
447 def search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
448 accounts = User.search(query, params["resolve"] == "true")
449
450 fetched = if Regex.match?(~r/https?:/, query) do
451 with {:ok, activities} <- OStatus.fetch_activity_from_url(query) do
452 activities
453 else
454 _e -> []
455 end
456 end || []
457
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),
461 limit: 20
462 statuses = Repo.all(q) ++ fetched
463
464 res = %{
465 "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
466 "statuses" => StatusView.render("index.json", activities: statuses, for: user, as: :activity),
467 "hashtags" => []
468 }
469
470 json(conn, res)
471 end
472
473 def account_search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
474 accounts = User.search(query, params["resolve"] == "true")
475
476 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
477
478 json(conn, res)
479 end
480
481 def favourites(%{assigns: %{user: user}} = conn, _) do
482 params = %{}
483 |> Map.put("type", "Create")
484 |> Map.put("favorited_by", user.ap_id)
485 |> Map.put("blocking_user", user)
486
487 activities = ActivityPub.fetch_public_activities(params)
488 |> Enum.reverse
489
490 conn
491 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
492 end
493
494 def index(%{assigns: %{user: user}} = conn, _params) do
495 token = conn
496 |> get_session(:oauth_token)
497
498 if user && token do
499 mastodon_emoji = mastodonized_emoji()
500 accounts = Map.put(%{}, user.id, AccountView.render("account.json", %{user: user}))
501 initial_state = %{
502 meta: %{
503 streaming_api_base_url: String.replace(Pleroma.Web.Endpoint.static_url(), "http", "ws"),
504 access_token: token,
505 locale: "en",
506 domain: Pleroma.Web.Endpoint.host(),
507 admin: "1",
508 me: "#{user.id}",
509 unfollow_modal: false,
510 boost_modal: false,
511 delete_modal: true,
512 auto_play_gif: false,
513 reduce_motion: false
514 },
515 compose: %{
516 me: "#{user.id}",
517 default_privacy: "public",
518 default_sensitive: false
519 },
520 media_attachments: %{
521 accept_content_types: [
522 ".jpg",
523 ".jpeg",
524 ".png",
525 ".gif",
526 ".webm",
527 ".mp4",
528 ".m4v",
529 "image\/jpeg",
530 "image\/png",
531 "image\/gif",
532 "video\/webm",
533 "video\/mp4"
534 ]
535 },
536 settings: %{
537 onboarded: true,
538 home: %{
539 shows: %{
540 reblog: true,
541 reply: true
542 }
543 },
544 notifications: %{
545 alerts: %{
546 follow: true,
547 favourite: true,
548 reblog: true,
549 mention: true
550 },
551 shows: %{
552 follow: true,
553 favourite: true,
554 reblog: true,
555 mention: true
556 },
557 sounds: %{
558 follow: true,
559 favourite: true,
560 reblog: true,
561 mention: true
562 }
563 }
564 },
565 push_subscription: nil,
566 accounts: accounts,
567 custom_emojis: mastodon_emoji
568 } |> Poison.encode!
569 conn
570 |> put_layout(false)
571 |> render(MastodonView, "index.html", %{initial_state: initial_state})
572 else
573 conn
574 |> redirect(to: "/web/login")
575 end
576 end
577
578 def login(conn, _) do
579 conn
580 |> render(MastodonView, "login.html", %{error: false})
581 end
582
583 defp get_or_make_app() do
584 with %App{} = app <- Repo.get_by(App, client_name: "Mastodon-Local") do
585 {:ok, app}
586 else
587 _e ->
588 cs = App.register_changeset(%App{}, %{client_name: "Mastodon-Local", redirect_uris: ".", scopes: "read,write,follow"})
589 Repo.insert(cs)
590 end
591 end
592
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
599 conn
600 |> put_session(:oauth_token, token.token)
601 |> redirect(to: "/web/getting-started")
602 else
603 _e ->
604 conn
605 |> render(MastodonView, "login.html", %{error: "Wrong username or password"})
606 end
607 end
608
609 def logout(conn, _) do
610 conn
611 |> clear_session
612 |> redirect(to: "/")
613 end
614
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}
619 end
620 end
621
622 def empty_array(conn, _) do
623 Logger.debug("Unimplemented, returning an empty array")
624 json(conn, [])
625 end
626
627 def empty_object(conn, _) do
628 Logger.debug("Unimplemented, returning an empty object")
629 json(conn, %{})
630 end
631
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
637 "Create" ->
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})}
639 "Like" ->
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})}
642 "Announce" ->
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})}
645 "Follow" ->
646 %{id: id, type: "follow", created_at: created_at, account: AccountView.render("account.json", %{user: actor})}
647 _ -> nil
648 end
649 end
650 end