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