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