a4b17e4f815c0fc93627409d0943bd733a2319c0
[akkoma] / lib / pleroma / web / mastodon_api / mastodon_api_controller.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do
6 use Pleroma.Web, :controller
7 alias Pleroma.{Repo, Object, Activity, User, Notification, Stats}
8 alias Pleroma.Web
9
10 alias Pleroma.Web.MastodonAPI.{
11 StatusView,
12 AccountView,
13 MastodonView,
14 ListView,
15 FilterView,
16 PushSubscriptionView
17 }
18
19 alias Pleroma.Web.ActivityPub.ActivityPub
20 alias Pleroma.Web.ActivityPub.Utils
21 alias Pleroma.Web.CommonAPI
22 alias Pleroma.Web.OAuth.{Authorization, Token, App}
23 alias Pleroma.Web.MediaProxy
24
25 import Ecto.Query
26 require Logger
27
28 @httpoison Application.get_env(:pleroma, :httpoison)
29
30 action_fallback(:errors)
31
32 def create_app(conn, params) do
33 with cs <- App.register_changeset(%App{}, params) |> IO.inspect(),
34 {:ok, app} <- Repo.insert(cs) |> IO.inspect() do
35 res = %{
36 id: app.id |> to_string,
37 name: app.client_name,
38 client_id: app.client_id,
39 client_secret: app.client_secret,
40 redirect_uri: app.redirect_uris,
41 website: app.website
42 }
43
44 json(conn, res)
45 end
46 end
47
48 defp add_if_present(
49 map,
50 params,
51 params_field,
52 map_field,
53 value_function \\ fn x -> {:ok, x} end
54 ) do
55 if Map.has_key?(params, params_field) do
56 case value_function.(params[params_field]) do
57 {:ok, new_value} -> Map.put(map, map_field, new_value)
58 :error -> map
59 end
60 else
61 map
62 end
63 end
64
65 def update_credentials(%{assigns: %{user: user}} = conn, params) do
66 original_user = user
67
68 user_params =
69 %{}
70 |> add_if_present(params, "display_name", :name)
71 |> add_if_present(params, "note", :bio, fn value -> {:ok, User.parse_bio(value)} end)
72 |> add_if_present(params, "avatar", :avatar, fn value ->
73 with %Plug.Upload{} <- value,
74 {:ok, object} <- ActivityPub.upload(value, type: :avatar) do
75 {:ok, object.data}
76 else
77 _ -> :error
78 end
79 end)
80
81 info_params =
82 %{}
83 |> add_if_present(params, "locked", :locked, fn value -> {:ok, value == "true"} end)
84 |> add_if_present(params, "header", :banner, fn value ->
85 with %Plug.Upload{} <- value,
86 {:ok, object} <- ActivityPub.upload(value, type: :banner) do
87 {:ok, object.data}
88 else
89 _ -> :error
90 end
91 end)
92
93 info_cng = User.Info.mastodon_profile_update(user.info, info_params)
94
95 with changeset <- User.update_changeset(user, user_params),
96 changeset <- Ecto.Changeset.put_embed(changeset, :info, info_cng),
97 {:ok, user} <- User.update_and_set_cache(changeset) do
98 if original_user != user do
99 CommonAPI.update(user)
100 end
101
102 json(conn, AccountView.render("account.json", %{user: user, for: user}))
103 else
104 _e ->
105 conn
106 |> put_status(403)
107 |> json(%{error: "Invalid request"})
108 end
109 end
110
111 def verify_credentials(%{assigns: %{user: user}} = conn, _) do
112 account = AccountView.render("account.json", %{user: user, for: user})
113 json(conn, account)
114 end
115
116 def user(%{assigns: %{user: for_user}} = conn, %{"id" => id}) do
117 with %User{} = user <- Repo.get(User, id),
118 true <- User.auth_active?(user) || user.id == for_user.id || User.superuser?(for_user) do
119 account = AccountView.render("account.json", %{user: user, for: for_user})
120 json(conn, account)
121 else
122 _e ->
123 conn
124 |> put_status(404)
125 |> json(%{error: "Can't find user"})
126 end
127 end
128
129 @mastodon_api_level "2.5.0"
130
131 def masto_instance(conn, _params) do
132 instance = Pleroma.Config.get(:instance)
133
134 response = %{
135 uri: Web.base_url(),
136 title: Keyword.get(instance, :name),
137 description: Keyword.get(instance, :description),
138 version: "#{@mastodon_api_level} (compatible; #{Pleroma.Application.named_version()})",
139 email: Keyword.get(instance, :email),
140 urls: %{
141 streaming_api: String.replace(Pleroma.Web.Endpoint.static_url(), "http", "ws")
142 },
143 stats: Stats.get_stats(),
144 thumbnail: Web.base_url() <> "/instance/thumbnail.jpeg",
145 max_toot_chars: Keyword.get(instance, :limit)
146 }
147
148 json(conn, response)
149 end
150
151 def peers(conn, _params) do
152 json(conn, Stats.get_peers())
153 end
154
155 defp mastodonized_emoji do
156 Pleroma.Emoji.get_all()
157 |> Enum.map(fn {shortcode, relative_url} ->
158 url = to_string(URI.merge(Web.base_url(), relative_url))
159
160 %{
161 "shortcode" => shortcode,
162 "static_url" => url,
163 "visible_in_picker" => true,
164 "url" => url
165 }
166 end)
167 end
168
169 def custom_emojis(conn, _params) do
170 mastodon_emoji = mastodonized_emoji()
171 json(conn, mastodon_emoji)
172 end
173
174 defp add_link_headers(conn, method, activities, param \\ nil, params \\ %{}) do
175 last = List.last(activities)
176 first = List.first(activities)
177
178 if last do
179 min = last.id
180 max = first.id
181
182 {next_url, prev_url} =
183 if param do
184 {
185 mastodon_api_url(
186 Pleroma.Web.Endpoint,
187 method,
188 param,
189 Map.merge(params, %{max_id: min})
190 ),
191 mastodon_api_url(
192 Pleroma.Web.Endpoint,
193 method,
194 param,
195 Map.merge(params, %{since_id: max})
196 )
197 }
198 else
199 {
200 mastodon_api_url(
201 Pleroma.Web.Endpoint,
202 method,
203 Map.merge(params, %{max_id: min})
204 ),
205 mastodon_api_url(
206 Pleroma.Web.Endpoint,
207 method,
208 Map.merge(params, %{since_id: max})
209 )
210 }
211 end
212
213 conn
214 |> put_resp_header("link", "<#{next_url}>; rel=\"next\", <#{prev_url}>; rel=\"prev\"")
215 else
216 conn
217 end
218 end
219
220 def home_timeline(%{assigns: %{user: user}} = conn, params) do
221 params =
222 params
223 |> Map.put("type", ["Create", "Announce"])
224 |> Map.put("blocking_user", user)
225 |> Map.put("user", user)
226
227 activities =
228 ActivityPub.fetch_activities([user.ap_id | user.following], params)
229 |> ActivityPub.contain_timeline(user)
230 |> Enum.reverse()
231
232 conn
233 |> add_link_headers(:home_timeline, activities)
234 |> put_view(StatusView)
235 |> render("index.json", %{activities: activities, for: user, as: :activity})
236 end
237
238 def public_timeline(%{assigns: %{user: user}} = conn, params) do
239 local_only = params["local"] in [true, "True", "true", "1"]
240
241 params =
242 params
243 |> Map.put("type", ["Create", "Announce"])
244 |> Map.put("local_only", local_only)
245 |> Map.put("blocking_user", user)
246
247 activities =
248 ActivityPub.fetch_public_activities(params)
249 |> Enum.reverse()
250
251 conn
252 |> add_link_headers(:public_timeline, activities, false, %{"local" => local_only})
253 |> put_view(StatusView)
254 |> render("index.json", %{activities: activities, for: user, as: :activity})
255 end
256
257 def user_statuses(%{assigns: %{user: reading_user}} = conn, params) do
258 with %User{} = user <- Repo.get(User, params["id"]) do
259 # Since Pleroma has no "pinned" posts feature, we'll just set an empty list here
260 activities =
261 if params["pinned"] == "true" do
262 []
263 else
264 ActivityPub.fetch_user_activities(user, reading_user, params)
265 end
266
267 conn
268 |> add_link_headers(:user_statuses, activities, params["id"])
269 |> put_view(StatusView)
270 |> render("index.json", %{
271 activities: activities,
272 for: reading_user,
273 as: :activity
274 })
275 end
276 end
277
278 def dm_timeline(%{assigns: %{user: user}} = conn, params) do
279 query =
280 ActivityPub.fetch_activities_query(
281 [user.ap_id],
282 Map.merge(params, %{"type" => "Create", visibility: "direct"})
283 )
284
285 activities = Repo.all(query)
286
287 conn
288 |> add_link_headers(:dm_timeline, activities)
289 |> put_view(StatusView)
290 |> render("index.json", %{activities: activities, for: user, as: :activity})
291 end
292
293 def get_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
294 with %Activity{} = activity <- Repo.get(Activity, id),
295 true <- ActivityPub.visible_for_user?(activity, user) do
296 conn
297 |> put_view(StatusView)
298 |> try_render("status.json", %{activity: activity, for: user})
299 end
300 end
301
302 def get_context(%{assigns: %{user: user}} = conn, %{"id" => id}) do
303 with %Activity{} = activity <- Repo.get(Activity, id),
304 activities <-
305 ActivityPub.fetch_activities_for_context(activity.data["context"], %{
306 "blocking_user" => user,
307 "user" => user
308 }),
309 activities <-
310 activities |> Enum.filter(fn %{id: aid} -> to_string(aid) != to_string(id) end),
311 activities <-
312 activities |> Enum.filter(fn %{data: %{"type" => type}} -> type == "Create" end),
313 grouped_activities <- Enum.group_by(activities, fn %{id: id} -> id < activity.id end) do
314 result = %{
315 ancestors:
316 StatusView.render(
317 "index.json",
318 for: user,
319 activities: grouped_activities[true] || [],
320 as: :activity
321 )
322 |> Enum.reverse(),
323 descendants:
324 StatusView.render(
325 "index.json",
326 for: user,
327 activities: grouped_activities[false] || [],
328 as: :activity
329 )
330 |> Enum.reverse()
331 }
332
333 json(conn, result)
334 end
335 end
336
337 def post_status(conn, %{"status" => "", "media_ids" => media_ids} = params)
338 when length(media_ids) > 0 do
339 params =
340 params
341 |> Map.put("status", ".")
342
343 post_status(conn, params)
344 end
345
346 def post_status(%{assigns: %{user: user}} = conn, %{"status" => _} = params) do
347 params =
348 params
349 |> Map.put("in_reply_to_status_id", params["in_reply_to_id"])
350 |> Map.put("no_attachment_links", true)
351
352 idempotency_key =
353 case get_req_header(conn, "idempotency-key") do
354 [key] -> key
355 _ -> Ecto.UUID.generate()
356 end
357
358 {:ok, activity} =
359 Cachex.fetch!(:idempotency_cache, idempotency_key, fn _ -> CommonAPI.post(user, params) end)
360
361 conn
362 |> put_view(StatusView)
363 |> try_render("status.json", %{activity: activity, for: user, as: :activity})
364 end
365
366 def delete_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
367 with {:ok, %Activity{}} <- CommonAPI.delete(id, user) do
368 json(conn, %{})
369 else
370 _e ->
371 conn
372 |> put_status(403)
373 |> json(%{error: "Can't delete this post"})
374 end
375 end
376
377 def reblog_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
378 with {:ok, announce, _activity} <- CommonAPI.repeat(ap_id_or_id, user) do
379 conn
380 |> put_view(StatusView)
381 |> try_render("status.json", %{activity: announce, for: user, as: :activity})
382 end
383 end
384
385 def unreblog_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
386 with {:ok, _unannounce, %{data: %{"id" => id}}} <- CommonAPI.unrepeat(ap_id_or_id, user),
387 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
388 conn
389 |> put_view(StatusView)
390 |> try_render("status.json", %{activity: activity, for: user, as: :activity})
391 end
392 end
393
394 def fav_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
395 with {:ok, _fav, %{data: %{"id" => id}}} <- CommonAPI.favorite(ap_id_or_id, user),
396 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
397 conn
398 |> put_view(StatusView)
399 |> try_render("status.json", %{activity: activity, for: user, as: :activity})
400 end
401 end
402
403 def unfav_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
404 with {:ok, _, _, %{data: %{"id" => id}}} <- CommonAPI.unfavorite(ap_id_or_id, user),
405 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
406 conn
407 |> put_view(StatusView)
408 |> try_render("status.json", %{activity: activity, for: user, as: :activity})
409 end
410 end
411
412 def notifications(%{assigns: %{user: user}} = conn, params) do
413 notifications = Notification.for_user(user, params)
414
415 result =
416 Enum.map(notifications, fn x ->
417 render_notification(user, x)
418 end)
419 |> Enum.filter(& &1)
420
421 conn
422 |> add_link_headers(:notifications, notifications)
423 |> json(result)
424 end
425
426 def get_notification(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
427 with {:ok, notification} <- Notification.get(user, id) do
428 json(conn, render_notification(user, notification))
429 else
430 {:error, reason} ->
431 conn
432 |> put_resp_content_type("application/json")
433 |> send_resp(403, Jason.encode!(%{"error" => reason}))
434 end
435 end
436
437 def clear_notifications(%{assigns: %{user: user}} = conn, _params) do
438 Notification.clear(user)
439 json(conn, %{})
440 end
441
442 def dismiss_notification(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
443 with {:ok, _notif} <- Notification.dismiss(user, id) do
444 json(conn, %{})
445 else
446 {:error, reason} ->
447 conn
448 |> put_resp_content_type("application/json")
449 |> send_resp(403, Jason.encode!(%{"error" => reason}))
450 end
451 end
452
453 def relationships(%{assigns: %{user: user}} = conn, %{"id" => id}) do
454 id = List.wrap(id)
455 q = from(u in User, where: u.id in ^id)
456 targets = Repo.all(q)
457
458 conn
459 |> put_view(AccountView)
460 |> render("relationships.json", %{user: user, targets: targets})
461 end
462
463 # Instead of returning a 400 when no "id" params is present, Mastodon returns an empty array.
464 def relationships(%{assigns: %{user: _user}} = conn, _), do: json(conn, [])
465
466 def update_media(%{assigns: %{user: user}} = conn, data) do
467 with %Object{} = object <- Repo.get(Object, data["id"]),
468 true <- Object.authorize_mutation(object, user),
469 true <- is_binary(data["description"]),
470 description <- data["description"] do
471 new_data = %{object.data | "name" => description}
472
473 {:ok, _} =
474 object
475 |> Object.change(%{data: new_data})
476 |> Repo.update()
477
478 attachment_data = Map.put(new_data, "id", object.id)
479
480 conn
481 |> put_view(StatusView)
482 |> render("attachment.json", %{attachment: attachment_data})
483 end
484 end
485
486 def upload(%{assigns: %{user: user}} = conn, %{"file" => file} = data) do
487 with {:ok, object} <-
488 ActivityPub.upload(file,
489 actor: User.ap_id(user),
490 description: Map.get(data, "description")
491 ) do
492 attachment_data = Map.put(object.data, "id", object.id)
493
494 conn
495 |> put_view(StatusView)
496 |> render("attachment.json", %{attachment: attachment_data})
497 end
498 end
499
500 def favourited_by(conn, %{"id" => id}) do
501 with %Activity{data: %{"object" => %{"likes" => likes}}} <- Repo.get(Activity, id) do
502 q = from(u in User, where: u.ap_id in ^likes)
503 users = Repo.all(q)
504
505 conn
506 |> put_view(AccountView)
507 |> render(AccountView, "accounts.json", %{users: users, as: :user})
508 else
509 _ -> json(conn, [])
510 end
511 end
512
513 def reblogged_by(conn, %{"id" => id}) do
514 with %Activity{data: %{"object" => %{"announcements" => announces}}} <- Repo.get(Activity, id) do
515 q = from(u in User, where: u.ap_id in ^announces)
516 users = Repo.all(q)
517
518 conn
519 |> put_view(AccountView)
520 |> render("accounts.json", %{users: users, as: :user})
521 else
522 _ -> json(conn, [])
523 end
524 end
525
526 def hashtag_timeline(%{assigns: %{user: user}} = conn, params) do
527 local_only = params["local"] in [true, "True", "true", "1"]
528
529 params =
530 params
531 |> Map.put("type", "Create")
532 |> Map.put("local_only", local_only)
533 |> Map.put("blocking_user", user)
534 |> Map.put("tag", String.downcase(params["tag"]))
535
536 activities =
537 ActivityPub.fetch_public_activities(params)
538 |> Enum.reverse()
539
540 conn
541 |> add_link_headers(:hashtag_timeline, activities, params["tag"], %{"local" => local_only})
542 |> put_view(StatusView)
543 |> render("index.json", %{activities: activities, for: user, as: :activity})
544 end
545
546 def followers(%{assigns: %{user: for_user}} = conn, %{"id" => id}) do
547 with %User{} = user <- Repo.get(User, id),
548 {:ok, followers} <- User.get_followers(user) do
549 followers =
550 cond do
551 for_user && user.id == for_user.id -> followers
552 user.info.hide_network -> []
553 true -> followers
554 end
555
556 conn
557 |> put_view(AccountView)
558 |> render("accounts.json", %{users: followers, as: :user})
559 end
560 end
561
562 def following(%{assigns: %{user: for_user}} = conn, %{"id" => id}) do
563 with %User{} = user <- Repo.get(User, id),
564 {:ok, followers} <- User.get_friends(user) do
565 followers =
566 cond do
567 for_user && user.id == for_user.id -> followers
568 user.info.hide_network -> []
569 true -> followers
570 end
571
572 conn
573 |> put_view(AccountView)
574 |> render("accounts.json", %{users: followers, as: :user})
575 end
576 end
577
578 def follow_requests(%{assigns: %{user: followed}} = conn, _params) do
579 with {:ok, follow_requests} <- User.get_follow_requests(followed) do
580 conn
581 |> put_view(AccountView)
582 |> render("accounts.json", %{users: follow_requests, as: :user})
583 end
584 end
585
586 def authorize_follow_request(%{assigns: %{user: followed}} = conn, %{"id" => id}) do
587 with %User{} = follower <- Repo.get(User, id),
588 {:ok, follower} <- User.maybe_follow(follower, followed),
589 %Activity{} = follow_activity <- Utils.fetch_latest_follow(follower, followed),
590 {:ok, follow_activity} <- Utils.update_follow_state(follow_activity, "accept"),
591 {:ok, _activity} <-
592 ActivityPub.accept(%{
593 to: [follower.ap_id],
594 actor: followed.ap_id,
595 object: follow_activity.data["id"],
596 type: "Accept"
597 }) do
598 conn
599 |> put_view(AccountView)
600 |> render("relationship.json", %{user: followed, target: follower})
601 else
602 {:error, message} ->
603 conn
604 |> put_resp_content_type("application/json")
605 |> send_resp(403, Jason.encode!(%{"error" => message}))
606 end
607 end
608
609 def reject_follow_request(%{assigns: %{user: followed}} = conn, %{"id" => id}) do
610 with %User{} = follower <- Repo.get(User, id),
611 %Activity{} = follow_activity <- Utils.fetch_latest_follow(follower, followed),
612 {:ok, follow_activity} <- Utils.update_follow_state(follow_activity, "reject"),
613 {:ok, _activity} <-
614 ActivityPub.reject(%{
615 to: [follower.ap_id],
616 actor: followed.ap_id,
617 object: follow_activity.data["id"],
618 type: "Reject"
619 }) do
620 conn
621 |> put_view(AccountView)
622 |> render("relationship.json", %{user: followed, target: follower})
623 else
624 {:error, message} ->
625 conn
626 |> put_resp_content_type("application/json")
627 |> send_resp(403, Jason.encode!(%{"error" => message}))
628 end
629 end
630
631 def follow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
632 with %User{} = followed <- Repo.get(User, id),
633 {:ok, follower} <- User.maybe_direct_follow(follower, followed),
634 {:ok, _activity} <- ActivityPub.follow(follower, followed),
635 {:ok, follower, followed} <-
636 User.wait_and_refresh(
637 Pleroma.Config.get([:activitypub, :follow_handshake_timeout]),
638 follower,
639 followed
640 ) do
641 conn
642 |> put_view(AccountView)
643 |> render("relationship.json", %{user: follower, target: followed})
644 else
645 {:error, message} ->
646 conn
647 |> put_resp_content_type("application/json")
648 |> send_resp(403, Jason.encode!(%{"error" => message}))
649 end
650 end
651
652 def follow(%{assigns: %{user: follower}} = conn, %{"uri" => uri}) do
653 with %User{} = followed <- Repo.get_by(User, nickname: uri),
654 {:ok, follower} <- User.maybe_direct_follow(follower, followed),
655 {:ok, _activity} <- ActivityPub.follow(follower, followed) do
656 conn
657 |> put_view(AccountView)
658 |> render("account.json", %{user: followed, for: follower})
659 else
660 {:error, message} ->
661 conn
662 |> put_resp_content_type("application/json")
663 |> send_resp(403, Jason.encode!(%{"error" => message}))
664 end
665 end
666
667 def unfollow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
668 with %User{} = followed <- Repo.get(User, id),
669 {:ok, _activity} <- ActivityPub.unfollow(follower, followed),
670 {:ok, follower, _} <- User.unfollow(follower, followed) do
671 conn
672 |> put_view(AccountView)
673 |> render("relationship.json", %{user: follower, target: followed})
674 end
675 end
676
677 def block(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
678 with %User{} = blocked <- Repo.get(User, id),
679 {:ok, blocker} <- User.block(blocker, blocked),
680 {:ok, _activity} <- ActivityPub.block(blocker, blocked) do
681 conn
682 |> put_view(AccountView)
683 |> render("relationship.json", %{user: blocker, target: blocked})
684 else
685 {:error, message} ->
686 conn
687 |> put_resp_content_type("application/json")
688 |> send_resp(403, Jason.encode!(%{"error" => message}))
689 end
690 end
691
692 def unblock(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
693 with %User{} = blocked <- Repo.get(User, id),
694 {:ok, blocker} <- User.unblock(blocker, blocked),
695 {:ok, _activity} <- ActivityPub.unblock(blocker, blocked) do
696 conn
697 |> put_view(AccountView)
698 |> render("relationship.json", %{user: blocker, target: blocked})
699 else
700 {:error, message} ->
701 conn
702 |> put_resp_content_type("application/json")
703 |> send_resp(403, Jason.encode!(%{"error" => message}))
704 end
705 end
706
707 # TODO: Use proper query
708 def blocks(%{assigns: %{user: user}} = conn, _) do
709 with blocked_users <- user.info.blocks || [],
710 accounts <- Enum.map(blocked_users, fn ap_id -> User.get_cached_by_ap_id(ap_id) end) do
711 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
712 json(conn, res)
713 end
714 end
715
716 def domain_blocks(%{assigns: %{user: %{info: info}}} = conn, _) do
717 json(conn, info.domain_blocks || [])
718 end
719
720 def block_domain(%{assigns: %{user: blocker}} = conn, %{"domain" => domain}) do
721 User.block_domain(blocker, domain)
722 json(conn, %{})
723 end
724
725 def unblock_domain(%{assigns: %{user: blocker}} = conn, %{"domain" => domain}) do
726 User.unblock_domain(blocker, domain)
727 json(conn, %{})
728 end
729
730 def status_search(query) do
731 fetched =
732 if Regex.match?(~r/https?:/, query) do
733 with {:ok, object} <- ActivityPub.fetch_object_from_id(query) do
734 [Activity.get_create_activity_by_object_ap_id(object.data["id"])]
735 else
736 _e -> []
737 end
738 end || []
739
740 q =
741 from(
742 a in Activity,
743 where: fragment("?->>'type' = 'Create'", a.data),
744 where: "https://www.w3.org/ns/activitystreams#Public" in a.recipients,
745 where:
746 fragment(
747 "to_tsvector('english', ?->'object'->>'content') @@ plainto_tsquery('english', ?)",
748 a.data,
749 ^query
750 ),
751 limit: 20,
752 order_by: [desc: :id]
753 )
754
755 Repo.all(q) ++ fetched
756 end
757
758 def search2(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
759 accounts = User.search(query, params["resolve"] == "true")
760
761 statuses = status_search(query)
762
763 tags_path = Web.base_url() <> "/tag/"
764
765 tags =
766 String.split(query)
767 |> Enum.uniq()
768 |> Enum.filter(fn tag -> String.starts_with?(tag, "#") end)
769 |> Enum.map(fn tag -> String.slice(tag, 1..-1) end)
770 |> Enum.map(fn tag -> %{name: tag, url: tags_path <> tag} end)
771
772 res = %{
773 "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
774 "statuses" =>
775 StatusView.render("index.json", activities: statuses, for: user, as: :activity),
776 "hashtags" => tags
777 }
778
779 json(conn, res)
780 end
781
782 def search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
783 accounts = User.search(query, params["resolve"] == "true")
784
785 statuses = status_search(query)
786
787 tags =
788 String.split(query)
789 |> Enum.uniq()
790 |> Enum.filter(fn tag -> String.starts_with?(tag, "#") end)
791 |> Enum.map(fn tag -> String.slice(tag, 1..-1) end)
792
793 res = %{
794 "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
795 "statuses" =>
796 StatusView.render("index.json", activities: statuses, for: user, as: :activity),
797 "hashtags" => tags
798 }
799
800 json(conn, res)
801 end
802
803 def account_search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
804 accounts = User.search(query, params["resolve"] == "true")
805
806 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
807
808 json(conn, res)
809 end
810
811 def favourites(%{assigns: %{user: user}} = conn, _) do
812 params =
813 %{}
814 |> Map.put("type", "Create")
815 |> Map.put("favorited_by", user.ap_id)
816 |> Map.put("blocking_user", user)
817
818 activities =
819 ActivityPub.fetch_public_activities(params)
820 |> Enum.reverse()
821
822 conn
823 |> put_view(StatusView)
824 |> render("index.json", %{activities: activities, for: user, as: :activity})
825 end
826
827 def get_lists(%{assigns: %{user: user}} = conn, opts) do
828 lists = Pleroma.List.for_user(user, opts)
829 res = ListView.render("lists.json", lists: lists)
830 json(conn, res)
831 end
832
833 def get_list(%{assigns: %{user: user}} = conn, %{"id" => id}) do
834 with %Pleroma.List{} = list <- Pleroma.List.get(id, user) do
835 res = ListView.render("list.json", list: list)
836 json(conn, res)
837 else
838 _e -> json(conn, "error")
839 end
840 end
841
842 def account_lists(%{assigns: %{user: user}} = conn, %{"id" => account_id}) do
843 lists = Pleroma.List.get_lists_account_belongs(user, account_id)
844 res = ListView.render("lists.json", lists: lists)
845 json(conn, res)
846 end
847
848 def delete_list(%{assigns: %{user: user}} = conn, %{"id" => id}) do
849 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
850 {:ok, _list} <- Pleroma.List.delete(list) do
851 json(conn, %{})
852 else
853 _e ->
854 json(conn, "error")
855 end
856 end
857
858 def create_list(%{assigns: %{user: user}} = conn, %{"title" => title}) do
859 with {:ok, %Pleroma.List{} = list} <- Pleroma.List.create(title, user) do
860 res = ListView.render("list.json", list: list)
861 json(conn, res)
862 end
863 end
864
865 def add_to_list(%{assigns: %{user: user}} = conn, %{"id" => id, "account_ids" => accounts}) do
866 accounts
867 |> Enum.each(fn account_id ->
868 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
869 %User{} = followed <- Repo.get(User, account_id) do
870 Pleroma.List.follow(list, followed)
871 end
872 end)
873
874 json(conn, %{})
875 end
876
877 def remove_from_list(%{assigns: %{user: user}} = conn, %{"id" => id, "account_ids" => accounts}) do
878 accounts
879 |> Enum.each(fn account_id ->
880 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
881 %User{} = followed <- Repo.get(Pleroma.User, account_id) do
882 Pleroma.List.unfollow(list, followed)
883 end
884 end)
885
886 json(conn, %{})
887 end
888
889 def list_accounts(%{assigns: %{user: user}} = conn, %{"id" => id}) do
890 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
891 {:ok, users} = Pleroma.List.get_following(list) do
892 conn
893 |> put_view(AccountView)
894 |> render("accounts.json", %{users: users, as: :user})
895 end
896 end
897
898 def rename_list(%{assigns: %{user: user}} = conn, %{"id" => id, "title" => title}) do
899 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
900 {:ok, list} <- Pleroma.List.rename(list, title) do
901 res = ListView.render("list.json", list: list)
902 json(conn, res)
903 else
904 _e ->
905 json(conn, "error")
906 end
907 end
908
909 def list_timeline(%{assigns: %{user: user}} = conn, %{"list_id" => id} = params) do
910 with %Pleroma.List{title: _title, following: following} <- Pleroma.List.get(id, user) do
911 params =
912 params
913 |> Map.put("type", "Create")
914 |> Map.put("blocking_user", user)
915
916 # we must filter the following list for the user to avoid leaking statuses the user
917 # does not actually have permission to see (for more info, peruse security issue #270).
918 following_to =
919 following
920 |> Enum.filter(fn x -> x in user.following end)
921
922 activities =
923 ActivityPub.fetch_activities_bounded(following_to, following, params)
924 |> Enum.reverse()
925
926 conn
927 |> put_view(StatusView)
928 |> render("index.json", %{activities: activities, for: user, as: :activity})
929 else
930 _e ->
931 conn
932 |> put_status(403)
933 |> json(%{error: "Error."})
934 end
935 end
936
937 def index(%{assigns: %{user: user}} = conn, _params) do
938 token =
939 conn
940 |> get_session(:oauth_token)
941
942 if user && token do
943 mastodon_emoji = mastodonized_emoji()
944
945 limit = Pleroma.Config.get([:instance, :limit])
946
947 accounts =
948 Map.put(%{}, user.id, AccountView.render("account.json", %{user: user, for: user}))
949
950 initial_state =
951 %{
952 meta: %{
953 streaming_api_base_url:
954 String.replace(Pleroma.Web.Endpoint.static_url(), "http", "ws"),
955 access_token: token,
956 locale: "en",
957 domain: Pleroma.Web.Endpoint.host(),
958 admin: "1",
959 me: "#{user.id}",
960 unfollow_modal: false,
961 boost_modal: false,
962 delete_modal: true,
963 auto_play_gif: false,
964 display_sensitive_media: false,
965 reduce_motion: false,
966 max_toot_chars: limit
967 },
968 rights: %{
969 delete_others_notice: !!user.info.is_moderator,
970 admin: !!user.info.is_admin
971 },
972 compose: %{
973 me: "#{user.id}",
974 default_privacy: user.info.default_scope,
975 default_sensitive: false
976 },
977 media_attachments: %{
978 accept_content_types: [
979 ".jpg",
980 ".jpeg",
981 ".png",
982 ".gif",
983 ".webm",
984 ".mp4",
985 ".m4v",
986 "image\/jpeg",
987 "image\/png",
988 "image\/gif",
989 "video\/webm",
990 "video\/mp4"
991 ]
992 },
993 settings:
994 user.info.settings ||
995 %{
996 onboarded: true,
997 home: %{
998 shows: %{
999 reblog: true,
1000 reply: true
1001 }
1002 },
1003 notifications: %{
1004 alerts: %{
1005 follow: true,
1006 favourite: true,
1007 reblog: true,
1008 mention: true
1009 },
1010 shows: %{
1011 follow: true,
1012 favourite: true,
1013 reblog: true,
1014 mention: true
1015 },
1016 sounds: %{
1017 follow: true,
1018 favourite: true,
1019 reblog: true,
1020 mention: true
1021 }
1022 }
1023 },
1024 push_subscription: nil,
1025 accounts: accounts,
1026 custom_emojis: mastodon_emoji,
1027 char_limit: limit
1028 }
1029 |> Jason.encode!()
1030
1031 conn
1032 |> put_layout(false)
1033 |> put_view(MastodonView)
1034 |> render("index.html", %{initial_state: initial_state})
1035 else
1036 conn
1037 |> redirect(to: "/web/login")
1038 end
1039 end
1040
1041 def put_settings(%{assigns: %{user: user}} = conn, %{"data" => settings} = _params) do
1042 info_cng = User.Info.mastodon_settings_update(user.info, settings)
1043
1044 with changeset <- Ecto.Changeset.change(user),
1045 changeset <- Ecto.Changeset.put_embed(changeset, :info, info_cng),
1046 {:ok, _user} <- User.update_and_set_cache(changeset) do
1047 json(conn, %{})
1048 else
1049 e ->
1050 conn
1051 |> put_resp_content_type("application/json")
1052 |> send_resp(500, Jason.encode!(%{"error" => inspect(e)}))
1053 end
1054 end
1055
1056 def login(conn, %{"code" => code}) do
1057 with {:ok, app} <- get_or_make_app(),
1058 %Authorization{} = auth <- Repo.get_by(Authorization, token: code, app_id: app.id),
1059 {:ok, token} <- Token.exchange_token(app, auth) do
1060 conn
1061 |> put_session(:oauth_token, token.token)
1062 |> redirect(to: "/web/getting-started")
1063 end
1064 end
1065
1066 def login(conn, _) do
1067 with {:ok, app} <- get_or_make_app() do
1068 path =
1069 o_auth_path(conn, :authorize,
1070 response_type: "code",
1071 client_id: app.client_id,
1072 redirect_uri: ".",
1073 scope: app.scopes
1074 )
1075
1076 conn
1077 |> redirect(to: path)
1078 end
1079 end
1080
1081 defp get_or_make_app() do
1082 with %App{} = app <- Repo.get_by(App, client_name: "Mastodon-Local") do
1083 {:ok, app}
1084 else
1085 _e ->
1086 cs =
1087 App.register_changeset(%App{}, %{
1088 client_name: "Mastodon-Local",
1089 redirect_uris: ".",
1090 scopes: "read,write,follow"
1091 })
1092
1093 Repo.insert(cs)
1094 end
1095 end
1096
1097 def logout(conn, _) do
1098 conn
1099 |> clear_session
1100 |> redirect(to: "/")
1101 end
1102
1103 def relationship_noop(%{assigns: %{user: user}} = conn, %{"id" => id}) do
1104 Logger.debug("Unimplemented, returning unmodified relationship")
1105
1106 with %User{} = target <- Repo.get(User, id) do
1107 conn
1108 |> put_view(AccountView)
1109 |> render("relationship.json", %{user: user, target: target})
1110 end
1111 end
1112
1113 def empty_array(conn, _) do
1114 Logger.debug("Unimplemented, returning an empty array")
1115 json(conn, [])
1116 end
1117
1118 def empty_object(conn, _) do
1119 Logger.debug("Unimplemented, returning an empty object")
1120 json(conn, %{})
1121 end
1122
1123 def render_notification(user, %{id: id, activity: activity, inserted_at: created_at} = _params) do
1124 actor = User.get_cached_by_ap_id(activity.data["actor"])
1125 parent_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
1126 mastodon_type = Activity.mastodon_notification_type(activity)
1127
1128 response = %{
1129 id: to_string(id),
1130 type: mastodon_type,
1131 created_at: CommonAPI.Utils.to_masto_date(created_at),
1132 account: AccountView.render("account.json", %{user: actor, for: user})
1133 }
1134
1135 case mastodon_type do
1136 "mention" ->
1137 response
1138 |> Map.merge(%{
1139 status: StatusView.render("status.json", %{activity: activity, for: user})
1140 })
1141
1142 "favourite" ->
1143 response
1144 |> Map.merge(%{
1145 status: StatusView.render("status.json", %{activity: parent_activity, for: user})
1146 })
1147
1148 "reblog" ->
1149 response
1150 |> Map.merge(%{
1151 status: StatusView.render("status.json", %{activity: parent_activity, for: user})
1152 })
1153
1154 "follow" ->
1155 response
1156
1157 _ ->
1158 nil
1159 end
1160 end
1161
1162 def get_filters(%{assigns: %{user: user}} = conn, _) do
1163 filters = Pleroma.Filter.get_filters(user)
1164 res = FilterView.render("filters.json", filters: filters)
1165 json(conn, res)
1166 end
1167
1168 def create_filter(
1169 %{assigns: %{user: user}} = conn,
1170 %{"phrase" => phrase, "context" => context} = params
1171 ) do
1172 query = %Pleroma.Filter{
1173 user_id: user.id,
1174 phrase: phrase,
1175 context: context,
1176 hide: Map.get(params, "irreversible", nil),
1177 whole_word: Map.get(params, "boolean", true)
1178 # expires_at
1179 }
1180
1181 {:ok, response} = Pleroma.Filter.create(query)
1182 res = FilterView.render("filter.json", filter: response)
1183 json(conn, res)
1184 end
1185
1186 def get_filter(%{assigns: %{user: user}} = conn, %{"id" => filter_id}) do
1187 filter = Pleroma.Filter.get(filter_id, user)
1188 res = FilterView.render("filter.json", filter: filter)
1189 json(conn, res)
1190 end
1191
1192 def update_filter(
1193 %{assigns: %{user: user}} = conn,
1194 %{"phrase" => phrase, "context" => context, "id" => filter_id} = params
1195 ) do
1196 query = %Pleroma.Filter{
1197 user_id: user.id,
1198 filter_id: filter_id,
1199 phrase: phrase,
1200 context: context,
1201 hide: Map.get(params, "irreversible", nil),
1202 whole_word: Map.get(params, "boolean", true)
1203 # expires_at
1204 }
1205
1206 {:ok, response} = Pleroma.Filter.update(query)
1207 res = FilterView.render("filter.json", filter: response)
1208 json(conn, res)
1209 end
1210
1211 def delete_filter(%{assigns: %{user: user}} = conn, %{"id" => filter_id}) do
1212 query = %Pleroma.Filter{
1213 user_id: user.id,
1214 filter_id: filter_id
1215 }
1216
1217 {:ok, _} = Pleroma.Filter.delete(query)
1218 json(conn, %{})
1219 end
1220
1221 def create_push_subscription(%{assigns: %{user: user, token: token}} = conn, params) do
1222 true = Pleroma.Web.Push.enabled()
1223 Pleroma.Web.Push.Subscription.delete_if_exists(user, token)
1224 {:ok, subscription} = Pleroma.Web.Push.Subscription.create(user, token, params)
1225 view = PushSubscriptionView.render("push_subscription.json", subscription: subscription)
1226 json(conn, view)
1227 end
1228
1229 def get_push_subscription(%{assigns: %{user: user, token: token}} = conn, _params) do
1230 true = Pleroma.Web.Push.enabled()
1231 subscription = Pleroma.Web.Push.Subscription.get(user, token)
1232 view = PushSubscriptionView.render("push_subscription.json", subscription: subscription)
1233 json(conn, view)
1234 end
1235
1236 def update_push_subscription(
1237 %{assigns: %{user: user, token: token}} = conn,
1238 params
1239 ) do
1240 true = Pleroma.Web.Push.enabled()
1241 {:ok, subscription} = Pleroma.Web.Push.Subscription.update(user, token, params)
1242 view = PushSubscriptionView.render("push_subscription.json", subscription: subscription)
1243 json(conn, view)
1244 end
1245
1246 def delete_push_subscription(%{assigns: %{user: user, token: token}} = conn, _params) do
1247 true = Pleroma.Web.Push.enabled()
1248 {:ok, _response} = Pleroma.Web.Push.Subscription.delete(user, token)
1249 json(conn, %{})
1250 end
1251
1252 def errors(conn, _) do
1253 conn
1254 |> put_status(500)
1255 |> json("Something went wrong")
1256 end
1257
1258 def suggestions(%{assigns: %{user: user}} = conn, _) do
1259 suggestions = Pleroma.Config.get(:suggestions)
1260
1261 if Keyword.get(suggestions, :enabled, false) do
1262 api = Keyword.get(suggestions, :third_party_engine, "")
1263 timeout = Keyword.get(suggestions, :timeout, 5000)
1264 limit = Keyword.get(suggestions, :limit, 23)
1265
1266 host = Pleroma.Config.get([Pleroma.Web.Endpoint, :url, :host])
1267
1268 user = user.nickname
1269 url = String.replace(api, "{{host}}", host) |> String.replace("{{user}}", user)
1270
1271 with {:ok, %{status: 200, body: body}} <-
1272 @httpoison.get(
1273 url,
1274 [],
1275 adapter: [
1276 timeout: timeout,
1277 recv_timeout: timeout
1278 ]
1279 ),
1280 {:ok, data} <- Jason.decode(body) do
1281 data2 =
1282 Enum.slice(data, 0, limit)
1283 |> Enum.map(fn x ->
1284 Map.put(
1285 x,
1286 "id",
1287 case User.get_or_fetch(x["acct"]) do
1288 %{id: id} -> id
1289 _ -> 0
1290 end
1291 )
1292 end)
1293 |> Enum.map(fn x ->
1294 Map.put(x, "avatar", MediaProxy.url(x["avatar"]))
1295 end)
1296 |> Enum.map(fn x ->
1297 Map.put(x, "avatar_static", MediaProxy.url(x["avatar_static"]))
1298 end)
1299
1300 conn
1301 |> json(data2)
1302 else
1303 e -> Logger.error("Could not retrieve suggestions at fetch #{url}, #{inspect(e)}")
1304 end
1305 else
1306 json(conn, [])
1307 end
1308 end
1309
1310 def try_render(conn, target, params)
1311 when is_binary(target) do
1312 res = render(conn, target, params)
1313
1314 if res == nil do
1315 conn
1316 |> put_status(501)
1317 |> json(%{error: "Can't display this activity"})
1318 else
1319 res
1320 end
1321 end
1322
1323 def try_render(conn, _, _) do
1324 conn
1325 |> put_status(501)
1326 |> json(%{error: "Can't display this activity"})
1327 end
1328 end