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