mastodon api: support descriptions in media api, add PUT endpoint for updating metada...
[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}
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 update_media(%{assigns: %{user: _}} = conn, data) do
432 with %Object{} = object <- Repo.get(Object, data["id"]),
433 true <- is_binary(data["description"]),
434 description <- data["description"] do
435 new_data = %{object.data | "name" => description}
436
437 change = Object.change(object, %{data: new_data})
438 {:ok, media_obj} = Repo.update(change)
439
440 data =
441 new_data
442 |> Map.put("id", object.id)
443
444 render(conn, StatusView, "attachment.json", %{attachment: data})
445 end
446 end
447
448 def upload(%{assigns: %{user: _}} = conn, %{"file" => file} = data) do
449 with {:ok, object} <- ActivityPub.upload(file) do
450 objdata =
451 if Map.has_key?(data, "description") do
452 Map.put(object.data, "name", data["description"])
453 else
454 object.data
455 end
456
457 change = Object.change(object, %{data: objdata})
458 {:ok, object} = Repo.update(change)
459
460 objdata =
461 objdata
462 |> Map.put("id", object.id)
463
464 render(conn, StatusView, "attachment.json", %{attachment: objdata})
465 end
466 end
467
468 def favourited_by(conn, %{"id" => id}) do
469 with %Activity{data: %{"object" => %{"likes" => likes}}} <- Repo.get(Activity, id) do
470 q = from(u in User, where: u.ap_id in ^likes)
471 users = Repo.all(q)
472 render(conn, AccountView, "accounts.json", %{users: users, as: :user})
473 else
474 _ -> json(conn, [])
475 end
476 end
477
478 def reblogged_by(conn, %{"id" => id}) do
479 with %Activity{data: %{"object" => %{"announcements" => announces}}} <- Repo.get(Activity, id) do
480 q = from(u in User, where: u.ap_id in ^announces)
481 users = Repo.all(q)
482 render(conn, AccountView, "accounts.json", %{users: users, as: :user})
483 else
484 _ -> json(conn, [])
485 end
486 end
487
488 def hashtag_timeline(%{assigns: %{user: user}} = conn, params) do
489 local_only = params["local"] in [true, "True", "true", "1"]
490
491 params =
492 params
493 |> Map.put("type", "Create")
494 |> Map.put("local_only", local_only)
495 |> Map.put("blocking_user", user)
496
497 activities =
498 ActivityPub.fetch_public_activities(params)
499 |> Enum.reverse()
500
501 conn
502 |> add_link_headers(:hashtag_timeline, activities, params["tag"], %{"local" => local_only})
503 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
504 end
505
506 # TODO: Pagination
507 def followers(conn, %{"id" => id}) do
508 with %User{} = user <- Repo.get(User, id),
509 {:ok, followers} <- User.get_followers(user) do
510 render(conn, AccountView, "accounts.json", %{users: followers, as: :user})
511 end
512 end
513
514 def following(conn, %{"id" => id}) do
515 with %User{} = user <- Repo.get(User, id),
516 {:ok, followers} <- User.get_friends(user) do
517 render(conn, AccountView, "accounts.json", %{users: followers, as: :user})
518 end
519 end
520
521 def follow_requests(%{assigns: %{user: followed}} = conn, _params) do
522 with {:ok, follow_requests} <- User.get_follow_requests(followed) do
523 render(conn, AccountView, "accounts.json", %{users: follow_requests, as: :user})
524 end
525 end
526
527 def authorize_follow_request(%{assigns: %{user: followed}} = conn, %{"id" => id}) do
528 with %User{} = follower <- Repo.get(User, id),
529 {:ok, follower} <- User.maybe_follow(follower, followed),
530 %Activity{} = follow_activity <- Utils.fetch_latest_follow(follower, followed),
531 {:ok, follow_activity} <- Utils.update_follow_state(follow_activity, "accept"),
532 {:ok, _activity} <-
533 ActivityPub.accept(%{
534 to: [follower.ap_id],
535 actor: followed.ap_id,
536 object: follow_activity.data["id"],
537 type: "Accept"
538 }) do
539 render(conn, AccountView, "relationship.json", %{user: followed, target: follower})
540 else
541 {:error, message} ->
542 conn
543 |> put_resp_content_type("application/json")
544 |> send_resp(403, Jason.encode!(%{"error" => message}))
545 end
546 end
547
548 def reject_follow_request(%{assigns: %{user: followed}} = conn, %{"id" => id}) do
549 with %User{} = follower <- Repo.get(User, id),
550 %Activity{} = follow_activity <- Utils.fetch_latest_follow(follower, followed),
551 {:ok, follow_activity} <- Utils.update_follow_state(follow_activity, "reject"),
552 {:ok, _activity} <-
553 ActivityPub.reject(%{
554 to: [follower.ap_id],
555 actor: followed.ap_id,
556 object: follow_activity.data["id"],
557 type: "Reject"
558 }) do
559 render(conn, AccountView, "relationship.json", %{user: followed, target: follower})
560 else
561 {:error, message} ->
562 conn
563 |> put_resp_content_type("application/json")
564 |> send_resp(403, Jason.encode!(%{"error" => message}))
565 end
566 end
567
568 def follow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
569 with %User{} = followed <- Repo.get(User, id),
570 {:ok, follower} <- User.maybe_direct_follow(follower, followed),
571 {:ok, _activity} <- ActivityPub.follow(follower, followed) do
572 render(conn, AccountView, "relationship.json", %{user: follower, target: followed})
573 else
574 {:error, message} ->
575 conn
576 |> put_resp_content_type("application/json")
577 |> send_resp(403, Jason.encode!(%{"error" => message}))
578 end
579 end
580
581 def follow(%{assigns: %{user: follower}} = conn, %{"uri" => uri}) do
582 with %User{} = followed <- Repo.get_by(User, nickname: uri),
583 {:ok, follower} <- User.maybe_direct_follow(follower, followed),
584 {:ok, _activity} <- ActivityPub.follow(follower, followed) do
585 render(conn, AccountView, "account.json", %{user: followed})
586 else
587 {:error, message} ->
588 conn
589 |> put_resp_content_type("application/json")
590 |> send_resp(403, Jason.encode!(%{"error" => message}))
591 end
592 end
593
594 def unfollow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
595 with %User{} = followed <- Repo.get(User, id),
596 {:ok, _activity} <- ActivityPub.unfollow(follower, followed),
597 {:ok, follower, _} <- User.unfollow(follower, followed) do
598 render(conn, AccountView, "relationship.json", %{user: follower, target: followed})
599 end
600 end
601
602 def block(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
603 with %User{} = blocked <- Repo.get(User, id),
604 {:ok, blocker} <- User.block(blocker, blocked),
605 {:ok, _activity} <- ActivityPub.block(blocker, blocked) do
606 render(conn, AccountView, "relationship.json", %{user: blocker, target: blocked})
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 unblock(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
616 with %User{} = blocked <- Repo.get(User, id),
617 {:ok, blocker} <- User.unblock(blocker, blocked),
618 {:ok, _activity} <- ActivityPub.unblock(blocker, blocked) do
619 render(conn, AccountView, "relationship.json", %{user: blocker, target: blocked})
620 else
621 {:error, message} ->
622 conn
623 |> put_resp_content_type("application/json")
624 |> send_resp(403, Jason.encode!(%{"error" => message}))
625 end
626 end
627
628 # TODO: Use proper query
629 def blocks(%{assigns: %{user: user}} = conn, _) do
630 with blocked_users <- user.info["blocks"] || [],
631 accounts <- Enum.map(blocked_users, fn ap_id -> User.get_cached_by_ap_id(ap_id) end) do
632 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
633 json(conn, res)
634 end
635 end
636
637 def domain_blocks(%{assigns: %{user: %{info: info}}} = conn, _) do
638 json(conn, info["domain_blocks"] || [])
639 end
640
641 def block_domain(%{assigns: %{user: blocker}} = conn, %{"domain" => domain}) do
642 User.block_domain(blocker, domain)
643 json(conn, %{})
644 end
645
646 def unblock_domain(%{assigns: %{user: blocker}} = conn, %{"domain" => domain}) do
647 User.unblock_domain(blocker, domain)
648 json(conn, %{})
649 end
650
651 def search2(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
652 accounts = User.search(query, params["resolve"] == "true")
653
654 fetched =
655 if Regex.match?(~r/https?:/, query) do
656 with {:ok, activities} <- OStatus.fetch_activity_from_url(query) do
657 activities
658 |> Enum.filter(fn
659 %{data: %{"type" => "Create"}} -> true
660 _ -> false
661 end)
662 else
663 _e -> []
664 end
665 end || []
666
667 q =
668 from(
669 a in Activity,
670 where: fragment("?->>'type' = 'Create'", a.data),
671 where: "https://www.w3.org/ns/activitystreams#Public" in a.recipients,
672 where:
673 fragment(
674 "to_tsvector('english', ?->'object'->>'content') @@ plainto_tsquery('english', ?)",
675 a.data,
676 ^query
677 ),
678 limit: 20,
679 order_by: [desc: :id]
680 )
681
682 statuses = Repo.all(q) ++ fetched
683
684 tags_path = Web.base_url() <> "/tag/"
685
686 tags =
687 String.split(query)
688 |> Enum.uniq()
689 |> Enum.filter(fn tag -> String.starts_with?(tag, "#") end)
690 |> Enum.map(fn tag -> String.slice(tag, 1..-1) end)
691 |> Enum.map(fn tag -> %{name: tag, url: tags_path <> tag} end)
692
693 res = %{
694 "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
695 "statuses" =>
696 StatusView.render("index.json", activities: statuses, for: user, as: :activity),
697 "hashtags" => tags
698 }
699
700 json(conn, res)
701 end
702
703 def search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
704 accounts = User.search(query, params["resolve"] == "true")
705
706 fetched =
707 if Regex.match?(~r/https?:/, query) do
708 with {:ok, activities} <- OStatus.fetch_activity_from_url(query) do
709 activities
710 |> Enum.filter(fn
711 %{data: %{"type" => "Create"}} -> true
712 _ -> false
713 end)
714 else
715 _e -> []
716 end
717 end || []
718
719 q =
720 from(
721 a in Activity,
722 where: fragment("?->>'type' = 'Create'", a.data),
723 where: "https://www.w3.org/ns/activitystreams#Public" in a.recipients,
724 where:
725 fragment(
726 "to_tsvector('english', ?->'object'->>'content') @@ plainto_tsquery('english', ?)",
727 a.data,
728 ^query
729 ),
730 limit: 20,
731 order_by: [desc: :id]
732 )
733
734 statuses = Repo.all(q) ++ fetched
735
736 tags =
737 String.split(query)
738 |> Enum.uniq()
739 |> Enum.filter(fn tag -> String.starts_with?(tag, "#") end)
740 |> Enum.map(fn tag -> String.slice(tag, 1..-1) end)
741
742 res = %{
743 "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
744 "statuses" =>
745 StatusView.render("index.json", activities: statuses, for: user, as: :activity),
746 "hashtags" => tags
747 }
748
749 json(conn, res)
750 end
751
752 def account_search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
753 accounts = User.search(query, params["resolve"] == "true")
754
755 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
756
757 json(conn, res)
758 end
759
760 def favourites(%{assigns: %{user: user}} = conn, _) do
761 params =
762 %{}
763 |> Map.put("type", "Create")
764 |> Map.put("favorited_by", user.ap_id)
765 |> Map.put("blocking_user", user)
766
767 activities =
768 ActivityPub.fetch_public_activities(params)
769 |> Enum.reverse()
770
771 conn
772 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
773 end
774
775 def get_lists(%{assigns: %{user: user}} = conn, opts) do
776 lists = Pleroma.List.for_user(user, opts)
777 res = ListView.render("lists.json", lists: lists)
778 json(conn, res)
779 end
780
781 def get_list(%{assigns: %{user: user}} = conn, %{"id" => id}) do
782 with %Pleroma.List{} = list <- Pleroma.List.get(id, user) do
783 res = ListView.render("list.json", list: list)
784 json(conn, res)
785 else
786 _e -> json(conn, "error")
787 end
788 end
789
790 def delete_list(%{assigns: %{user: user}} = conn, %{"id" => id}) do
791 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
792 {:ok, _list} <- Pleroma.List.delete(list) do
793 json(conn, %{})
794 else
795 _e ->
796 json(conn, "error")
797 end
798 end
799
800 def create_list(%{assigns: %{user: user}} = conn, %{"title" => title}) do
801 with {:ok, %Pleroma.List{} = list} <- Pleroma.List.create(title, user) do
802 res = ListView.render("list.json", list: list)
803 json(conn, res)
804 end
805 end
806
807 def add_to_list(%{assigns: %{user: user}} = conn, %{"id" => id, "account_ids" => accounts}) do
808 accounts
809 |> Enum.each(fn account_id ->
810 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
811 %User{} = followed <- Repo.get(User, account_id) do
812 Pleroma.List.follow(list, followed)
813 end
814 end)
815
816 json(conn, %{})
817 end
818
819 def remove_from_list(%{assigns: %{user: user}} = conn, %{"id" => id, "account_ids" => accounts}) do
820 accounts
821 |> Enum.each(fn account_id ->
822 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
823 %User{} = followed <- Repo.get(Pleroma.User, account_id) do
824 Pleroma.List.unfollow(list, followed)
825 end
826 end)
827
828 json(conn, %{})
829 end
830
831 def list_accounts(%{assigns: %{user: user}} = conn, %{"id" => id}) do
832 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
833 {:ok, users} = Pleroma.List.get_following(list) do
834 render(conn, AccountView, "accounts.json", %{users: users, as: :user})
835 end
836 end
837
838 def rename_list(%{assigns: %{user: user}} = conn, %{"id" => id, "title" => title}) do
839 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
840 {:ok, list} <- Pleroma.List.rename(list, title) do
841 res = ListView.render("list.json", list: list)
842 json(conn, res)
843 else
844 _e ->
845 json(conn, "error")
846 end
847 end
848
849 def list_timeline(%{assigns: %{user: user}} = conn, %{"list_id" => id} = params) do
850 with %Pleroma.List{title: title, following: following} <- Pleroma.List.get(id, user) do
851 params =
852 params
853 |> Map.put("type", "Create")
854 |> Map.put("blocking_user", user)
855
856 # adding title is a hack to not make empty lists function like a public timeline
857 activities =
858 ActivityPub.fetch_activities([title | following], params)
859 |> Enum.reverse()
860
861 conn
862 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
863 else
864 _e ->
865 conn
866 |> put_status(403)
867 |> json(%{error: "Error."})
868 end
869 end
870
871 def index(%{assigns: %{user: user}} = conn, _params) do
872 token =
873 conn
874 |> get_session(:oauth_token)
875
876 if user && token do
877 mastodon_emoji = mastodonized_emoji()
878 accounts = Map.put(%{}, user.id, AccountView.render("account.json", %{user: user}))
879
880 initial_state =
881 %{
882 meta: %{
883 streaming_api_base_url:
884 String.replace(Pleroma.Web.Endpoint.static_url(), "http", "ws"),
885 access_token: token,
886 locale: "en",
887 domain: Pleroma.Web.Endpoint.host(),
888 admin: "1",
889 me: "#{user.id}",
890 unfollow_modal: false,
891 boost_modal: false,
892 delete_modal: true,
893 auto_play_gif: false,
894 display_sensitive_media: false,
895 reduce_motion: false,
896 max_toot_chars: Keyword.get(@instance, :limit)
897 },
898 rights: %{
899 delete_others_notice: !!user.info["is_moderator"]
900 },
901 compose: %{
902 me: "#{user.id}",
903 default_privacy: user.info["default_scope"] || "public",
904 default_sensitive: false
905 },
906 media_attachments: %{
907 accept_content_types: [
908 ".jpg",
909 ".jpeg",
910 ".png",
911 ".gif",
912 ".webm",
913 ".mp4",
914 ".m4v",
915 "image\/jpeg",
916 "image\/png",
917 "image\/gif",
918 "video\/webm",
919 "video\/mp4"
920 ]
921 },
922 settings:
923 Map.get(user.info, "settings") ||
924 %{
925 onboarded: true,
926 home: %{
927 shows: %{
928 reblog: true,
929 reply: true
930 }
931 },
932 notifications: %{
933 alerts: %{
934 follow: true,
935 favourite: true,
936 reblog: true,
937 mention: true
938 },
939 shows: %{
940 follow: true,
941 favourite: true,
942 reblog: true,
943 mention: true
944 },
945 sounds: %{
946 follow: true,
947 favourite: true,
948 reblog: true,
949 mention: true
950 }
951 }
952 },
953 push_subscription: nil,
954 accounts: accounts,
955 custom_emojis: mastodon_emoji,
956 char_limit: Keyword.get(@instance, :limit)
957 }
958 |> Jason.encode!()
959
960 conn
961 |> put_layout(false)
962 |> render(MastodonView, "index.html", %{initial_state: initial_state})
963 else
964 conn
965 |> redirect(to: "/web/login")
966 end
967 end
968
969 def put_settings(%{assigns: %{user: user}} = conn, %{"data" => settings} = _params) do
970 with new_info <- Map.put(user.info, "settings", settings),
971 change <- User.info_changeset(user, %{info: new_info}),
972 {:ok, _user} <- User.update_and_set_cache(change) do
973 conn
974 |> json(%{})
975 else
976 e ->
977 conn
978 |> json(%{error: inspect(e)})
979 end
980 end
981
982 def login(conn, _) do
983 conn
984 |> render(MastodonView, "login.html", %{error: false})
985 end
986
987 defp get_or_make_app() do
988 with %App{} = app <- Repo.get_by(App, client_name: "Mastodon-Local") do
989 {:ok, app}
990 else
991 _e ->
992 cs =
993 App.register_changeset(%App{}, %{
994 client_name: "Mastodon-Local",
995 redirect_uris: ".",
996 scopes: "read,write,follow"
997 })
998
999 Repo.insert(cs)
1000 end
1001 end
1002
1003 def login_post(conn, %{"authorization" => %{"name" => name, "password" => password}}) do
1004 with %User{} = user <- User.get_by_nickname_or_email(name),
1005 true <- Pbkdf2.checkpw(password, user.password_hash),
1006 {:ok, app} <- get_or_make_app(),
1007 {:ok, auth} <- Authorization.create_authorization(app, user),
1008 {:ok, token} <- Token.exchange_token(app, auth) do
1009 conn
1010 |> put_session(:oauth_token, token.token)
1011 |> redirect(to: "/web/getting-started")
1012 else
1013 _e ->
1014 conn
1015 |> render(MastodonView, "login.html", %{error: "Wrong username or password"})
1016 end
1017 end
1018
1019 def logout(conn, _) do
1020 conn
1021 |> clear_session
1022 |> redirect(to: "/")
1023 end
1024
1025 def relationship_noop(%{assigns: %{user: user}} = conn, %{"id" => id}) do
1026 Logger.debug("Unimplemented, returning unmodified relationship")
1027
1028 with %User{} = target <- Repo.get(User, id) do
1029 render(conn, AccountView, "relationship.json", %{user: user, target: target})
1030 end
1031 end
1032
1033 def empty_array(conn, _) do
1034 Logger.debug("Unimplemented, returning an empty array")
1035 json(conn, [])
1036 end
1037
1038 def empty_object(conn, _) do
1039 Logger.debug("Unimplemented, returning an empty object")
1040 json(conn, %{})
1041 end
1042
1043 def render_notification(user, %{id: id, activity: activity, inserted_at: created_at} = _params) do
1044 actor = User.get_cached_by_ap_id(activity.data["actor"])
1045
1046 created_at =
1047 NaiveDateTime.to_iso8601(created_at)
1048 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
1049
1050 case activity.data["type"] do
1051 "Create" ->
1052 %{
1053 id: id,
1054 type: "mention",
1055 created_at: created_at,
1056 account: AccountView.render("account.json", %{user: actor}),
1057 status: StatusView.render("status.json", %{activity: activity, for: user})
1058 }
1059
1060 "Like" ->
1061 liked_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
1062
1063 %{
1064 id: id,
1065 type: "favourite",
1066 created_at: created_at,
1067 account: AccountView.render("account.json", %{user: actor}),
1068 status: StatusView.render("status.json", %{activity: liked_activity, for: user})
1069 }
1070
1071 "Announce" ->
1072 announced_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
1073
1074 %{
1075 id: id,
1076 type: "reblog",
1077 created_at: created_at,
1078 account: AccountView.render("account.json", %{user: actor}),
1079 status: StatusView.render("status.json", %{activity: announced_activity, for: user})
1080 }
1081
1082 "Follow" ->
1083 %{
1084 id: id,
1085 type: "follow",
1086 created_at: created_at,
1087 account: AccountView.render("account.json", %{user: actor})
1088 }
1089
1090 _ ->
1091 nil
1092 end
1093 end
1094
1095 def errors(conn, _) do
1096 conn
1097 |> put_status(500)
1098 |> json("Something went wrong")
1099 end
1100 end