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