{mastodon api, twitter api}: make the follow handshake timeout configurable
[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 |> Enum.reverse()
227
228 conn
229 |> add_link_headers(:home_timeline, activities)
230 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
231 end
232
233 def public_timeline(%{assigns: %{user: user}} = conn, params) do
234 local_only = params["local"] in [true, "True", "true", "1"]
235
236 params =
237 params
238 |> Map.put("type", ["Create", "Announce"])
239 |> Map.put("local_only", local_only)
240 |> Map.put("blocking_user", user)
241
242 activities =
243 ActivityPub.fetch_public_activities(params)
244 |> Enum.reverse()
245
246 conn
247 |> add_link_headers(:public_timeline, activities, false, %{"local" => local_only})
248 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
249 end
250
251 def user_statuses(%{assigns: %{user: reading_user}} = conn, params) do
252 with %User{} = user <- Repo.get(User, params["id"]) do
253 # Since Pleroma has no "pinned" posts feature, we'll just set an empty list here
254 activities =
255 if params["pinned"] == "true" do
256 []
257 else
258 ActivityPub.fetch_user_activities(user, reading_user, params)
259 end
260
261 conn
262 |> add_link_headers(:user_statuses, activities, params["id"])
263 |> render(StatusView, "index.json", %{
264 activities: activities,
265 for: reading_user,
266 as: :activity
267 })
268 end
269 end
270
271 def dm_timeline(%{assigns: %{user: user}} = conn, _params) do
272 query =
273 ActivityPub.fetch_activities_query([user.ap_id], %{"type" => "Create", visibility: "direct"})
274
275 activities = Repo.all(query)
276
277 conn
278 |> add_link_headers(:dm_timeline, activities)
279 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
280 end
281
282 def get_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
283 with %Activity{} = activity <- Repo.get(Activity, id),
284 true <- ActivityPub.visible_for_user?(activity, user) do
285 render(conn, StatusView, "status.json", %{activity: activity, for: user})
286 end
287 end
288
289 def get_context(%{assigns: %{user: user}} = conn, %{"id" => id}) do
290 with %Activity{} = activity <- Repo.get(Activity, id),
291 activities <-
292 ActivityPub.fetch_activities_for_context(activity.data["context"], %{
293 "blocking_user" => user,
294 "user" => user
295 }),
296 activities <-
297 activities |> Enum.filter(fn %{id: aid} -> to_string(aid) != to_string(id) end),
298 activities <-
299 activities |> Enum.filter(fn %{data: %{"type" => type}} -> type == "Create" end),
300 grouped_activities <- Enum.group_by(activities, fn %{id: id} -> id < activity.id end) do
301 result = %{
302 ancestors:
303 StatusView.render(
304 "index.json",
305 for: user,
306 activities: grouped_activities[true] || [],
307 as: :activity
308 )
309 |> Enum.reverse(),
310 descendants:
311 StatusView.render(
312 "index.json",
313 for: user,
314 activities: grouped_activities[false] || [],
315 as: :activity
316 )
317 |> Enum.reverse()
318 }
319
320 json(conn, result)
321 end
322 end
323
324 def post_status(conn, %{"status" => "", "media_ids" => media_ids} = params)
325 when length(media_ids) > 0 do
326 params =
327 params
328 |> Map.put("status", ".")
329
330 post_status(conn, params)
331 end
332
333 def post_status(%{assigns: %{user: user}} = conn, %{"status" => _} = params) do
334 params =
335 params
336 |> Map.put("in_reply_to_status_id", params["in_reply_to_id"])
337 |> Map.put("no_attachment_links", true)
338
339 idempotency_key =
340 case get_req_header(conn, "idempotency-key") do
341 [key] -> key
342 _ -> Ecto.UUID.generate()
343 end
344
345 {:ok, activity} =
346 Cachex.fetch!(:idempotency_cache, idempotency_key, fn _ -> CommonAPI.post(user, params) end)
347
348 render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity})
349 end
350
351 def delete_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
352 with {:ok, %Activity{}} <- CommonAPI.delete(id, user) do
353 json(conn, %{})
354 else
355 _e ->
356 conn
357 |> put_status(403)
358 |> json(%{error: "Can't delete this post"})
359 end
360 end
361
362 def reblog_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
363 with {:ok, announce, _activity} <- CommonAPI.repeat(ap_id_or_id, user) do
364 render(conn, StatusView, "status.json", %{activity: announce, for: user, as: :activity})
365 end
366 end
367
368 def unreblog_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
369 with {:ok, _unannounce, %{data: %{"id" => id}}} <- CommonAPI.unrepeat(ap_id_or_id, user),
370 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
371 render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity})
372 end
373 end
374
375 def fav_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
376 with {:ok, _fav, %{data: %{"id" => id}}} <- CommonAPI.favorite(ap_id_or_id, user),
377 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
378 render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity})
379 end
380 end
381
382 def unfav_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
383 with {:ok, _, _, %{data: %{"id" => id}}} <- CommonAPI.unfavorite(ap_id_or_id, user),
384 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
385 render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity})
386 end
387 end
388
389 def notifications(%{assigns: %{user: user}} = conn, params) do
390 notifications = Notification.for_user(user, params)
391
392 result =
393 Enum.map(notifications, fn x ->
394 render_notification(user, x)
395 end)
396 |> Enum.filter(& &1)
397
398 conn
399 |> add_link_headers(:notifications, notifications)
400 |> json(result)
401 end
402
403 def get_notification(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
404 with {:ok, notification} <- Notification.get(user, id) do
405 json(conn, render_notification(user, notification))
406 else
407 {:error, reason} ->
408 conn
409 |> put_resp_content_type("application/json")
410 |> send_resp(403, Jason.encode!(%{"error" => reason}))
411 end
412 end
413
414 def clear_notifications(%{assigns: %{user: user}} = conn, _params) do
415 Notification.clear(user)
416 json(conn, %{})
417 end
418
419 def dismiss_notification(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
420 with {:ok, _notif} <- Notification.dismiss(user, id) do
421 json(conn, %{})
422 else
423 {:error, reason} ->
424 conn
425 |> put_resp_content_type("application/json")
426 |> send_resp(403, Jason.encode!(%{"error" => reason}))
427 end
428 end
429
430 def relationships(%{assigns: %{user: user}} = conn, %{"id" => id}) do
431 id = List.wrap(id)
432 q = from(u in User, where: u.id in ^id)
433 targets = Repo.all(q)
434 render(conn, AccountView, "relationships.json", %{user: user, targets: targets})
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) do
456 objdata =
457 if Map.has_key?(data, "description") do
458 Map.put(object.data, "name", data["description"])
459 else
460 object.data
461 end
462
463 change = Object.change(object, %{data: objdata})
464 {:ok, object} = Repo.update(change)
465
466 objdata =
467 objdata
468 |> Map.put("id", object.id)
469
470 render(conn, StatusView, "attachment.json", %{attachment: objdata})
471 end
472 end
473
474 def favourited_by(conn, %{"id" => id}) do
475 with %Activity{data: %{"object" => %{"likes" => likes}}} <- Repo.get(Activity, id) do
476 q = from(u in User, where: u.ap_id in ^likes)
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 reblogged_by(conn, %{"id" => id}) do
485 with %Activity{data: %{"object" => %{"announcements" => announces}}} <- Repo.get(Activity, id) do
486 q = from(u in User, where: u.ap_id in ^announces)
487 users = Repo.all(q)
488 render(conn, AccountView, "accounts.json", %{users: users, as: :user})
489 else
490 _ -> json(conn, [])
491 end
492 end
493
494 def hashtag_timeline(%{assigns: %{user: user}} = conn, params) do
495 local_only = params["local"] in [true, "True", "true", "1"]
496
497 params =
498 params
499 |> Map.put("type", "Create")
500 |> Map.put("local_only", local_only)
501 |> Map.put("blocking_user", user)
502
503 activities =
504 ActivityPub.fetch_public_activities(params)
505 |> Enum.reverse()
506
507 conn
508 |> add_link_headers(:hashtag_timeline, activities, params["tag"], %{"local" => local_only})
509 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
510 end
511
512 # TODO: Pagination
513 def followers(conn, %{"id" => id}) do
514 with %User{} = user <- Repo.get(User, id),
515 {:ok, followers} <- User.get_followers(user) do
516 render(conn, AccountView, "accounts.json", %{users: followers, as: :user})
517 end
518 end
519
520 def following(conn, %{"id" => id}) do
521 with %User{} = user <- Repo.get(User, id),
522 {:ok, followers} <- User.get_friends(user) do
523 render(conn, AccountView, "accounts.json", %{users: followers, as: :user})
524 end
525 end
526
527 def follow_requests(%{assigns: %{user: followed}} = conn, _params) do
528 with {:ok, follow_requests} <- User.get_follow_requests(followed) do
529 render(conn, AccountView, "accounts.json", %{users: follow_requests, as: :user})
530 end
531 end
532
533 def authorize_follow_request(%{assigns: %{user: followed}} = conn, %{"id" => id}) do
534 with %User{} = follower <- Repo.get(User, id),
535 {:ok, follower} <- User.maybe_follow(follower, followed),
536 %Activity{} = follow_activity <- Utils.fetch_latest_follow(follower, followed),
537 {:ok, follow_activity} <- Utils.update_follow_state(follow_activity, "accept"),
538 {:ok, _activity} <-
539 ActivityPub.accept(%{
540 to: [follower.ap_id],
541 actor: followed.ap_id,
542 object: follow_activity.data["id"],
543 type: "Accept"
544 }) do
545 render(conn, AccountView, "relationship.json", %{user: followed, target: follower})
546 else
547 {:error, message} ->
548 conn
549 |> put_resp_content_type("application/json")
550 |> send_resp(403, Jason.encode!(%{"error" => message}))
551 end
552 end
553
554 def reject_follow_request(%{assigns: %{user: followed}} = conn, %{"id" => id}) do
555 with %User{} = follower <- Repo.get(User, id),
556 %Activity{} = follow_activity <- Utils.fetch_latest_follow(follower, followed),
557 {:ok, follow_activity} <- Utils.update_follow_state(follow_activity, "reject"),
558 {:ok, _activity} <-
559 ActivityPub.reject(%{
560 to: [follower.ap_id],
561 actor: followed.ap_id,
562 object: follow_activity.data["id"],
563 type: "Reject"
564 }) do
565 render(conn, AccountView, "relationship.json", %{user: followed, target: follower})
566 else
567 {:error, message} ->
568 conn
569 |> put_resp_content_type("application/json")
570 |> send_resp(403, Jason.encode!(%{"error" => message}))
571 end
572 end
573
574 @activitypub Application.get_env(:pleroma, :activitypub)
575 @follow_handshake_timeout Keyword.get(@activitypub, :follow_handshake_timeout)
576
577 def follow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
578 with %User{} = followed <- Repo.get(User, id),
579 {:ok, follower} <- User.maybe_direct_follow(follower, followed),
580 {:ok, _activity} <- ActivityPub.follow(follower, followed),
581 {:ok, follower, followed} <-
582 User.wait_and_refresh(@follow_handshake_timeout, follower, followed) do
583 render(conn, AccountView, "relationship.json", %{user: follower, target: followed})
584 else
585 {:error, message} ->
586 conn
587 |> put_resp_content_type("application/json")
588 |> send_resp(403, Jason.encode!(%{"error" => message}))
589 end
590 end
591
592 def follow(%{assigns: %{user: follower}} = conn, %{"uri" => uri}) do
593 with %User{} = followed <- Repo.get_by(User, nickname: uri),
594 {:ok, follower} <- User.maybe_direct_follow(follower, followed),
595 {:ok, _activity} <- ActivityPub.follow(follower, followed) do
596 render(conn, AccountView, "account.json", %{user: followed, for: follower})
597 else
598 {:error, message} ->
599 conn
600 |> put_resp_content_type("application/json")
601 |> send_resp(403, Jason.encode!(%{"error" => message}))
602 end
603 end
604
605 def unfollow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
606 with %User{} = followed <- Repo.get(User, id),
607 {:ok, _activity} <- ActivityPub.unfollow(follower, followed),
608 {:ok, follower, _} <- User.unfollow(follower, followed) do
609 render(conn, AccountView, "relationship.json", %{user: follower, target: followed})
610 end
611 end
612
613 def block(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
614 with %User{} = blocked <- Repo.get(User, id),
615 {:ok, blocker} <- User.block(blocker, blocked),
616 {:ok, _activity} <- ActivityPub.block(blocker, blocked) do
617 render(conn, AccountView, "relationship.json", %{user: blocker, target: blocked})
618 else
619 {:error, message} ->
620 conn
621 |> put_resp_content_type("application/json")
622 |> send_resp(403, Jason.encode!(%{"error" => message}))
623 end
624 end
625
626 def unblock(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
627 with %User{} = blocked <- Repo.get(User, id),
628 {:ok, blocker} <- User.unblock(blocker, blocked),
629 {:ok, _activity} <- ActivityPub.unblock(blocker, blocked) do
630 render(conn, AccountView, "relationship.json", %{user: blocker, target: blocked})
631 else
632 {:error, message} ->
633 conn
634 |> put_resp_content_type("application/json")
635 |> send_resp(403, Jason.encode!(%{"error" => message}))
636 end
637 end
638
639 # TODO: Use proper query
640 def blocks(%{assigns: %{user: user}} = conn, _) do
641 with blocked_users <- user.info["blocks"] || [],
642 accounts <- Enum.map(blocked_users, fn ap_id -> User.get_cached_by_ap_id(ap_id) end) do
643 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
644 json(conn, res)
645 end
646 end
647
648 def domain_blocks(%{assigns: %{user: %{info: info}}} = conn, _) do
649 json(conn, info["domain_blocks"] || [])
650 end
651
652 def block_domain(%{assigns: %{user: blocker}} = conn, %{"domain" => domain}) do
653 User.block_domain(blocker, domain)
654 json(conn, %{})
655 end
656
657 def unblock_domain(%{assigns: %{user: blocker}} = conn, %{"domain" => domain}) do
658 User.unblock_domain(blocker, domain)
659 json(conn, %{})
660 end
661
662 def status_search(query) do
663 fetched =
664 if Regex.match?(~r/https?:/, query) do
665 with {:ok, object} <- ActivityPub.fetch_object_from_id(query) do
666 [Activity.get_create_activity_by_object_ap_id(object.data["id"])]
667 else
668 _e -> []
669 end
670 end || []
671
672 q =
673 from(
674 a in Activity,
675 where: fragment("?->>'type' = 'Create'", a.data),
676 where: "https://www.w3.org/ns/activitystreams#Public" in a.recipients,
677 where:
678 fragment(
679 "to_tsvector('english', ?->'object'->>'content') @@ plainto_tsquery('english', ?)",
680 a.data,
681 ^query
682 ),
683 limit: 20,
684 order_by: [desc: :id]
685 )
686
687 Repo.all(q) ++ fetched
688 end
689
690 def search2(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
691 accounts = User.search(query, params["resolve"] == "true")
692
693 statuses = status_search(query)
694
695 tags_path = Web.base_url() <> "/tag/"
696
697 tags =
698 String.split(query)
699 |> Enum.uniq()
700 |> Enum.filter(fn tag -> String.starts_with?(tag, "#") end)
701 |> Enum.map(fn tag -> String.slice(tag, 1..-1) end)
702 |> Enum.map(fn tag -> %{name: tag, url: tags_path <> tag} end)
703
704 res = %{
705 "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
706 "statuses" =>
707 StatusView.render("index.json", activities: statuses, for: user, as: :activity),
708 "hashtags" => tags
709 }
710
711 json(conn, res)
712 end
713
714 def search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
715 accounts = User.search(query, params["resolve"] == "true")
716
717 statuses = status_search(query)
718
719 tags =
720 String.split(query)
721 |> Enum.uniq()
722 |> Enum.filter(fn tag -> String.starts_with?(tag, "#") end)
723 |> Enum.map(fn tag -> String.slice(tag, 1..-1) end)
724
725 res = %{
726 "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
727 "statuses" =>
728 StatusView.render("index.json", activities: statuses, for: user, as: :activity),
729 "hashtags" => tags
730 }
731
732 json(conn, res)
733 end
734
735 def account_search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
736 accounts = User.search(query, params["resolve"] == "true")
737
738 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
739
740 json(conn, res)
741 end
742
743 def favourites(%{assigns: %{user: user}} = conn, _) do
744 params =
745 %{}
746 |> Map.put("type", "Create")
747 |> Map.put("favorited_by", user.ap_id)
748 |> Map.put("blocking_user", user)
749
750 activities =
751 ActivityPub.fetch_public_activities(params)
752 |> Enum.reverse()
753
754 conn
755 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
756 end
757
758 def get_lists(%{assigns: %{user: user}} = conn, opts) do
759 lists = Pleroma.List.for_user(user, opts)
760 res = ListView.render("lists.json", lists: lists)
761 json(conn, res)
762 end
763
764 def get_list(%{assigns: %{user: user}} = conn, %{"id" => id}) do
765 with %Pleroma.List{} = list <- Pleroma.List.get(id, user) do
766 res = ListView.render("list.json", list: list)
767 json(conn, res)
768 else
769 _e -> json(conn, "error")
770 end
771 end
772
773 def delete_list(%{assigns: %{user: user}} = conn, %{"id" => id}) do
774 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
775 {:ok, _list} <- Pleroma.List.delete(list) do
776 json(conn, %{})
777 else
778 _e ->
779 json(conn, "error")
780 end
781 end
782
783 def create_list(%{assigns: %{user: user}} = conn, %{"title" => title}) do
784 with {:ok, %Pleroma.List{} = list} <- Pleroma.List.create(title, user) do
785 res = ListView.render("list.json", list: list)
786 json(conn, res)
787 end
788 end
789
790 def add_to_list(%{assigns: %{user: user}} = conn, %{"id" => id, "account_ids" => accounts}) do
791 accounts
792 |> Enum.each(fn account_id ->
793 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
794 %User{} = followed <- Repo.get(User, account_id) do
795 Pleroma.List.follow(list, followed)
796 end
797 end)
798
799 json(conn, %{})
800 end
801
802 def remove_from_list(%{assigns: %{user: user}} = conn, %{"id" => id, "account_ids" => accounts}) do
803 accounts
804 |> Enum.each(fn account_id ->
805 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
806 %User{} = followed <- Repo.get(Pleroma.User, account_id) do
807 Pleroma.List.unfollow(list, followed)
808 end
809 end)
810
811 json(conn, %{})
812 end
813
814 def list_accounts(%{assigns: %{user: user}} = conn, %{"id" => id}) do
815 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
816 {:ok, users} = Pleroma.List.get_following(list) do
817 render(conn, AccountView, "accounts.json", %{users: users, as: :user})
818 end
819 end
820
821 def rename_list(%{assigns: %{user: user}} = conn, %{"id" => id, "title" => title}) do
822 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
823 {:ok, list} <- Pleroma.List.rename(list, title) do
824 res = ListView.render("list.json", list: list)
825 json(conn, res)
826 else
827 _e ->
828 json(conn, "error")
829 end
830 end
831
832 def list_timeline(%{assigns: %{user: user}} = conn, %{"list_id" => id} = params) do
833 with %Pleroma.List{title: title, following: following} <- Pleroma.List.get(id, user) do
834 params =
835 params
836 |> Map.put("type", "Create")
837 |> Map.put("blocking_user", user)
838
839 # we must filter the following list for the user to avoid leaking statuses the user
840 # does not actually have permission to see (for more info, peruse security issue #270).
841 following_to =
842 following
843 |> Enum.filter(fn x -> x in user.following end)
844
845 activities =
846 ActivityPub.fetch_activities_bounded(following_to, following, params)
847 |> Enum.reverse()
848
849 conn
850 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
851 else
852 _e ->
853 conn
854 |> put_status(403)
855 |> json(%{error: "Error."})
856 end
857 end
858
859 def index(%{assigns: %{user: user}} = conn, _params) do
860 token =
861 conn
862 |> get_session(:oauth_token)
863
864 if user && token do
865 mastodon_emoji = mastodonized_emoji()
866
867 accounts =
868 Map.put(%{}, user.id, AccountView.render("account.json", %{user: user, for: user}))
869
870 initial_state =
871 %{
872 meta: %{
873 streaming_api_base_url:
874 String.replace(Pleroma.Web.Endpoint.static_url(), "http", "ws"),
875 access_token: token,
876 locale: "en",
877 domain: Pleroma.Web.Endpoint.host(),
878 admin: "1",
879 me: "#{user.id}",
880 unfollow_modal: false,
881 boost_modal: false,
882 delete_modal: true,
883 auto_play_gif: false,
884 display_sensitive_media: false,
885 reduce_motion: false,
886 max_toot_chars: Keyword.get(@instance, :limit)
887 },
888 rights: %{
889 delete_others_notice: !!user.info["is_moderator"]
890 },
891 compose: %{
892 me: "#{user.id}",
893 default_privacy: user.info["default_scope"] || "public",
894 default_sensitive: false
895 },
896 media_attachments: %{
897 accept_content_types: [
898 ".jpg",
899 ".jpeg",
900 ".png",
901 ".gif",
902 ".webm",
903 ".mp4",
904 ".m4v",
905 "image\/jpeg",
906 "image\/png",
907 "image\/gif",
908 "video\/webm",
909 "video\/mp4"
910 ]
911 },
912 settings:
913 Map.get(user.info, "settings") ||
914 %{
915 onboarded: true,
916 home: %{
917 shows: %{
918 reblog: true,
919 reply: true
920 }
921 },
922 notifications: %{
923 alerts: %{
924 follow: true,
925 favourite: true,
926 reblog: true,
927 mention: true
928 },
929 shows: %{
930 follow: true,
931 favourite: true,
932 reblog: true,
933 mention: true
934 },
935 sounds: %{
936 follow: true,
937 favourite: true,
938 reblog: true,
939 mention: true
940 }
941 }
942 },
943 push_subscription: nil,
944 accounts: accounts,
945 custom_emojis: mastodon_emoji,
946 char_limit: Keyword.get(@instance, :limit)
947 }
948 |> Jason.encode!()
949
950 conn
951 |> put_layout(false)
952 |> render(MastodonView, "index.html", %{initial_state: initial_state})
953 else
954 conn
955 |> redirect(to: "/web/login")
956 end
957 end
958
959 def put_settings(%{assigns: %{user: user}} = conn, %{"data" => settings} = _params) do
960 with new_info <- Map.put(user.info, "settings", settings),
961 change <- User.info_changeset(user, %{info: new_info}),
962 {:ok, _user} <- User.update_and_set_cache(change) do
963 conn
964 |> json(%{})
965 else
966 e ->
967 conn
968 |> json(%{error: inspect(e)})
969 end
970 end
971
972 def login(conn, _) do
973 conn
974 |> render(MastodonView, "login.html", %{error: false})
975 end
976
977 defp get_or_make_app() do
978 with %App{} = app <- Repo.get_by(App, client_name: "Mastodon-Local") do
979 {:ok, app}
980 else
981 _e ->
982 cs =
983 App.register_changeset(%App{}, %{
984 client_name: "Mastodon-Local",
985 redirect_uris: ".",
986 scopes: "read,write,follow"
987 })
988
989 Repo.insert(cs)
990 end
991 end
992
993 def login_post(conn, %{"authorization" => %{"name" => name, "password" => password}}) do
994 with %User{} = user <- User.get_by_nickname_or_email(name),
995 true <- Pbkdf2.checkpw(password, user.password_hash),
996 {:ok, app} <- get_or_make_app(),
997 {:ok, auth} <- Authorization.create_authorization(app, user),
998 {:ok, token} <- Token.exchange_token(app, auth) do
999 conn
1000 |> put_session(:oauth_token, token.token)
1001 |> redirect(to: "/web/getting-started")
1002 else
1003 _e ->
1004 conn
1005 |> render(MastodonView, "login.html", %{error: "Wrong username or password"})
1006 end
1007 end
1008
1009 def logout(conn, _) do
1010 conn
1011 |> clear_session
1012 |> redirect(to: "/")
1013 end
1014
1015 def relationship_noop(%{assigns: %{user: user}} = conn, %{"id" => id}) do
1016 Logger.debug("Unimplemented, returning unmodified relationship")
1017
1018 with %User{} = target <- Repo.get(User, id) do
1019 render(conn, AccountView, "relationship.json", %{user: user, target: target})
1020 end
1021 end
1022
1023 def empty_array(conn, _) do
1024 Logger.debug("Unimplemented, returning an empty array")
1025 json(conn, [])
1026 end
1027
1028 def empty_object(conn, _) do
1029 Logger.debug("Unimplemented, returning an empty object")
1030 json(conn, %{})
1031 end
1032
1033 def render_notification(user, %{id: id, activity: activity, inserted_at: created_at} = _params) do
1034 actor = User.get_cached_by_ap_id(activity.data["actor"])
1035
1036 created_at =
1037 NaiveDateTime.to_iso8601(created_at)
1038 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
1039
1040 id = id |> to_string
1041
1042 case activity.data["type"] do
1043 "Create" ->
1044 %{
1045 id: id,
1046 type: "mention",
1047 created_at: created_at,
1048 account: AccountView.render("account.json", %{user: actor, for: user}),
1049 status: StatusView.render("status.json", %{activity: activity, for: user})
1050 }
1051
1052 "Like" ->
1053 liked_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
1054
1055 %{
1056 id: id,
1057 type: "favourite",
1058 created_at: created_at,
1059 account: AccountView.render("account.json", %{user: actor, for: user}),
1060 status: StatusView.render("status.json", %{activity: liked_activity, for: user})
1061 }
1062
1063 "Announce" ->
1064 announced_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
1065
1066 %{
1067 id: id,
1068 type: "reblog",
1069 created_at: created_at,
1070 account: AccountView.render("account.json", %{user: actor, for: user}),
1071 status: StatusView.render("status.json", %{activity: announced_activity, for: user})
1072 }
1073
1074 "Follow" ->
1075 %{
1076 id: id,
1077 type: "follow",
1078 created_at: created_at,
1079 account: AccountView.render("account.json", %{user: actor, for: user})
1080 }
1081
1082 _ ->
1083 nil
1084 end
1085 end
1086
1087 def get_filters(%{assigns: %{user: user}} = conn, _) do
1088 filters = Pleroma.Filter.get_filters(user)
1089 res = FilterView.render("filters.json", filters: filters)
1090 json(conn, res)
1091 end
1092
1093 def create_filter(
1094 %{assigns: %{user: user}} = conn,
1095 %{"phrase" => phrase, "context" => context} = params
1096 ) do
1097 query = %Pleroma.Filter{
1098 user_id: user.id,
1099 phrase: phrase,
1100 context: context,
1101 hide: Map.get(params, "irreversible", nil),
1102 whole_word: Map.get(params, "boolean", true)
1103 # expires_at
1104 }
1105
1106 {:ok, response} = Pleroma.Filter.create(query)
1107 res = FilterView.render("filter.json", filter: response)
1108 json(conn, res)
1109 end
1110
1111 def get_filter(%{assigns: %{user: user}} = conn, %{"id" => filter_id}) do
1112 filter = Pleroma.Filter.get(filter_id, user)
1113 res = FilterView.render("filter.json", filter: filter)
1114 json(conn, res)
1115 end
1116
1117 def update_filter(
1118 %{assigns: %{user: user}} = conn,
1119 %{"phrase" => phrase, "context" => context, "id" => filter_id} = params
1120 ) do
1121 query = %Pleroma.Filter{
1122 user_id: user.id,
1123 filter_id: filter_id,
1124 phrase: phrase,
1125 context: context,
1126 hide: Map.get(params, "irreversible", nil),
1127 whole_word: Map.get(params, "boolean", true)
1128 # expires_at
1129 }
1130
1131 {:ok, response} = Pleroma.Filter.update(query)
1132 res = FilterView.render("filter.json", filter: response)
1133 json(conn, res)
1134 end
1135
1136 def delete_filter(%{assigns: %{user: user}} = conn, %{"id" => filter_id}) do
1137 query = %Pleroma.Filter{
1138 user_id: user.id,
1139 filter_id: filter_id
1140 }
1141
1142 {:ok, _} = Pleroma.Filter.delete(query)
1143 json(conn, %{})
1144 end
1145
1146 def errors(conn, _) do
1147 conn
1148 |> put_status(500)
1149 |> json("Something went wrong")
1150 end
1151
1152 @suggestions Application.get_env(:pleroma, :suggestions)
1153
1154 def suggestions(%{assigns: %{user: user}} = conn, _) do
1155 if Keyword.get(@suggestions, :enabled, false) do
1156 api = Keyword.get(@suggestions, :third_party_engine, "")
1157 timeout = Keyword.get(@suggestions, :timeout, 5000)
1158 limit = Keyword.get(@suggestions, :limit, 23)
1159
1160 host =
1161 Application.get_env(:pleroma, Pleroma.Web.Endpoint)
1162 |> Keyword.get(:url)
1163 |> Keyword.get(:host)
1164
1165 user = user.nickname
1166 url = String.replace(api, "{{host}}", host) |> String.replace("{{user}}", user)
1167
1168 with {:ok, %{status_code: 200, body: body}} <-
1169 @httpoison.get(url, [], timeout: timeout, recv_timeout: timeout),
1170 {:ok, data} <- Jason.decode(body) do
1171 data2 =
1172 Enum.slice(data, 0, limit)
1173 |> Enum.map(fn x ->
1174 Map.put(
1175 x,
1176 "id",
1177 case User.get_or_fetch(x["acct"]) do
1178 %{id: id} -> id
1179 _ -> 0
1180 end
1181 )
1182 end)
1183 |> Enum.map(fn x ->
1184 Map.put(x, "avatar", MediaProxy.url(x["avatar"]))
1185 end)
1186 |> Enum.map(fn x ->
1187 Map.put(x, "avatar_static", MediaProxy.url(x["avatar_static"]))
1188 end)
1189
1190 conn
1191 |> json(data2)
1192 else
1193 e -> Logger.error("Could not retrieve suggestions at fetch #{url}, #{inspect(e)}")
1194 end
1195 else
1196 json(conn, [])
1197 end
1198 end
1199 end