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