[MastodonAPI] Add filters
[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 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_uri: 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, object} <- ActivityPub.fetch_object_from_id(query) do
662 [Activity.get_create_activity_by_object_ap_id(object.data["id"])]
663 else
664 _e -> []
665 end
666 end || []
667
668 q =
669 from(
670 a in Activity,
671 where: fragment("?->>'type' = 'Create'", a.data),
672 where: "https://www.w3.org/ns/activitystreams#Public" in a.recipients,
673 where:
674 fragment(
675 "to_tsvector('english', ?->'object'->>'content') @@ plainto_tsquery('english', ?)",
676 a.data,
677 ^query
678 ),
679 limit: 20,
680 order_by: [desc: :id]
681 )
682
683 statuses = Repo.all(q) ++ fetched
684
685 tags_path = Web.base_url() <> "/tag/"
686
687 tags =
688 String.split(query)
689 |> Enum.uniq()
690 |> Enum.filter(fn tag -> String.starts_with?(tag, "#") end)
691 |> Enum.map(fn tag -> String.slice(tag, 1..-1) end)
692 |> Enum.map(fn tag -> %{name: tag, url: tags_path <> tag} end)
693
694 res = %{
695 "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
696 "statuses" =>
697 StatusView.render("index.json", activities: statuses, for: user, as: :activity),
698 "hashtags" => tags
699 }
700
701 json(conn, res)
702 end
703
704 def search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
705 accounts = User.search(query, params["resolve"] == "true")
706
707 fetched =
708 if Regex.match?(~r/https?:/, query) do
709 with {:ok, object} <- ActivityPub.fetch_object_from_id(query) do
710 [Activity.get_create_activity_by_object_ap_id(object.data["id"])]
711 else
712 _e -> []
713 end
714 end || []
715
716 q =
717 from(
718 a in Activity,
719 where: fragment("?->>'type' = 'Create'", a.data),
720 where: "https://www.w3.org/ns/activitystreams#Public" in a.recipients,
721 where:
722 fragment(
723 "to_tsvector('english', ?->'object'->>'content') @@ plainto_tsquery('english', ?)",
724 a.data,
725 ^query
726 ),
727 limit: 20,
728 order_by: [desc: :id]
729 )
730
731 statuses = Repo.all(q) ++ fetched
732
733 tags =
734 String.split(query)
735 |> Enum.uniq()
736 |> Enum.filter(fn tag -> String.starts_with?(tag, "#") end)
737 |> Enum.map(fn tag -> String.slice(tag, 1..-1) end)
738
739 res = %{
740 "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
741 "statuses" =>
742 StatusView.render("index.json", activities: statuses, for: user, as: :activity),
743 "hashtags" => tags
744 }
745
746 json(conn, res)
747 end
748
749 def account_search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
750 accounts = User.search(query, params["resolve"] == "true")
751
752 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
753
754 json(conn, res)
755 end
756
757 def favourites(%{assigns: %{user: user}} = conn, _) do
758 params =
759 %{}
760 |> Map.put("type", "Create")
761 |> Map.put("favorited_by", user.ap_id)
762 |> Map.put("blocking_user", user)
763
764 activities =
765 ActivityPub.fetch_public_activities(params)
766 |> Enum.reverse()
767
768 conn
769 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
770 end
771
772 def get_lists(%{assigns: %{user: user}} = conn, opts) do
773 lists = Pleroma.List.for_user(user, opts)
774 res = ListView.render("lists.json", lists: lists)
775 json(conn, res)
776 end
777
778 def get_list(%{assigns: %{user: user}} = conn, %{"id" => id}) do
779 with %Pleroma.List{} = list <- Pleroma.List.get(id, user) do
780 res = ListView.render("list.json", list: list)
781 json(conn, res)
782 else
783 _e -> json(conn, "error")
784 end
785 end
786
787 def delete_list(%{assigns: %{user: user}} = conn, %{"id" => id}) do
788 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
789 {:ok, _list} <- Pleroma.List.delete(list) do
790 json(conn, %{})
791 else
792 _e ->
793 json(conn, "error")
794 end
795 end
796
797 def create_list(%{assigns: %{user: user}} = conn, %{"title" => title}) do
798 with {:ok, %Pleroma.List{} = list} <- Pleroma.List.create(title, user) do
799 res = ListView.render("list.json", list: list)
800 json(conn, res)
801 end
802 end
803
804 def add_to_list(%{assigns: %{user: user}} = conn, %{"id" => id, "account_ids" => accounts}) do
805 accounts
806 |> Enum.each(fn account_id ->
807 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
808 %User{} = followed <- Repo.get(User, account_id) do
809 Pleroma.List.follow(list, followed)
810 end
811 end)
812
813 json(conn, %{})
814 end
815
816 def remove_from_list(%{assigns: %{user: user}} = conn, %{"id" => id, "account_ids" => accounts}) do
817 accounts
818 |> Enum.each(fn account_id ->
819 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
820 %User{} = followed <- Repo.get(Pleroma.User, account_id) do
821 Pleroma.List.unfollow(list, followed)
822 end
823 end)
824
825 json(conn, %{})
826 end
827
828 def list_accounts(%{assigns: %{user: user}} = conn, %{"id" => id}) do
829 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
830 {:ok, users} = Pleroma.List.get_following(list) do
831 render(conn, AccountView, "accounts.json", %{users: users, as: :user})
832 end
833 end
834
835 def rename_list(%{assigns: %{user: user}} = conn, %{"id" => id, "title" => title}) do
836 with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
837 {:ok, list} <- Pleroma.List.rename(list, title) do
838 res = ListView.render("list.json", list: list)
839 json(conn, res)
840 else
841 _e ->
842 json(conn, "error")
843 end
844 end
845
846 def list_timeline(%{assigns: %{user: user}} = conn, %{"list_id" => id} = params) do
847 with %Pleroma.List{title: title, following: following} <- Pleroma.List.get(id, user) do
848 params =
849 params
850 |> Map.put("type", "Create")
851 |> Map.put("blocking_user", user)
852
853 # adding title is a hack to not make empty lists function like a public timeline
854 activities =
855 ActivityPub.fetch_activities([title | following], params)
856 |> Enum.reverse()
857
858 conn
859 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
860 else
861 _e ->
862 conn
863 |> put_status(403)
864 |> json(%{error: "Error."})
865 end
866 end
867
868 def index(%{assigns: %{user: user}} = conn, _params) do
869 token =
870 conn
871 |> get_session(:oauth_token)
872
873 if user && token do
874 mastodon_emoji = mastodonized_emoji()
875 accounts = Map.put(%{}, user.id, AccountView.render("account.json", %{user: user}))
876
877 initial_state =
878 %{
879 meta: %{
880 streaming_api_base_url:
881 String.replace(Pleroma.Web.Endpoint.static_url(), "http", "ws"),
882 access_token: token,
883 locale: "en",
884 domain: Pleroma.Web.Endpoint.host(),
885 admin: "1",
886 me: "#{user.id}",
887 unfollow_modal: false,
888 boost_modal: false,
889 delete_modal: true,
890 auto_play_gif: false,
891 display_sensitive_media: false,
892 reduce_motion: false,
893 max_toot_chars: Keyword.get(@instance, :limit)
894 },
895 rights: %{
896 delete_others_notice: !!user.info["is_moderator"]
897 },
898 compose: %{
899 me: "#{user.id}",
900 default_privacy: user.info["default_scope"] || "public",
901 default_sensitive: false
902 },
903 media_attachments: %{
904 accept_content_types: [
905 ".jpg",
906 ".jpeg",
907 ".png",
908 ".gif",
909 ".webm",
910 ".mp4",
911 ".m4v",
912 "image\/jpeg",
913 "image\/png",
914 "image\/gif",
915 "video\/webm",
916 "video\/mp4"
917 ]
918 },
919 settings:
920 Map.get(user.info, "settings") ||
921 %{
922 onboarded: true,
923 home: %{
924 shows: %{
925 reblog: true,
926 reply: true
927 }
928 },
929 notifications: %{
930 alerts: %{
931 follow: true,
932 favourite: true,
933 reblog: true,
934 mention: true
935 },
936 shows: %{
937 follow: true,
938 favourite: true,
939 reblog: true,
940 mention: true
941 },
942 sounds: %{
943 follow: true,
944 favourite: true,
945 reblog: true,
946 mention: true
947 }
948 }
949 },
950 push_subscription: nil,
951 accounts: accounts,
952 custom_emojis: mastodon_emoji,
953 char_limit: Keyword.get(@instance, :limit)
954 }
955 |> Jason.encode!()
956
957 conn
958 |> put_layout(false)
959 |> render(MastodonView, "index.html", %{initial_state: initial_state})
960 else
961 conn
962 |> redirect(to: "/web/login")
963 end
964 end
965
966 def put_settings(%{assigns: %{user: user}} = conn, %{"data" => settings} = _params) do
967 with new_info <- Map.put(user.info, "settings", settings),
968 change <- User.info_changeset(user, %{info: new_info}),
969 {:ok, _user} <- User.update_and_set_cache(change) do
970 conn
971 |> json(%{})
972 else
973 e ->
974 conn
975 |> json(%{error: inspect(e)})
976 end
977 end
978
979 def login(conn, _) do
980 conn
981 |> render(MastodonView, "login.html", %{error: false})
982 end
983
984 defp get_or_make_app() do
985 with %App{} = app <- Repo.get_by(App, client_name: "Mastodon-Local") do
986 {:ok, app}
987 else
988 _e ->
989 cs =
990 App.register_changeset(%App{}, %{
991 client_name: "Mastodon-Local",
992 redirect_uris: ".",
993 scopes: "read,write,follow"
994 })
995
996 Repo.insert(cs)
997 end
998 end
999
1000 def login_post(conn, %{"authorization" => %{"name" => name, "password" => password}}) do
1001 with %User{} = user <- User.get_by_nickname_or_email(name),
1002 true <- Pbkdf2.checkpw(password, user.password_hash),
1003 {:ok, app} <- get_or_make_app(),
1004 {:ok, auth} <- Authorization.create_authorization(app, user),
1005 {:ok, token} <- Token.exchange_token(app, auth) do
1006 conn
1007 |> put_session(:oauth_token, token.token)
1008 |> redirect(to: "/web/getting-started")
1009 else
1010 _e ->
1011 conn
1012 |> render(MastodonView, "login.html", %{error: "Wrong username or password"})
1013 end
1014 end
1015
1016 def logout(conn, _) do
1017 conn
1018 |> clear_session
1019 |> redirect(to: "/")
1020 end
1021
1022 def relationship_noop(%{assigns: %{user: user}} = conn, %{"id" => id}) do
1023 Logger.debug("Unimplemented, returning unmodified relationship")
1024
1025 with %User{} = target <- Repo.get(User, id) do
1026 render(conn, AccountView, "relationship.json", %{user: user, target: target})
1027 end
1028 end
1029
1030 def empty_array(conn, _) do
1031 Logger.debug("Unimplemented, returning an empty array")
1032 json(conn, [])
1033 end
1034
1035 def empty_object(conn, _) do
1036 Logger.debug("Unimplemented, returning an empty object")
1037 json(conn, %{})
1038 end
1039
1040 def render_notification(user, %{id: id, activity: activity, inserted_at: created_at} = _params) do
1041 actor = User.get_cached_by_ap_id(activity.data["actor"])
1042
1043 created_at =
1044 NaiveDateTime.to_iso8601(created_at)
1045 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
1046
1047 case activity.data["type"] do
1048 "Create" ->
1049 %{
1050 id: id,
1051 type: "mention",
1052 created_at: created_at,
1053 account: AccountView.render("account.json", %{user: actor}),
1054 status: StatusView.render("status.json", %{activity: activity, for: user})
1055 }
1056
1057 "Like" ->
1058 liked_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
1059
1060 %{
1061 id: id,
1062 type: "favourite",
1063 created_at: created_at,
1064 account: AccountView.render("account.json", %{user: actor}),
1065 status: StatusView.render("status.json", %{activity: liked_activity, for: user})
1066 }
1067
1068 "Announce" ->
1069 announced_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
1070
1071 %{
1072 id: id,
1073 type: "reblog",
1074 created_at: created_at,
1075 account: AccountView.render("account.json", %{user: actor}),
1076 status: StatusView.render("status.json", %{activity: announced_activity, for: user})
1077 }
1078
1079 "Follow" ->
1080 %{
1081 id: id,
1082 type: "follow",
1083 created_at: created_at,
1084 account: AccountView.render("account.json", %{user: actor})
1085 }
1086
1087 _ ->
1088 nil
1089 end
1090 end
1091
1092 def get_filters(%{assigns: %{user: user}} = conn, params) do
1093 filters = Pleroma.Filter.get_filters(user)
1094 res = FilterView.render("filters.json", filters: filters)
1095 json(conn, res)
1096 end
1097
1098 def create_filter(
1099 %{assigns: %{user: user}} = conn,
1100 %{"phrase" => phrase, "context" => context} = params
1101 ) do
1102 query = %Pleroma.Filter{
1103 user_id: user.id,
1104 phrase: phrase,
1105 context: context,
1106 hide: Map.get(params, "irreversible", nil),
1107 whole_word: Map.get(params, "boolean", true)
1108 # expires_at
1109 }
1110
1111 {:ok, response} = Pleroma.Filter.create(query)
1112 res = FilterView.render("filter.json", filter: response)
1113 json(conn, res)
1114 end
1115
1116 def get_filter(%{assigns: %{user: user}} = conn, %{"id" => filter_id} = params) do
1117 filter = Pleroma.Filter.get(filter_id, user)
1118 res = FilterView.render("filter.json", filter: filter)
1119 json(conn, res)
1120 end
1121
1122 def update_filter(
1123 %{assigns: %{user: user}} = conn,
1124 %{"phrase" => phrase, "context" => context, "id" => filter_id} = params
1125 ) do
1126 query = %Pleroma.Filter{
1127 user_id: user.id,
1128 filter_id: filter_id,
1129 phrase: phrase,
1130 context: context,
1131 hide: Map.get(params, "irreversible", nil),
1132 whole_word: Map.get(params, "boolean", true)
1133 # expires_at
1134 }
1135
1136 {:ok, response} = Pleroma.Filter.update(query)
1137 res = FilterView.render("filter.json", filter: response)
1138 json(conn, res)
1139 end
1140
1141 def delete_filter(%{assigns: %{user: user}} = conn, %{"id" => filter_id} = params) do
1142 query = %Pleroma.Filter{
1143 user_id: user.id,
1144 filter_id: filter_id
1145 }
1146
1147 {:ok, response} = Pleroma.Filter.delete(query)
1148 json(conn, %{})
1149 end
1150
1151 def errors(conn, _) do
1152 conn
1153 |> put_status(500)
1154 |> json("Something went wrong")
1155 end
1156
1157 @suggestions Application.get_env(:pleroma, :suggestions)
1158
1159 def suggestions(%{assigns: %{user: user}} = conn, _) do
1160 if Keyword.get(@suggestions, :enabled, false) do
1161 api = Keyword.get(@suggestions, :third_party_engine, "")
1162 timeout = Keyword.get(@suggestions, :timeout, 5000)
1163
1164 host =
1165 Application.get_env(:pleroma, Pleroma.Web.Endpoint)
1166 |> Keyword.get(:url)
1167 |> Keyword.get(:host)
1168
1169 user = user.nickname
1170 url = String.replace(api, "{{host}}", host) |> String.replace("{{user}}", user)
1171
1172 with {:ok, %{status_code: 200, body: body}} <-
1173 @httpoison.get(url, [], timeout: timeout, recv_timeout: timeout),
1174 {:ok, data} <- Jason.decode(body) do
1175 data2 =
1176 Enum.slice(data, 0, 40)
1177 |> Enum.map(fn x ->
1178 Map.put(
1179 x,
1180 "id",
1181 case User.get_or_fetch(x["acct"]) do
1182 %{id: id} -> id
1183 _ -> 0
1184 end
1185 )
1186 end)
1187
1188 conn
1189 |> json(data2)
1190 else
1191 e -> Logger.error("Could not retrieve suggestions at fetch #{url}, #{inspect(e)}")
1192 end
1193 else
1194 json(conn, [])
1195 end
1196 end
1197 end