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