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