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