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