Update/add OpenBSD config files
[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: json(conn, [])
441
442 def update_media(%{assigns: %{user: user}} = conn, data) do
443 with %Object{} = object <- Repo.get(Object, data["id"]),
444 true <- Object.authorize_mutation(object, user),
445 true <- is_binary(data["description"]),
446 description <- data["description"] do
447 new_data = %{object.data | "name" => description}
448
449 {:ok, _} =
450 object
451 |> Object.change(%{data: new_data})
452 |> Repo.update()
453
454 attachment_data = Map.put(new_data, "id", object.id)
455 render(conn, StatusView, "attachment.json", %{attachment: attachment_data})
456 end
457 end
458
459 def upload(%{assigns: %{user: user}} = conn, %{"file" => file} = data) do
460 with {:ok, object} <-
461 ActivityPub.upload(file,
462 actor: User.ap_id(user),
463 description: Map.get(data, "description")
464 ) do
465 attachment_data = Map.put(object.data, "id", object.id)
466 render(conn, StatusView, "attachment.json", %{attachment: attachment_data})
467 end
468 end
469
470 def favourited_by(conn, %{"id" => id}) do
471 with %Activity{data: %{"object" => %{"likes" => likes}}} <- Repo.get(Activity, id) do
472 q = from(u in User, where: u.ap_id in ^likes)
473 users = Repo.all(q)
474 render(conn, AccountView, "accounts.json", %{users: users, as: :user})
475 else
476 _ -> json(conn, [])
477 end
478 end
479
480 def reblogged_by(conn, %{"id" => id}) do
481 with %Activity{data: %{"object" => %{"announcements" => announces}}} <- Repo.get(Activity, id) do
482 q = from(u in User, where: u.ap_id in ^announces)
483 users = Repo.all(q)
484 render(conn, AccountView, "accounts.json", %{users: users, as: :user})
485 else
486 _ -> json(conn, [])
487 end
488 end
489
490 def hashtag_timeline(%{assigns: %{user: user}} = conn, params) do
491 local_only = params["local"] in [true, "True", "true", "1"]
492
493 params =
494 params
495 |> Map.put("type", "Create")
496 |> Map.put("local_only", local_only)
497 |> Map.put("blocking_user", user)
498 |> Map.put("tag", String.downcase(params["tag"]))
499
500 activities =
501 ActivityPub.fetch_public_activities(params)
502 |> Enum.reverse()
503
504 conn
505 |> add_link_headers(:hashtag_timeline, activities, params["tag"], %{"local" => local_only})
506 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
507 end
508
509 def followers(%{assigns: %{user: for_user}} = conn, %{"id" => id}) do
510 with %User{} = user <- Repo.get(User, id),
511 {:ok, followers} <- User.get_followers(user) do
512 followers =
513 cond do
514 for_user && user.id == for_user.id -> followers
515 user.info.hide_network -> []
516 true -> followers
517 end
518
519 render(conn, AccountView, "accounts.json", %{users: followers, as: :user})
520 end
521 end
522
523 def following(%{assigns: %{user: for_user}} = conn, %{"id" => id}) do
524 with %User{} = user <- Repo.get(User, id),
525 {:ok, followers} <- User.get_friends(user) do
526 followers =
527 cond do
528 for_user && user.id == for_user.id -> followers
529 user.info.hide_network -> []
530 true -> followers
531 end
532
533 render(conn, AccountView, "accounts.json", %{users: followers, as: :user})
534 end
535 end
536
537 def follow_requests(%{assigns: %{user: followed}} = conn, _params) do
538 with {:ok, follow_requests} <- User.get_follow_requests(followed) do
539 render(conn, AccountView, "accounts.json", %{users: follow_requests, as: :user})
540 end
541 end
542
543 def authorize_follow_request(%{assigns: %{user: followed}} = conn, %{"id" => id}) do
544 with %User{} = follower <- Repo.get(User, id),
545 {:ok, follower} <- User.maybe_follow(follower, followed),
546 %Activity{} = follow_activity <- Utils.fetch_latest_follow(follower, followed),
547 {:ok, follow_activity} <- Utils.update_follow_state(follow_activity, "accept"),
548 {:ok, _activity} <-
549 ActivityPub.accept(%{
550 to: [follower.ap_id],
551 actor: followed.ap_id,
552 object: follow_activity.data["id"],
553 type: "Accept"
554 }) do
555 render(conn, AccountView, "relationship.json", %{user: followed, target: follower})
556 else
557 {:error, message} ->
558 conn
559 |> put_resp_content_type("application/json")
560 |> send_resp(403, Jason.encode!(%{"error" => message}))
561 end
562 end
563
564 def reject_follow_request(%{assigns: %{user: followed}} = conn, %{"id" => id}) do
565 with %User{} = follower <- Repo.get(User, id),
566 %Activity{} = follow_activity <- Utils.fetch_latest_follow(follower, followed),
567 {:ok, follow_activity} <- Utils.update_follow_state(follow_activity, "reject"),
568 {:ok, _activity} <-
569 ActivityPub.reject(%{
570 to: [follower.ap_id],
571 actor: followed.ap_id,
572 object: follow_activity.data["id"],
573 type: "Reject"
574 }) do
575 render(conn, AccountView, "relationship.json", %{user: followed, target: follower})
576 else
577 {:error, message} ->
578 conn
579 |> put_resp_content_type("application/json")
580 |> send_resp(403, Jason.encode!(%{"error" => message}))
581 end
582 end
583
584 def follow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
585 with %User{} = followed <- Repo.get(User, id),
586 {:ok, follower} <- User.maybe_direct_follow(follower, followed),
587 {:ok, _activity} <- ActivityPub.follow(follower, followed),
588 {:ok, follower, followed} <-
589 User.wait_and_refresh(
590 Pleroma.Config.get([:activitypub, :follow_handshake_timeout]),
591 follower,
592 followed
593 ) do
594 render(conn, AccountView, "relationship.json", %{user: follower, target: followed})
595 else
596 {:error, message} ->
597 conn
598 |> put_resp_content_type("application/json")
599 |> send_resp(403, Jason.encode!(%{"error" => message}))
600 end
601 end
602
603 def follow(%{assigns: %{user: follower}} = conn, %{"uri" => uri}) do
604 with %User{} = followed <- Repo.get_by(User, nickname: uri),
605 {:ok, follower} <- User.maybe_direct_follow(follower, followed),
606 {:ok, _activity} <- ActivityPub.follow(follower, followed) do
607 render(conn, AccountView, "account.json", %{user: followed, for: follower})
608 else
609 {:error, message} ->
610 conn
611 |> put_resp_content_type("application/json")
612 |> send_resp(403, Jason.encode!(%{"error" => message}))
613 end
614 end
615
616 def unfollow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
617 with %User{} = followed <- Repo.get(User, id),
618 {:ok, _activity} <- ActivityPub.unfollow(follower, followed),
619 {:ok, follower, _} <- User.unfollow(follower, followed) do
620 render(conn, AccountView, "relationship.json", %{user: follower, target: followed})
621 end
622 end
623
624 def block(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
625 with %User{} = blocked <- Repo.get(User, id),
626 {:ok, blocker} <- User.block(blocker, blocked),
627 {:ok, _activity} <- ActivityPub.block(blocker, blocked) do
628 render(conn, AccountView, "relationship.json", %{user: blocker, target: blocked})
629 else
630 {:error, message} ->
631 conn
632 |> put_resp_content_type("application/json")
633 |> send_resp(403, Jason.encode!(%{"error" => message}))
634 end
635 end
636
637 def unblock(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
638 with %User{} = blocked <- Repo.get(User, id),
639 {:ok, blocker} <- User.unblock(blocker, blocked),
640 {:ok, _activity} <- ActivityPub.unblock(blocker, blocked) do
641 render(conn, AccountView, "relationship.json", %{user: blocker, target: blocked})
642 else
643 {:error, message} ->
644 conn
645 |> put_resp_content_type("application/json")
646 |> send_resp(403, Jason.encode!(%{"error" => message}))
647 end
648 end
649
650 # TODO: Use proper query
651 def blocks(%{assigns: %{user: user}} = conn, _) do
652 with blocked_users <- user.info.blocks || [],
653 accounts <- Enum.map(blocked_users, fn ap_id -> User.get_cached_by_ap_id(ap_id) end) do
654 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
655 json(conn, res)
656 end
657 end
658
659 def domain_blocks(%{assigns: %{user: %{info: info}}} = conn, _) do
660 json(conn, info.domain_blocks || [])
661 end
662
663 def block_domain(%{assigns: %{user: blocker}} = conn, %{"domain" => domain}) do
664 User.block_domain(blocker, domain)
665 json(conn, %{})
666 end
667
668 def unblock_domain(%{assigns: %{user: blocker}} = conn, %{"domain" => domain}) do
669 User.unblock_domain(blocker, domain)
670 json(conn, %{})
671 end
672
673 def status_search(query) do
674 fetched =
675 if Regex.match?(~r/https?:/, query) do
676 with {:ok, object} <- ActivityPub.fetch_object_from_id(query) do
677 [Activity.get_create_activity_by_object_ap_id(object.data["id"])]
678 else
679 _e -> []
680 end
681 end || []
682
683 q =
684 from(
685 a in Activity,
686 where: fragment("?->>'type' = 'Create'", a.data),
687 where: "https://www.w3.org/ns/activitystreams#Public" in a.recipients,
688 where:
689 fragment(
690 "to_tsvector('english', ?->'object'->>'content') @@ plainto_tsquery('english', ?)",
691 a.data,
692 ^query
693 ),
694 limit: 20,
695 order_by: [desc: :id]
696 )
697
698 Repo.all(q) ++ fetched
699 end
700
701 def search2(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
702 accounts = User.search(query, params["resolve"] == "true")
703
704 statuses = status_search(query)
705
706 tags_path = Web.base_url() <> "/tag/"
707
708 tags =
709 String.split(query)
710 |> Enum.uniq()
711 |> Enum.filter(fn tag -> String.starts_with?(tag, "#") end)
712 |> Enum.map(fn tag -> String.slice(tag, 1..-1) end)
713 |> Enum.map(fn tag -> %{name: tag, url: tags_path <> tag} end)
714
715 res = %{
716 "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
717 "statuses" =>
718 StatusView.render("index.json", activities: statuses, for: user, as: :activity),
719 "hashtags" => tags
720 }
721
722 json(conn, res)
723 end
724
725 def search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
726 accounts = User.search(query, params["resolve"] == "true")
727
728 statuses = status_search(query)
729
730 tags =
731 String.split(query)
732 |> Enum.uniq()
733 |> Enum.filter(fn tag -> String.starts_with?(tag, "#") end)
734 |> Enum.map(fn tag -> String.slice(tag, 1..-1) end)
735
736 res = %{
737 "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
738 "statuses" =>
739 StatusView.render("index.json", activities: statuses, for: user, as: :activity),
740 "hashtags" => tags
741 }
742
743 json(conn, res)
744 end
745
746 def account_search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
747 accounts = User.search(query, params["resolve"] == "true")
748
749 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
750
751 json(conn, res)
752 end
753
754 def favourites(%{assigns: %{user: user}} = conn, _) do
755 params =
756 %{}
757 |> Map.put("type", "Create")
758 |> Map.put("favorited_by", user.ap_id)
759 |> Map.put("blocking_user", user)
760
761 activities =
762 ActivityPub.fetch_public_activities(params)
763 |> Enum.reverse()
764
765 conn
766 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
767 end
768
769 def get_lists(%{assigns: %{user: user}} = conn, opts) do
770 lists = Pleroma.List.for_user(user, opts)
771 res = ListView.render("lists.json", lists: lists)
772 json(conn, res)
773 end
774
775 def get_list(%{assigns: %{user: user}} = conn, %{"id" => id}) do
776 with %Pleroma.List{} = list <- Pleroma.List.get(id, user) do
777 res = ListView.render("list.json", list: list)
778 json(conn, res)
779 else
780 _e -> json(conn, "error")
781 end
782 end
783
784 def account_lists(%{assigns: %{user: user}} = conn, %{"id" => account_id}) do
785 lists = Pleroma.List.get_lists_account_belongs(user, account_id)
786 res = ListView.render("lists.json", lists: lists)
787 json(conn, res)
788 end
789
790 def delete_list(%{assigns: %{user: user}} = conn, %{"id" => id}) do
791 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
792 {:ok, _list} <- Pleroma.List.delete(list) do
793 json(conn, %{})
794 else
795 _e ->
796 json(conn, "error")
797 end
798 end
799
800 def create_list(%{assigns: %{user: user}} = conn, %{"title" => title}) do
801 with {:ok, %Pleroma.List{} = list} <- Pleroma.List.create(title, user) do
802 res = ListView.render("list.json", list: list)
803 json(conn, res)
804 end
805 end
806
807 def add_to_list(%{assigns: %{user: user}} = conn, %{"id" => id, "account_ids" => accounts}) do
808 accounts
809 |> Enum.each(fn account_id ->
810 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
811 %User{} = followed <- Repo.get(User, account_id) do
812 Pleroma.List.follow(list, followed)
813 end
814 end)
815
816 json(conn, %{})
817 end
818
819 def remove_from_list(%{assigns: %{user: user}} = conn, %{"id" => id, "account_ids" => accounts}) do
820 accounts
821 |> Enum.each(fn account_id ->
822 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
823 %User{} = followed <- Repo.get(Pleroma.User, account_id) do
824 Pleroma.List.unfollow(list, followed)
825 end
826 end)
827
828 json(conn, %{})
829 end
830
831 def list_accounts(%{assigns: %{user: user}} = conn, %{"id" => id}) do
832 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
833 {:ok, users} = Pleroma.List.get_following(list) do
834 render(conn, AccountView, "accounts.json", %{users: users, as: :user})
835 end
836 end
837
838 def rename_list(%{assigns: %{user: user}} = conn, %{"id" => id, "title" => title}) do
839 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
840 {:ok, list} <- Pleroma.List.rename(list, title) do
841 res = ListView.render("list.json", list: list)
842 json(conn, res)
843 else
844 _e ->
845 json(conn, "error")
846 end
847 end
848
849 def list_timeline(%{assigns: %{user: user}} = conn, %{"list_id" => id} = params) do
850 with %Pleroma.List{title: _title, following: following} <- Pleroma.List.get(id, user) do
851 params =
852 params
853 |> Map.put("type", "Create")
854 |> Map.put("blocking_user", user)
855
856 # we must filter the following list for the user to avoid leaking statuses the user
857 # does not actually have permission to see (for more info, peruse security issue #270).
858 following_to =
859 following
860 |> Enum.filter(fn x -> x in user.following end)
861
862 activities =
863 ActivityPub.fetch_activities_bounded(following_to, following, params)
864 |> Enum.reverse()
865
866 conn
867 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
868 else
869 _e ->
870 conn
871 |> put_status(403)
872 |> json(%{error: "Error."})
873 end
874 end
875
876 def index(%{assigns: %{user: user}} = conn, _params) do
877 token =
878 conn
879 |> get_session(:oauth_token)
880
881 if user && token do
882 mastodon_emoji = mastodonized_emoji()
883
884 limit = Pleroma.Config.get([:instance, :limit])
885
886 accounts =
887 Map.put(%{}, user.id, AccountView.render("account.json", %{user: user, for: user}))
888
889 initial_state =
890 %{
891 meta: %{
892 streaming_api_base_url:
893 String.replace(Pleroma.Web.Endpoint.static_url(), "http", "ws"),
894 access_token: token,
895 locale: "en",
896 domain: Pleroma.Web.Endpoint.host(),
897 admin: "1",
898 me: "#{user.id}",
899 unfollow_modal: false,
900 boost_modal: false,
901 delete_modal: true,
902 auto_play_gif: false,
903 display_sensitive_media: false,
904 reduce_motion: false,
905 max_toot_chars: limit
906 },
907 rights: %{
908 delete_others_notice: !!user.info.is_moderator
909 },
910 compose: %{
911 me: "#{user.id}",
912 default_privacy: user.info.default_scope,
913 default_sensitive: false
914 },
915 media_attachments: %{
916 accept_content_types: [
917 ".jpg",
918 ".jpeg",
919 ".png",
920 ".gif",
921 ".webm",
922 ".mp4",
923 ".m4v",
924 "image\/jpeg",
925 "image\/png",
926 "image\/gif",
927 "video\/webm",
928 "video\/mp4"
929 ]
930 },
931 settings:
932 Map.get(user.info, :settings) ||
933 %{
934 onboarded: true,
935 home: %{
936 shows: %{
937 reblog: true,
938 reply: true
939 }
940 },
941 notifications: %{
942 alerts: %{
943 follow: true,
944 favourite: true,
945 reblog: true,
946 mention: true
947 },
948 shows: %{
949 follow: true,
950 favourite: true,
951 reblog: true,
952 mention: true
953 },
954 sounds: %{
955 follow: true,
956 favourite: true,
957 reblog: true,
958 mention: true
959 }
960 }
961 },
962 push_subscription: nil,
963 accounts: accounts,
964 custom_emojis: mastodon_emoji,
965 char_limit: limit
966 }
967 |> Jason.encode!()
968
969 conn
970 |> put_layout(false)
971 |> render(MastodonView, "index.html", %{initial_state: initial_state})
972 else
973 conn
974 |> redirect(to: "/web/login")
975 end
976 end
977
978 def put_settings(%{assigns: %{user: user}} = conn, %{"data" => settings} = _params) do
979 info_cng = User.Info.mastodon_settings_update(user.info, settings)
980
981 with changeset <- User.update_changeset(user),
982 changeset <- Ecto.Changeset.put_embed(changeset, :info, info_cng),
983 {:ok, _user} <- User.update_and_set_cache(changeset) do
984 json(conn, %{})
985 else
986 e ->
987 json(conn, %{error: inspect(e)})
988 end
989 end
990
991 def login(conn, %{"code" => code}) do
992 with {:ok, app} <- get_or_make_app(),
993 %Authorization{} = auth <- Repo.get_by(Authorization, token: code, app_id: app.id),
994 {:ok, token} <- Token.exchange_token(app, auth) do
995 conn
996 |> put_session(:oauth_token, token.token)
997 |> redirect(to: "/web/getting-started")
998 end
999 end
1000
1001 def login(conn, _) do
1002 with {:ok, app} <- get_or_make_app() do
1003 path =
1004 o_auth_path(conn, :authorize,
1005 response_type: "code",
1006 client_id: app.client_id,
1007 redirect_uri: ".",
1008 scope: app.scopes
1009 )
1010
1011 conn
1012 |> redirect(to: path)
1013 end
1014 end
1015
1016 defp get_or_make_app() do
1017 with %App{} = app <- Repo.get_by(App, client_name: "Mastodon-Local") do
1018 {:ok, app}
1019 else
1020 _e ->
1021 cs =
1022 App.register_changeset(%App{}, %{
1023 client_name: "Mastodon-Local",
1024 redirect_uris: ".",
1025 scopes: "read,write,follow"
1026 })
1027
1028 Repo.insert(cs)
1029 end
1030 end
1031
1032 def logout(conn, _) do
1033 conn
1034 |> clear_session
1035 |> redirect(to: "/")
1036 end
1037
1038 def relationship_noop(%{assigns: %{user: user}} = conn, %{"id" => id}) do
1039 Logger.debug("Unimplemented, returning unmodified relationship")
1040
1041 with %User{} = target <- Repo.get(User, id) do
1042 render(conn, AccountView, "relationship.json", %{user: user, target: target})
1043 end
1044 end
1045
1046 def empty_array(conn, _) do
1047 Logger.debug("Unimplemented, returning an empty array")
1048 json(conn, [])
1049 end
1050
1051 def empty_object(conn, _) do
1052 Logger.debug("Unimplemented, returning an empty object")
1053 json(conn, %{})
1054 end
1055
1056 def render_notification(user, %{id: id, activity: activity, inserted_at: created_at} = _params) do
1057 actor = User.get_cached_by_ap_id(activity.data["actor"])
1058 parent_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
1059 mastodon_type = Activity.mastodon_notification_type(activity)
1060
1061 response = %{
1062 id: to_string(id),
1063 type: mastodon_type,
1064 created_at: CommonAPI.Utils.to_masto_date(created_at),
1065 account: AccountView.render("account.json", %{user: actor, for: user})
1066 }
1067
1068 case mastodon_type do
1069 "mention" ->
1070 response
1071 |> Map.merge(%{
1072 status: StatusView.render("status.json", %{activity: activity, for: user})
1073 })
1074
1075 "favourite" ->
1076 response
1077 |> Map.merge(%{
1078 status: StatusView.render("status.json", %{activity: parent_activity, for: user})
1079 })
1080
1081 "reblog" ->
1082 response
1083 |> Map.merge(%{
1084 status: StatusView.render("status.json", %{activity: parent_activity, for: user})
1085 })
1086
1087 "follow" ->
1088 response
1089
1090 _ ->
1091 nil
1092 end
1093 end
1094
1095 def get_filters(%{assigns: %{user: user}} = conn, _) do
1096 filters = Pleroma.Filter.get_filters(user)
1097 res = FilterView.render("filters.json", filters: filters)
1098 json(conn, res)
1099 end
1100
1101 def create_filter(
1102 %{assigns: %{user: user}} = conn,
1103 %{"phrase" => phrase, "context" => context} = params
1104 ) do
1105 query = %Pleroma.Filter{
1106 user_id: user.id,
1107 phrase: phrase,
1108 context: context,
1109 hide: Map.get(params, "irreversible", nil),
1110 whole_word: Map.get(params, "boolean", true)
1111 # expires_at
1112 }
1113
1114 {:ok, response} = Pleroma.Filter.create(query)
1115 res = FilterView.render("filter.json", filter: response)
1116 json(conn, res)
1117 end
1118
1119 def get_filter(%{assigns: %{user: user}} = conn, %{"id" => filter_id}) do
1120 filter = Pleroma.Filter.get(filter_id, user)
1121 res = FilterView.render("filter.json", filter: filter)
1122 json(conn, res)
1123 end
1124
1125 def update_filter(
1126 %{assigns: %{user: user}} = conn,
1127 %{"phrase" => phrase, "context" => context, "id" => filter_id} = params
1128 ) do
1129 query = %Pleroma.Filter{
1130 user_id: user.id,
1131 filter_id: filter_id,
1132 phrase: phrase,
1133 context: context,
1134 hide: Map.get(params, "irreversible", nil),
1135 whole_word: Map.get(params, "boolean", true)
1136 # expires_at
1137 }
1138
1139 {:ok, response} = Pleroma.Filter.update(query)
1140 res = FilterView.render("filter.json", filter: response)
1141 json(conn, res)
1142 end
1143
1144 def delete_filter(%{assigns: %{user: user}} = conn, %{"id" => filter_id}) do
1145 query = %Pleroma.Filter{
1146 user_id: user.id,
1147 filter_id: filter_id
1148 }
1149
1150 {:ok, _} = Pleroma.Filter.delete(query)
1151 json(conn, %{})
1152 end
1153
1154 def create_push_subscription(%{assigns: %{user: user, token: token}} = conn, params) do
1155 true = Pleroma.Web.Push.enabled()
1156 Pleroma.Web.Push.Subscription.delete_if_exists(user, token)
1157 {:ok, subscription} = Pleroma.Web.Push.Subscription.create(user, token, params)
1158 view = PushSubscriptionView.render("push_subscription.json", subscription: subscription)
1159 json(conn, view)
1160 end
1161
1162 def get_push_subscription(%{assigns: %{user: user, token: token}} = conn, _params) do
1163 true = Pleroma.Web.Push.enabled()
1164 subscription = Pleroma.Web.Push.Subscription.get(user, token)
1165 view = PushSubscriptionView.render("push_subscription.json", subscription: subscription)
1166 json(conn, view)
1167 end
1168
1169 def update_push_subscription(
1170 %{assigns: %{user: user, token: token}} = conn,
1171 params
1172 ) do
1173 true = Pleroma.Web.Push.enabled()
1174 {:ok, subscription} = Pleroma.Web.Push.Subscription.update(user, token, params)
1175 view = PushSubscriptionView.render("push_subscription.json", subscription: subscription)
1176 json(conn, view)
1177 end
1178
1179 def delete_push_subscription(%{assigns: %{user: user, token: token}} = conn, _params) do
1180 true = Pleroma.Web.Push.enabled()
1181 {:ok, _response} = Pleroma.Web.Push.Subscription.delete(user, token)
1182 json(conn, %{})
1183 end
1184
1185 def errors(conn, _) do
1186 conn
1187 |> put_status(500)
1188 |> json("Something went wrong")
1189 end
1190
1191 def suggestions(%{assigns: %{user: user}} = conn, _) do
1192 suggestions = Pleroma.Config.get(:suggestions)
1193
1194 if Keyword.get(suggestions, :enabled, false) do
1195 api = Keyword.get(suggestions, :third_party_engine, "")
1196 timeout = Keyword.get(suggestions, :timeout, 5000)
1197 limit = Keyword.get(suggestions, :limit, 23)
1198
1199 host = Pleroma.Config.get([Pleroma.Web.Endpoint, :url, :host])
1200
1201 user = user.nickname
1202 url = String.replace(api, "{{host}}", host) |> String.replace("{{user}}", user)
1203
1204 with {:ok, %{status: 200, body: body}} <-
1205 @httpoison.get(
1206 url,
1207 [],
1208 adapter: [
1209 timeout: timeout,
1210 recv_timeout: timeout
1211 ]
1212 ),
1213 {:ok, data} <- Jason.decode(body) do
1214 data2 =
1215 Enum.slice(data, 0, limit)
1216 |> Enum.map(fn x ->
1217 Map.put(
1218 x,
1219 "id",
1220 case User.get_or_fetch(x["acct"]) do
1221 %{id: id} -> id
1222 _ -> 0
1223 end
1224 )
1225 end)
1226 |> Enum.map(fn x ->
1227 Map.put(x, "avatar", MediaProxy.url(x["avatar"]))
1228 end)
1229 |> Enum.map(fn x ->
1230 Map.put(x, "avatar_static", MediaProxy.url(x["avatar_static"]))
1231 end)
1232
1233 conn
1234 |> json(data2)
1235 else
1236 e -> Logger.error("Could not retrieve suggestions at fetch #{url}, #{inspect(e)}")
1237 end
1238 else
1239 json(conn, [])
1240 end
1241 end
1242
1243 def try_render(conn, renderer, target, params)
1244 when is_binary(target) do
1245 res = render(conn, renderer, target, params)
1246
1247 if res == nil do
1248 conn
1249 |> put_status(501)
1250 |> json(%{error: "Can't display this activity"})
1251 else
1252 res
1253 end
1254 end
1255
1256 def try_render(conn, _, _, _) do
1257 conn
1258 |> put_status(501)
1259 |> json(%{error: "Can't display this activity"})
1260 end
1261 end