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