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