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