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