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