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