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