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