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