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