Fix all compilation warnings
[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, Activity, User, Notification}
4 alias Pleroma.Web
5 alias Pleroma.Web.MastodonAPI.{StatusView, AccountView, MastodonView}
6 alias Pleroma.Web.ActivityPub.ActivityPub
7 alias Pleroma.Web.{CommonAPI, OStatus}
8 alias Pleroma.Web.OAuth.{Authorization, Token, App}
9 alias Comeonin.Pbkdf2
10 import Ecto.Query
11 require Logger
12
13 def create_app(conn, params) do
14 with cs <- App.register_changeset(%App{}, params) |> IO.inspect,
15 {:ok, app} <- Repo.insert(cs) |> IO.inspect do
16 res = %{
17 id: app.id,
18 client_id: app.client_id,
19 client_secret: app.client_secret
20 }
21
22 json(conn, res)
23 end
24 end
25
26 def update_credentials(%{assigns: %{user: user}} = conn, params) do
27 params = if bio = params["note"] do
28 Map.put(params, "bio", bio)
29 else
30 params
31 end
32
33 params = if name = params["display_name"] do
34 Map.put(params, "name", name)
35 else
36 params
37 end
38
39 user = if avatar = params["avatar"] do
40 with %Plug.Upload{} <- avatar,
41 {:ok, object} <- ActivityPub.upload(avatar),
42 change = Ecto.Changeset.change(user, %{avatar: object.data}),
43 {:ok, user} = Repo.update(change) do
44 user
45 else
46 _e -> user
47 end
48 else
49 user
50 end
51
52 user = if banner = params["header"] do
53 with %Plug.Upload{} <- banner,
54 {:ok, object} <- ActivityPub.upload(banner),
55 new_info <- Map.put(user.info, "banner", object.data),
56 change <- User.info_changeset(user, %{info: new_info}),
57 {:ok, user} <- Repo.update(change) do
58 user
59 else
60 _e -> user
61 end
62 else
63 user
64 end
65
66 with changeset <- User.update_changeset(user, params),
67 {:ok, user} <- Repo.update(changeset) do
68 json conn, AccountView.render("account.json", %{user: user})
69 else
70 _e ->
71 conn
72 |> put_status(403)
73 |> json(%{error: "Invalid request"})
74 end
75 end
76
77 def verify_credentials(%{assigns: %{user: user}} = conn, _) do
78 account = AccountView.render("account.json", %{user: user})
79 json(conn, account)
80 end
81
82 def user(conn, %{"id" => id}) do
83 with %User{} = user <- Repo.get(User, id) do
84 account = AccountView.render("account.json", %{user: user})
85 json(conn, account)
86 else
87 _e -> conn
88 |> put_status(404)
89 |> json(%{error: "Can't find user"})
90 end
91 end
92
93 @instance Application.get_env(:pleroma, :instance)
94
95 def masto_instance(conn, _params) do
96 response = %{
97 uri: Web.base_url,
98 title: Keyword.get(@instance, :name),
99 description: "A Pleroma instance, an alternative fediverse server",
100 version: Keyword.get(@instance, :version),
101 email: Keyword.get(@instance, :email),
102 urls: %{
103 streaming_api: String.replace(Web.base_url, ["http","https"], "wss")
104 },
105 stats: %{
106 user_count: 1,
107 status_count: 2,
108 domain_count: 3
109 }
110 }
111
112 json(conn, response)
113 end
114
115 defp mastodonized_emoji do
116 Pleroma.Formatter.get_custom_emoji()
117 |> Enum.map(fn {shortcode, relative_url} ->
118 url = to_string URI.merge(Web.base_url(), relative_url)
119 %{
120 "shortcode" => shortcode,
121 "static_url" => url,
122 "url" => url
123 }
124 end)
125 end
126
127 def custom_emojis(conn, _params) do
128 mastodon_emoji = mastodonized_emoji()
129 json conn, mastodon_emoji
130 end
131
132 defp add_link_headers(conn, method, activities) do
133 last = List.last(activities)
134 first = List.first(activities)
135 if last do
136 min = last.id
137 max = first.id
138 next_url = mastodon_api_url(Pleroma.Web.Endpoint, method, max_id: min)
139 prev_url = mastodon_api_url(Pleroma.Web.Endpoint, method, since_id: max)
140 conn
141 |> put_resp_header("link", "<#{next_url}>; rel=\"next\", <#{prev_url}>; rel=\"prev\"")
142 else
143 conn
144 end
145 end
146
147 def home_timeline(%{assigns: %{user: user}} = conn, params) do
148 params = params
149 |> Map.put("type", ["Create", "Announce"])
150 |> Map.put("blocking_user", user)
151
152 activities = ActivityPub.fetch_activities([user.ap_id | user.following], params)
153 |> Enum.reverse
154
155 conn
156 |> add_link_headers(:home_timeline, activities)
157 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
158 end
159
160 def public_timeline(%{assigns: %{user: user}} = conn, params) do
161 params = params
162 |> Map.put("type", ["Create", "Announce"])
163 |> Map.put("local_only", !!params["local"])
164 |> Map.put("blocking_user", user)
165
166 activities = ActivityPub.fetch_public_activities(params)
167 |> Enum.reverse
168
169 conn
170 |> add_link_headers(:public_timeline, activities)
171 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
172 end
173
174 # TODO: Link headers
175 def user_statuses(%{assigns: %{user: user}} = conn, params) do
176 with %User{ap_id: ap_id} <- Repo.get(User, params["id"]) do
177 params = params
178 |> Map.put("type", ["Create", "Announce"])
179 |> Map.put("actor_id", ap_id)
180 |> Map.put("whole_db", true)
181
182 activities = ActivityPub.fetch_activities([], params)
183 |> Enum.reverse
184
185 render conn, StatusView, "index.json", %{activities: activities, for: user, as: :activity}
186 end
187 end
188
189 def get_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
190 with %Activity{} = activity <- Repo.get(Activity, id) do
191 render conn, StatusView, "status.json", %{activity: activity, for: user}
192 end
193 end
194
195 def get_context(%{assigns: %{user: user}} = conn, %{"id" => id}) do
196 with %Activity{} = activity <- Repo.get(Activity, id),
197 activities <- ActivityPub.fetch_activities_for_context(activity.data["object"]["context"], %{"blocking_user" => user}),
198 activities <- activities |> Enum.filter(fn (%{id: aid}) -> to_string(aid) != to_string(id) end),
199 grouped_activities <- Enum.group_by(activities, fn (%{id: id}) -> id < activity.id end) do
200 result = %{
201 ancestors: StatusView.render("index.json", for: user, activities: grouped_activities[true] || [], as: :activity) |> Enum.reverse,
202 descendants: StatusView.render("index.json", for: user, activities: grouped_activities[false] || [], as: :activity) |> Enum.reverse,
203 }
204
205 json(conn, result)
206 end
207 end
208
209 def post_status(%{assigns: %{user: user}} = conn, %{"status" => _} = params) do
210 params = params
211 |> Map.put("in_reply_to_status_id", params["in_reply_to_id"])
212
213 {:ok, activity} = CommonAPI.post(user, params)
214 render conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity}
215 end
216
217 def delete_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
218 with {:ok, %Activity{}} <- CommonAPI.delete(id, user) do
219 json(conn, %{})
220 else
221 _e ->
222 conn
223 |> put_status(403)
224 |> json(%{error: "Can't delete this post"})
225 end
226 end
227
228 def reblog_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
229 with {:ok, announce, _activity} = CommonAPI.repeat(ap_id_or_id, user) do
230 render conn, StatusView, "status.json", %{activity: announce, for: user, as: :activity}
231 end
232 end
233
234 def fav_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
235 with {:ok, _fav, %{data: %{"id" => id}}} = CommonAPI.favorite(ap_id_or_id, user),
236 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
237 render conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity}
238 end
239 end
240
241 def unfav_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
242 with {:ok, %{data: %{"id" => id}}} = CommonAPI.unfavorite(ap_id_or_id, user),
243 %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
244 render conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity}
245 end
246 end
247
248 def notifications(%{assigns: %{user: user}} = conn, params) do
249 notifications = Notification.for_user(user, params)
250 result = Enum.map(notifications, fn x ->
251 render_notification(user, x)
252 end)
253 |> Enum.filter(&(&1))
254
255 conn
256 |> add_link_headers(:notifications, notifications)
257 |> json(result)
258 end
259
260 def get_notification(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
261 with {:ok, notification} <- Notification.get(user, id) do
262 json(conn, render_notification(user, notification))
263 else
264 {:error, reason} ->
265 conn
266 |> put_resp_content_type("application/json")
267 |> send_resp(403, Poison.encode!(%{"error" => reason}))
268 end
269 end
270
271 def clear_notifications(%{assigns: %{user: user}} = conn, _params) do
272 Notification.clear(user)
273 json(conn, %{})
274 end
275
276 def dismiss_notification(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
277 with {:ok, _notif} <- Notification.dismiss(user, id) do
278 json(conn, %{})
279 else
280 {:error, reason} ->
281 conn
282 |> put_resp_content_type("application/json")
283 |> send_resp(403, Poison.encode!(%{"error" => reason}))
284 end
285 end
286
287 def relationships(%{assigns: %{user: user}} = conn, %{"id" => id}) do
288 id = List.wrap(id)
289 q = from u in User,
290 where: u.id in ^id
291 targets = Repo.all(q)
292 render conn, AccountView, "relationships.json", %{user: user, targets: targets}
293 end
294
295 def upload(%{assigns: %{user: _}} = conn, %{"file" => file}) do
296 with {:ok, object} <- ActivityPub.upload(file) do
297 data = object.data
298 |> Map.put("id", object.id)
299
300 render conn, StatusView, "attachment.json", %{attachment: data}
301 end
302 end
303
304 def favourited_by(conn, %{"id" => id}) do
305 with %Activity{data: %{"object" => %{"likes" => likes}}} <- Repo.get(Activity, id) do
306 q = from u in User,
307 where: u.ap_id in ^likes
308 users = Repo.all(q)
309 render conn, AccountView, "accounts.json", %{users: users, as: :user}
310 else
311 _ -> json(conn, [])
312 end
313 end
314
315 def reblogged_by(conn, %{"id" => id}) do
316 with %Activity{data: %{"object" => %{"announcements" => announces}}} <- Repo.get(Activity, id) do
317 q = from u in User,
318 where: u.ap_id in ^announces
319 users = Repo.all(q)
320 render conn, AccountView, "accounts.json", %{users: users, as: :user}
321 else
322 _ -> json(conn, [])
323 end
324 end
325
326 # TODO: Link headers
327 def hashtag_timeline(%{assigns: %{user: user}} = conn, params) do
328 params = params
329 |> Map.put("type", "Create")
330 |> Map.put("local_only", !!params["local"])
331 |> Map.put("blocking_user", user)
332
333 activities = ActivityPub.fetch_public_activities(params)
334 |> Enum.reverse
335
336 conn
337 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
338 end
339
340 # TODO: Pagination
341 def followers(conn, %{"id" => id}) do
342 with %User{} = user <- Repo.get(User, id),
343 {:ok, followers} <- User.get_followers(user) do
344 render conn, AccountView, "accounts.json", %{users: followers, as: :user}
345 end
346 end
347
348 def following(conn, %{"id" => id}) do
349 with %User{} = user <- Repo.get(User, id),
350 {:ok, followers} <- User.get_friends(user) do
351 render conn, AccountView, "accounts.json", %{users: followers, as: :user}
352 end
353 end
354
355 def follow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
356 with %User{} = followed <- Repo.get(User, id),
357 {:ok, follower} <- User.follow(follower, followed),
358 {:ok, _activity} <- ActivityPub.follow(follower, followed) do
359 render conn, AccountView, "relationship.json", %{user: follower, target: followed}
360 else
361 {:error, message} ->
362 conn
363 |> put_resp_content_type("application/json")
364 |> send_resp(403, Poison.encode!(%{"error" => message}))
365 end
366 end
367
368 def follow(%{assigns: %{user: follower}} = conn, %{"uri" => uri}) do
369 with %User{} = followed <- Repo.get_by(User, nickname: uri),
370 {:ok, follower} <- User.follow(follower, followed),
371 {:ok, _activity} <- ActivityPub.follow(follower, followed) do
372 render conn, AccountView, "account.json", %{user: followed}
373 else
374 {:error, message} ->
375 conn
376 |> put_resp_content_type("application/json")
377 |> send_resp(403, Poison.encode!(%{"error" => message}))
378 end
379 end
380
381 # TODO: Clean up and unify
382 def unfollow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
383 with %User{} = followed <- Repo.get(User, id),
384 { :ok, follower, follow_activity } <- User.unfollow(follower, followed),
385 { :ok, _activity } <- ActivityPub.insert(%{
386 "type" => "Undo",
387 "actor" => follower.ap_id,
388 "object" => follow_activity.data["id"] # get latest Follow for these users
389 }) do
390 render conn, AccountView, "relationship.json", %{user: follower, target: followed}
391 end
392 end
393
394 def block(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
395 with %User{} = blocked <- Repo.get(User, id),
396 {:ok, blocker} <- User.block(blocker, blocked) do
397 render conn, AccountView, "relationship.json", %{user: blocker, target: blocked}
398 else
399 {:error, message} ->
400 conn
401 |> put_resp_content_type("application/json")
402 |> send_resp(403, Poison.encode!(%{"error" => message}))
403 end
404 end
405
406 def unblock(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
407 with %User{} = blocked <- Repo.get(User, id),
408 {:ok, blocker} <- User.unblock(blocker, blocked) do
409 render conn, AccountView, "relationship.json", %{user: blocker, target: blocked}
410 else
411 {:error, message} ->
412 conn
413 |> put_resp_content_type("application/json")
414 |> send_resp(403, Poison.encode!(%{"error" => message}))
415 end
416 end
417
418 # TODO: Use proper query
419 def blocks(%{assigns: %{user: user}} = conn, _) do
420 with blocked_users <- user.info["blocks"] || [],
421 accounts <- Enum.map(blocked_users, fn (ap_id) -> User.get_cached_by_ap_id(ap_id) end) do
422 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
423 json(conn, res)
424 end
425 end
426
427 def search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
428 accounts = User.search(query, params["resolve"] == "true")
429
430 fetched = if Regex.match?(~r/https?:/, query) do
431 with {:ok, activities} <- OStatus.fetch_activity_from_url(query) do
432 activities
433 else
434 _e -> []
435 end
436 end || []
437
438 q = from a in Activity,
439 where: fragment("?->>'type' = 'Create'", a.data),
440 where: fragment("to_tsvector('english', ?->'object'->>'content') @@ plainto_tsquery('english', ?)", a.data, ^query),
441 limit: 20
442 statuses = Repo.all(q) ++ fetched
443
444 res = %{
445 "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
446 "statuses" => StatusView.render("index.json", activities: statuses, for: user, as: :activity),
447 "hashtags" => []
448 }
449
450 json(conn, res)
451 end
452
453 def account_search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
454 accounts = User.search(query, params["resolve"] == "true")
455
456 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
457
458 json(conn, res)
459 end
460
461 def favourites(%{assigns: %{user: user}} = conn, _) do
462 params = conn
463 |> Map.put("type", "Create")
464 |> Map.put("favorited_by", user.ap_id)
465 |> Map.put("blocking_user", user)
466
467 activities = ActivityPub.fetch_activities([], params)
468 |> Enum.reverse
469
470 conn
471 |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
472 end
473
474 def index(%{assigns: %{user: user}} = conn, _params) do
475 token = conn
476 |> get_session(:oauth_token)
477
478 if user && token do
479 mastodon_emoji = mastodonized_emoji()
480 accounts = Map.put(%{}, user.id, AccountView.render("account.json", %{user: user}))
481 initial_state = %{
482 meta: %{
483 streaming_api_base_url: String.replace(Pleroma.Web.Endpoint.static_url(), "http", "ws"),
484 access_token: token,
485 locale: "en",
486 domain: Pleroma.Web.Endpoint.host(),
487 admin: "1",
488 me: "#{user.id}",
489 unfollow_modal: false,
490 boost_modal: false,
491 delete_modal: true,
492 auto_play_gif: false,
493 reduce_motion: false
494 },
495 compose: %{
496 me: "#{user.id}",
497 default_privacy: "public",
498 default_sensitive: false
499 },
500 media_attachments: %{
501 accept_content_types: [
502 ".jpg",
503 ".jpeg",
504 ".png",
505 ".gif",
506 ".webm",
507 ".mp4",
508 ".m4v",
509 "image\/jpeg",
510 "image\/png",
511 "image\/gif",
512 "video\/webm",
513 "video\/mp4"
514 ]
515 },
516 settings: %{
517 onboarded: true,
518 home: %{
519 shows: %{
520 reblog: true,
521 reply: true
522 }
523 },
524 notifications: %{
525 alerts: %{
526 follow: true,
527 favourite: true,
528 reblog: true,
529 mention: true
530 },
531 shows: %{
532 follow: true,
533 favourite: true,
534 reblog: true,
535 mention: true
536 },
537 sounds: %{
538 follow: true,
539 favourite: true,
540 reblog: true,
541 mention: true
542 }
543 }
544 },
545 push_subscription: nil,
546 accounts: accounts,
547 custom_emojis: mastodon_emoji
548 } |> Poison.encode!
549 conn
550 |> put_layout(false)
551 |> render(MastodonView, "index.html", %{initial_state: initial_state})
552 else
553 conn
554 |> redirect(to: "/web/login")
555 end
556 end
557
558 def login(conn, _) do
559 conn
560 |> render(MastodonView, "login.html")
561 end
562
563 defp get_or_make_app() do
564 with %App{} = app <- Repo.get_by(App, client_name: "Mastodon-Local") do
565 {:ok, app}
566 else
567 _e ->
568 cs = App.register_changeset(%App{}, %{client_name: "Mastodon-Local", redirect_uris: ".", scopes: "read,write,follow"})
569 Repo.insert(cs)
570 end
571 end
572
573 def login_post(conn, %{"authorization" => %{ "name" => name, "password" => password}}) do
574 with %User{} = user <- User.get_cached_by_nickname(name),
575 true <- Pbkdf2.checkpw(password, user.password_hash),
576 {:ok, app} <- get_or_make_app(),
577 {:ok, auth} <- Authorization.create_authorization(app, user),
578 {:ok, token} <- Token.exchange_token(app, auth) do
579 conn
580 |> put_session(:oauth_token, token.token)
581 |> redirect(to: "/web/getting-started")
582 end
583 end
584
585 def relationship_noop(%{assigns: %{user: user}} = conn, %{"id" => id}) do
586 Logger.debug("Unimplemented, returning unmodified relationship")
587 with %User{} = target <- Repo.get(User, id) do
588 render conn, AccountView, "relationship.json", %{user: user, target: target}
589 end
590 end
591
592 def empty_array(conn, _) do
593 Logger.debug("Unimplemented, returning an empty array")
594 json(conn, [])
595 end
596
597 def render_notification(user, %{id: id, activity: activity, inserted_at: created_at} = _params) do
598 actor = User.get_cached_by_ap_id(activity.data["actor"])
599 created_at = NaiveDateTime.to_iso8601(created_at)
600 |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)
601 case activity.data["type"] do
602 "Create" ->
603 %{id: id, type: "mention", created_at: created_at, account: AccountView.render("account.json", %{user: actor}), status: StatusView.render("status.json", %{activity: activity, for: user})}
604 "Like" ->
605 liked_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
606 %{id: id, type: "favourite", created_at: created_at, account: AccountView.render("account.json", %{user: actor}), status: StatusView.render("status.json", %{activity: liked_activity, for: user})}
607 "Announce" ->
608 announced_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
609 %{id: id, type: "reblog", created_at: created_at, account: AccountView.render("account.json", %{user: actor}), status: StatusView.render("status.json", %{activity: announced_activity, for: user})}
610 "Follow" ->
611 %{id: id, type: "follow", created_at: created_at, account: AccountView.render("account.json", %{user: actor})}
612 _ -> nil
613 end
614 end
615 end