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