mastodon_api_controller.ex 35.2 KB
Newer Older
1 2
defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do
  use Pleroma.Web, :controller
3
  alias Pleroma.{Repo, Object, Activity, User, Notification, Stats}
Roger Braun's avatar
Roger Braun committed
4
  alias Pleroma.Web
eal's avatar
eal committed
5
  alias Pleroma.Web.MastodonAPI.{StatusView, AccountView, MastodonView, ListView}
6
  alias Pleroma.Web.ActivityPub.ActivityPub
William Pitcock's avatar
William Pitcock committed
7
  alias Pleroma.Web.ActivityPub.Utils
lain's avatar
lain committed
8
  alias Pleroma.Web.CommonAPI
Roger Braun's avatar
Roger Braun committed
9 10
  alias Pleroma.Web.OAuth.{Authorization, Token, App}
  alias Comeonin.Pbkdf2
Mayel's avatar
Mayel committed
11
  alias Pleroma.Web.TwitterAPI.TwitterAPI
12
  import Ecto.Query
13
  require Logger
14

15 16
  @httpoison Application.get_env(:pleroma, :httpoison)

17 18
  action_fallback(:errors)

19
  def create_app(conn, params) do
lain's avatar
lain committed
20 21
    with cs <- App.register_changeset(%App{}, params) |> IO.inspect(),
         {:ok, app} <- Repo.insert(cs) |> IO.inspect() do
22
      res = %{
23
        id: app.id |> to_string,
24
        name: app.client_name,
25
        client_id: app.client_id,
26
        client_secret: app.client_secret,
27
        redirect_uri: app.redirect_uris,
28
        website: app.website
29 30 31 32 33 34
      }

      json(conn, res)
    end
  end

35
  def update_credentials(%{assigns: %{user: user}} = conn, params) do
lain's avatar
lain committed
36
    original_user = user
37

lain's avatar
lain committed
38 39 40 41 42 43
    params =
      if bio = params["note"] do
        Map.put(params, "bio", bio)
      else
        params
      end
44

lain's avatar
lain committed
45 46 47
    params =
      if name = params["display_name"] do
        Map.put(params, "name", name)
48
      else
lain's avatar
lain committed
49
        params
50 51
      end

lain's avatar
lain committed
52 53 54 55 56 57 58 59 60 61 62
    user =
      if avatar = params["avatar"] do
        with %Plug.Upload{} <- avatar,
             {:ok, object} <- ActivityPub.upload(avatar),
             change = Ecto.Changeset.change(user, %{avatar: object.data}),
             {:ok, user} = User.update_and_set_cache(change) do
          user
        else
          _e -> user
        end
      else
63
        user
lain's avatar
lain committed
64 65 66 67 68 69 70 71 72 73 74 75 76
      end

    user =
      if banner = params["header"] do
        with %Plug.Upload{} <- banner,
             {:ok, object} <- ActivityPub.upload(banner),
             new_info <- Map.put(user.info, "banner", object.data),
             change <- User.info_changeset(user, %{info: new_info}),
             {:ok, user} <- User.update_and_set_cache(change) do
          user
        else
          _e -> user
        end
77
      else
lain's avatar
lain committed
78
        user
79 80
      end

81 82 83 84 85 86 87 88 89 90 91 92 93 94
    user =
      if locked = params["locked"] do
        with locked <- locked == "true",
             new_info <- Map.put(user.info, "locked", locked),
             change <- User.info_changeset(user, %{info: new_info}),
             {:ok, user} <- User.update_and_set_cache(change) do
          user
        else
          _e -> user
        end
      else
        user
      end

95
    with changeset <- User.update_changeset(user, params),
lain's avatar
lain committed
96 97 98 99
         {:ok, user} <- User.update_and_set_cache(changeset) do
      if original_user != user do
        CommonAPI.update(user)
      end
lain's avatar
lain committed
100 101

      json(conn, AccountView.render("account.json", %{user: user}))
102 103 104 105 106 107 108 109
    else
      _e ->
        conn
        |> put_status(403)
        |> json(%{error: "Invalid request"})
    end
  end

110
  def verify_credentials(%{assigns: %{user: user}} = conn, _) do
Roger Braun's avatar
Roger Braun committed
111 112 113 114
    account = AccountView.render("account.json", %{user: user})
    json(conn, account)
  end

115 116 117 118 119
  def user(conn, %{"id" => id}) do
    with %User{} = user <- Repo.get(User, id) do
      account = AccountView.render("account.json", %{user: user})
      json(conn, account)
    else
lain's avatar
lain committed
120 121 122 123
      _e ->
        conn
        |> put_status(404)
        |> json(%{error: "Can't find user"})
124 125 126
    end
  end

127
  @instance Application.get_env(:pleroma, :instance)
128
  @mastodon_api_level "2.3.3"
129

Roger Braun's avatar
Roger Braun committed
130 131
  def masto_instance(conn, _params) do
    response = %{
lain's avatar
lain committed
132
      uri: Web.base_url(),
133
      title: Keyword.get(@instance, :name),
134
      description: Keyword.get(@instance, :description),
135
      version: "#{@mastodon_api_level} (compatible; #{Keyword.get(@instance, :version)})",
136 137
      email: Keyword.get(@instance, :email),
      urls: %{
lain's avatar
lain committed
138
        streaming_api: String.replace(Pleroma.Web.Endpoint.static_url(), "http", "ws")
139
      },
lain's avatar
lain committed
140 141
      stats: Stats.get_stats(),
      thumbnail: Web.base_url() <> "/instance/thumbnail.jpeg",
142
      max_toot_chars: Keyword.get(@instance, :limit)
143 144
    }

Roger Braun's avatar
Roger Braun committed
145
    json(conn, response)
146
  end
147

148
  def peers(conn, _params) do
lain's avatar
lain committed
149
    json(conn, Stats.get_peers())
150 151
  end

152 153
  defp mastodonized_emoji do
    Pleroma.Formatter.get_custom_emoji()
154
    |> Enum.map(fn {shortcode, relative_url} ->
lain's avatar
lain committed
155 156
      url = to_string(URI.merge(Web.base_url(), relative_url))

157 158 159
      %{
        "shortcode" => shortcode,
        "static_url" => url,
160
        "visible_in_picker" => true,
161 162 163
        "url" => url
      }
    end)
164 165 166 167
  end

  def custom_emojis(conn, _params) do
    mastodon_emoji = mastodonized_emoji()
lain's avatar
lain committed
168
    json(conn, mastodon_emoji)
169 170
  end

171
  defp add_link_headers(conn, method, activities, param \\ nil, params \\ %{}) do
172 173
    last = List.last(activities)
    first = List.first(activities)
lain's avatar
lain committed
174

175 176 177
    if last do
      min = last.id
      max = first.id
lain's avatar
lain committed
178 179 180 181

      {next_url, prev_url} =
        if param do
          {
182 183 184 185 186 187 188 189 190 191 192 193
            mastodon_api_url(
              Pleroma.Web.Endpoint,
              method,
              param,
              Map.merge(params, %{max_id: min})
            ),
            mastodon_api_url(
              Pleroma.Web.Endpoint,
              method,
              param,
              Map.merge(params, %{since_id: max})
            )
lain's avatar
lain committed
194 195 196
          }
        else
          {
197 198 199 200 201 202 203 204 205 206
            mastodon_api_url(
              Pleroma.Web.Endpoint,
              method,
              Map.merge(params, %{max_id: min})
            ),
            mastodon_api_url(
              Pleroma.Web.Endpoint,
              method,
              Map.merge(params, %{since_id: max})
            )
lain's avatar
lain committed
207 208 209
          }
        end

210 211 212 213 214 215 216
      conn
      |> put_resp_header("link", "<#{next_url}>; rel=\"next\", <#{prev_url}>; rel=\"prev\"")
    else
      conn
    end
  end

217
  def home_timeline(%{assigns: %{user: user}} = conn, params) do
lain's avatar
lain committed
218 219 220 221 222
    params =
      params
      |> Map.put("type", ["Create", "Announce"])
      |> Map.put("blocking_user", user)
      |> Map.put("user", user)
223

lain's avatar
lain committed
224 225 226
    activities =
      ActivityPub.fetch_activities([user.ap_id | user.following], params)
      |> Enum.reverse()
227 228

    conn
229
    |> add_link_headers(:home_timeline, activities)
Roger Braun's avatar
Roger Braun committed
230
    |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
231 232 233
  end

  def public_timeline(%{assigns: %{user: user}} = conn, params) do
234 235
    local_only = params["local"] in [true, "True", "true", "1"]

lain's avatar
lain committed
236 237 238
    params =
      params
      |> Map.put("type", ["Create", "Announce"])
239
      |> Map.put("local_only", local_only)
lain's avatar
lain committed
240
      |> Map.put("blocking_user", user)
241

lain's avatar
lain committed
242 243 244
    activities =
      ActivityPub.fetch_public_activities(params)
      |> Enum.reverse()
245

246
    conn
247
    |> add_link_headers(:public_timeline, activities, false, %{"local" => local_only})
248
    |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
249 250
  end

251 252 253
  def user_statuses(%{assigns: %{user: reading_user}} = conn, params) do
    with %User{} = user <- Repo.get(User, params["id"]) do
      # Since Pleroma has no "pinned" posts feature, we'll just set an empty list here
eal's avatar
eal committed
254 255 256 257
      activities =
        if params["pinned"] == "true" do
          []
        else
258
          ActivityPub.fetch_user_activities(user, reading_user, params)
eal's avatar
eal committed
259
        end
260

261 262
      conn
      |> add_link_headers(:user_statuses, activities, params["id"])
263 264 265 266 267
      |> render(StatusView, "index.json", %{
        activities: activities,
        for: reading_user,
        as: :activity
      })
268 269 270
    end
  end

271
  def dm_timeline(%{assigns: %{user: user}} = conn, _params) do
272 273 274
    query =
      ActivityPub.fetch_activities_query([user.ap_id], %{"type" => "Create", visibility: "direct"})

275 276 277
    activities = Repo.all(query)

    conn
278
    |> add_link_headers(:dm_timeline, activities)
279 280 281
    |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
  end

282
  def get_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
lain's avatar
lain committed
283 284
    with %Activity{} = activity <- Repo.get(Activity, id),
         true <- ActivityPub.visible_for_user?(activity, user) do
lain's avatar
lain committed
285
      render(conn, StatusView, "status.json", %{activity: activity, for: user})
286 287 288
    end
  end

289 290
  def get_context(%{assigns: %{user: user}} = conn, %{"id" => id}) do
    with %Activity{} = activity <- Repo.get(Activity, id),
lain's avatar
lain committed
291 292 293 294 295 296 297 298 299 300
         activities <-
           ActivityPub.fetch_activities_for_context(activity.data["context"], %{
             "blocking_user" => user,
             "user" => user
           }),
         activities <-
           activities |> Enum.filter(fn %{id: aid} -> to_string(aid) != to_string(id) end),
         activities <-
           activities |> Enum.filter(fn %{data: %{"type" => type}} -> type == "Create" end),
         grouped_activities <- Enum.group_by(activities, fn %{id: id} -> id < activity.id end) do
301
      result = %{
lain's avatar
lain committed
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
        ancestors:
          StatusView.render(
            "index.json",
            for: user,
            activities: grouped_activities[true] || [],
            as: :activity
          )
          |> Enum.reverse(),
        descendants:
          StatusView.render(
            "index.json",
            for: user,
            activities: grouped_activities[false] || [],
            as: :activity
          )
          |> Enum.reverse()
318 319 320 321 322 323
      }

      json(conn, result)
    end
  end

324 325 326 327 328 329 330 331 332
  def post_status(conn, %{"status" => "", "media_ids" => media_ids} = params)
      when length(media_ids) > 0 do
    params =
      params
      |> Map.put("status", ".")

    post_status(conn, params)
  end

333
  def post_status(%{assigns: %{user: user}} = conn, %{"status" => _} = params) do
lain's avatar
lain committed
334 335 336 337
    params =
      params
      |> Map.put("in_reply_to_status_id", params["in_reply_to_id"])
      |> Map.put("no_attachment_links", true)
338

339 340 341 342 343 344 345
    idempotency_key =
      case get_req_header(conn, "idempotency-key") do
        [key] -> key
        _ -> Ecto.UUID.generate()
      end

    {:ok, activity} =
346
      Cachex.fetch!(:idempotency_cache, idempotency_key, fn _ -> CommonAPI.post(user, params) end)
347

lain's avatar
lain committed
348
    render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity})
349
  end
Roger Braun's avatar
Roger Braun committed
350 351 352 353 354 355 356 357 358 359 360

  def delete_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
    with {:ok, %Activity{}} <- CommonAPI.delete(id, user) do
      json(conn, %{})
    else
      _e ->
        conn
        |> put_status(403)
        |> json(%{error: "Can't delete this post"})
    end
  end
361 362

  def reblog_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
363
    with {:ok, announce, _activity} <- CommonAPI.repeat(ap_id_or_id, user) do
lain's avatar
lain committed
364
      render(conn, StatusView, "status.json", %{activity: announce, for: user, as: :activity})
365 366
    end
  end
367

368
  def unreblog_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
369
    with {:ok, _unannounce, %{data: %{"id" => id}}} <- CommonAPI.unrepeat(ap_id_or_id, user),
370 371
         %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
      render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity})
372 373 374
    end
  end

375
  def fav_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
376
    with {:ok, _fav, %{data: %{"id" => id}}} <- CommonAPI.favorite(ap_id_or_id, user),
Roger Braun's avatar
Roger Braun committed
377
         %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
lain's avatar
lain committed
378
      render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity})
Roger Braun's avatar
Roger Braun committed
379 380 381 382
    end
  end

  def unfav_status(%{assigns: %{user: user}} = conn, %{"id" => ap_id_or_id}) do
383
    with {:ok, _, _, %{data: %{"id" => id}}} <- CommonAPI.unfavorite(ap_id_or_id, user),
384
         %Activity{} = activity <- Activity.get_create_activity_by_object_ap_id(id) do
lain's avatar
lain committed
385
      render(conn, StatusView, "status.json", %{activity: activity, for: user, as: :activity})
386 387
    end
  end
388

389 390
  def notifications(%{assigns: %{user: user}} = conn, params) do
    notifications = Notification.for_user(user, params)
lain's avatar
lain committed
391 392 393 394 395 396

    result =
      Enum.map(notifications, fn x ->
        render_notification(user, x)
      end)
      |> Enum.filter(& &1)
397

398 399 400
    conn
    |> add_link_headers(:notifications, notifications)
    |> json(result)
401 402
  end

403 404 405 406 407 408 409
  def get_notification(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
    with {:ok, notification} <- Notification.get(user, id) do
      json(conn, render_notification(user, notification))
    else
      {:error, reason} ->
        conn
        |> put_resp_content_type("application/json")
lain's avatar
lain committed
410
        |> send_resp(403, Jason.encode!(%{"error" => reason}))
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
    end
  end

  def clear_notifications(%{assigns: %{user: user}} = conn, _params) do
    Notification.clear(user)
    json(conn, %{})
  end

  def dismiss_notification(%{assigns: %{user: user}} = conn, %{"id" => id} = _params) do
    with {:ok, _notif} <- Notification.dismiss(user, id) do
      json(conn, %{})
    else
      {:error, reason} ->
        conn
        |> put_resp_content_type("application/json")
lain's avatar
lain committed
426
        |> send_resp(403, Jason.encode!(%{"error" => reason}))
427 428 429
    end
  end

430 431
  def relationships(%{assigns: %{user: user}} = conn, %{"id" => id}) do
    id = List.wrap(id)
lain's avatar
lain committed
432
    q = from(u in User, where: u.id in ^id)
433
    targets = Repo.all(q)
lain's avatar
lain committed
434
    render(conn, AccountView, "relationships.json", %{user: user, targets: targets})
435 436
  end

437 438 439 440 441 442 443 444 445
  def update_media(%{assigns: %{user: _}} = conn, data) do
    with %Object{} = object <- Repo.get(Object, data["id"]),
         true <- is_binary(data["description"]),
         description <- data["description"] do
      new_data = %{object.data | "name" => description}

      change = Object.change(object, %{data: new_data})
      {:ok, media_obj} = Repo.update(change)

lain's avatar
lain committed
446
      data =
447
        new_data
lain's avatar
lain committed
448
        |> Map.put("id", object.id)
Roger Braun's avatar
Roger Braun committed
449

lain's avatar
lain committed
450
      render(conn, StatusView, "attachment.json", %{attachment: data})
Roger Braun's avatar
Roger Braun committed
451 452 453
    end
  end

454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
  def upload(%{assigns: %{user: _}} = conn, %{"file" => file} = data) do
    with {:ok, object} <- ActivityPub.upload(file) do
      objdata =
        if Map.has_key?(data, "description") do
          Map.put(object.data, "name", data["description"])
        else
          object.data
        end

      change = Object.change(object, %{data: objdata})
      {:ok, object} = Repo.update(change)

      objdata =
        objdata
        |> Map.put("id", object.id)

      render(conn, StatusView, "attachment.json", %{attachment: objdata})
    end
  end

474
  def favourited_by(conn, %{"id" => id}) do
475
    with %Activity{data: %{"object" => %{"likes" => likes}}} <- Repo.get(Activity, id) do
lain's avatar
lain committed
476
      q = from(u in User, where: u.ap_id in ^likes)
477
      users = Repo.all(q)
lain's avatar
lain committed
478
      render(conn, AccountView, "accounts.json", %{users: users, as: :user})
479 480 481 482 483 484 485
    else
      _ -> json(conn, [])
    end
  end

  def reblogged_by(conn, %{"id" => id}) do
    with %Activity{data: %{"object" => %{"announcements" => announces}}} <- Repo.get(Activity, id) do
lain's avatar
lain committed
486
      q = from(u in User, where: u.ap_id in ^announces)
487
      users = Repo.all(q)
lain's avatar
lain committed
488
      render(conn, AccountView, "accounts.json", %{users: users, as: :user})
489 490 491 492 493
    else
      _ -> json(conn, [])
    end
  end

Roger Braun's avatar
Roger Braun committed
494
  def hashtag_timeline(%{assigns: %{user: user}} = conn, params) do
495 496
    local_only = params["local"] in [true, "True", "true", "1"]

lain's avatar
lain committed
497 498 499
    params =
      params
      |> Map.put("type", "Create")
500
      |> Map.put("local_only", local_only)
lain's avatar
lain committed
501
      |> Map.put("blocking_user", user)
Roger Braun's avatar
Roger Braun committed
502

lain's avatar
lain committed
503 504 505
    activities =
      ActivityPub.fetch_public_activities(params)
      |> Enum.reverse()
Roger Braun's avatar
Roger Braun committed
506 507

    conn
508
    |> add_link_headers(:hashtag_timeline, activities, params["tag"], %{"local" => local_only})
Roger Braun's avatar
Roger Braun committed
509 510 511
    |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
  end

512 513 514 515
  # TODO: Pagination
  def followers(conn, %{"id" => id}) do
    with %User{} = user <- Repo.get(User, id),
         {:ok, followers} <- User.get_followers(user) do
lain's avatar
lain committed
516
      render(conn, AccountView, "accounts.json", %{users: followers, as: :user})
517 518 519 520 521 522
    end
  end

  def following(conn, %{"id" => id}) do
    with %User{} = user <- Repo.get(User, id),
         {:ok, followers} <- User.get_friends(user) do
lain's avatar
lain committed
523
      render(conn, AccountView, "accounts.json", %{users: followers, as: :user})
524 525 526
    end
  end

527 528 529 530 531 532
  def follow_requests(%{assigns: %{user: followed}} = conn, _params) do
    with {:ok, follow_requests} <- User.get_follow_requests(followed) do
      render(conn, AccountView, "accounts.json", %{users: follow_requests, as: :user})
    end
  end

William Pitcock's avatar
William Pitcock committed
533 534
  def authorize_follow_request(%{assigns: %{user: followed}} = conn, %{"id" => id}) do
    with %User{} = follower <- Repo.get(User, id),
535
         {:ok, follower} <- User.maybe_follow(follower, followed),
William Pitcock's avatar
William Pitcock committed
536
         %Activity{} = follow_activity <- Utils.fetch_latest_follow(follower, followed),
William Pitcock's avatar
William Pitcock committed
537
         {:ok, follow_activity} <- Utils.update_follow_state(follow_activity, "accept"),
William Pitcock's avatar
William Pitcock committed
538 539
         {:ok, _activity} <-
           ActivityPub.accept(%{
William Pitcock's avatar
William Pitcock committed
540
             to: [follower.ap_id],
William Pitcock's avatar
William Pitcock committed
541 542 543 544 545 546 547 548 549 550 551 552 553
             actor: followed.ap_id,
             object: follow_activity.data["id"],
             type: "Accept"
           }) do
      render(conn, AccountView, "relationship.json", %{user: followed, target: follower})
    else
      {:error, message} ->
        conn
        |> put_resp_content_type("application/json")
        |> send_resp(403, Jason.encode!(%{"error" => message}))
    end
  end

William Pitcock's avatar
William Pitcock committed
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
  def reject_follow_request(%{assigns: %{user: followed}} = conn, %{"id" => id}) do
    with %User{} = follower <- Repo.get(User, id),
         %Activity{} = follow_activity <- Utils.fetch_latest_follow(follower, followed),
         {:ok, follow_activity} <- Utils.update_follow_state(follow_activity, "reject"),
         {:ok, _activity} <-
           ActivityPub.reject(%{
             to: [follower.ap_id],
             actor: followed.ap_id,
             object: follow_activity.data["id"],
             type: "Reject"
           }) do
      render(conn, AccountView, "relationship.json", %{user: followed, target: follower})
    else
      {:error, message} ->
        conn
        |> put_resp_content_type("application/json")
        |> send_resp(403, Jason.encode!(%{"error" => message}))
    end
  end
William Pitcock's avatar
William Pitcock committed
573

eal's avatar
eal committed
574 575
  def follow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
    with %User{} = followed <- Repo.get(User, id),
576
         {:ok, follower} <- User.maybe_direct_follow(follower, followed),
577
         {:ok, _activity} <- ActivityPub.follow(follower, followed) do
lain's avatar
lain committed
578
      render(conn, AccountView, "relationship.json", %{user: follower, target: followed})
579
    else
580
      {:error, message} ->
eal's avatar
eal committed
581 582
        conn
        |> put_resp_content_type("application/json")
lain's avatar
lain committed
583
        |> send_resp(403, Jason.encode!(%{"error" => message}))
584 585 586
    end
  end

eal's avatar
eal committed
587
  def follow(%{assigns: %{user: follower}} = conn, %{"uri" => uri}) do
eal's avatar
eal committed
588
    with %User{} = followed <- Repo.get_by(User, nickname: uri),
589
         {:ok, follower} <- User.maybe_direct_follow(follower, followed),
590
         {:ok, _activity} <- ActivityPub.follow(follower, followed) do
lain's avatar
lain committed
591
      render(conn, AccountView, "account.json", %{user: followed})
eal's avatar
eal committed
592
    else
593
      {:error, message} ->
eal's avatar
eal committed
594 595
        conn
        |> put_resp_content_type("application/json")
lain's avatar
lain committed
596
        |> send_resp(403, Jason.encode!(%{"error" => message}))
eal's avatar
eal committed
597 598 599
    end
  end

600 601
  def unfollow(%{assigns: %{user: follower}} = conn, %{"id" => id}) do
    with %User{} = followed <- Repo.get(User, id),
602 603
         {:ok, _activity} <- ActivityPub.unfollow(follower, followed),
         {:ok, follower, _} <- User.unfollow(follower, followed) do
lain's avatar
lain committed
604
      render(conn, AccountView, "relationship.json", %{user: follower, target: followed})
605 606 607
    end
  end

Roger Braun's avatar
Roger Braun committed
608 609
  def block(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
    with %User{} = blocked <- Repo.get(User, id),
610 611
         {:ok, blocker} <- User.block(blocker, blocked),
         {:ok, _activity} <- ActivityPub.block(blocker, blocked) do
lain's avatar
lain committed
612
      render(conn, AccountView, "relationship.json", %{user: blocker, target: blocked})
Roger Braun's avatar
Roger Braun committed
613
    else
614
      {:error, message} ->
Roger Braun's avatar
Roger Braun committed
615 616
        conn
        |> put_resp_content_type("application/json")
lain's avatar
lain committed
617
        |> send_resp(403, Jason.encode!(%{"error" => message}))
Roger Braun's avatar
Roger Braun committed
618 619 620 621 622
    end
  end

  def unblock(%{assigns: %{user: blocker}} = conn, %{"id" => id}) do
    with %User{} = blocked <- Repo.get(User, id),
623 624
         {:ok, blocker} <- User.unblock(blocker, blocked),
         {:ok, _activity} <- ActivityPub.unblock(blocker, blocked) do
lain's avatar
lain committed
625
      render(conn, AccountView, "relationship.json", %{user: blocker, target: blocked})
Roger Braun's avatar
Roger Braun committed
626
    else
627
      {:error, message} ->
Roger Braun's avatar
Roger Braun committed
628 629
        conn
        |> put_resp_content_type("application/json")
lain's avatar
lain committed
630
        |> send_resp(403, Jason.encode!(%{"error" => message}))
Roger Braun's avatar
Roger Braun committed
631 632 633
    end
  end

634 635 636
  # TODO: Use proper query
  def blocks(%{assigns: %{user: user}} = conn, _) do
    with blocked_users <- user.info["blocks"] || [],
lain's avatar
lain committed
637
         accounts <- Enum.map(blocked_users, fn ap_id -> User.get_cached_by_ap_id(ap_id) end) do
638 639 640 641 642
      res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
      json(conn, res)
    end
  end

eal's avatar
eal committed
643 644 645 646 647 648 649 650 651 652 653 654 655 656
  def domain_blocks(%{assigns: %{user: %{info: info}}} = conn, _) do
    json(conn, info["domain_blocks"] || [])
  end

  def block_domain(%{assigns: %{user: blocker}} = conn, %{"domain" => domain}) do
    User.block_domain(blocker, domain)
    json(conn, %{})
  end

  def unblock_domain(%{assigns: %{user: blocker}} = conn, %{"domain" => domain}) do
    User.unblock_domain(blocker, domain)
    json(conn, %{})
  end

657 658 659 660 661
  def search2(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
    accounts = User.search(query, params["resolve"] == "true")

    fetched =
      if Regex.match?(~r/https?:/, query) do
lain's avatar
lain committed
662 663
        with {:ok, object} <- ActivityPub.fetch_object_from_id(query) do
          [Activity.get_create_activity_by_object_ap_id(object.data["id"])]
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
        else
          _e -> []
        end
      end || []

    q =
      from(
        a in Activity,
        where: fragment("?->>'type' = 'Create'", a.data),
        where: "https://www.w3.org/ns/activitystreams#Public" in a.recipients,
        where:
          fragment(
            "to_tsvector('english', ?->'object'->>'content') @@ plainto_tsquery('english', ?)",
            a.data,
            ^query
          ),
        limit: 20,
        order_by: [desc: :id]
      )

    statuses = Repo.all(q) ++ fetched

    tags_path = Web.base_url() <> "/tag/"

    tags =
      String.split(query)
      |> Enum.uniq()
      |> Enum.filter(fn tag -> String.starts_with?(tag, "#") end)
      |> Enum.map(fn tag -> String.slice(tag, 1..-1) end)
      |> Enum.map(fn tag -> %{name: tag, url: tags_path <> tag} end)

    res = %{
      "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
      "statuses" =>
        StatusView.render("index.json", activities: statuses, for: user, as: :activity),
      "hashtags" => tags
    }

    json(conn, res)
  end

705
  def search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
706
    accounts = User.search(query, params["resolve"] == "true")
Roger Braun's avatar
Roger Braun committed
707

lain's avatar
lain committed
708 709
    fetched =
      if Regex.match?(~r/https?:/, query) do
lain's avatar
lain committed
710 711
        with {:ok, object} <- ActivityPub.fetch_object_from_id(query) do
          [Activity.get_create_activity_by_object_ap_id(object.data["id"])]
lain's avatar
lain committed
712 713 714 715 716 717 718 719 720
        else
          _e -> []
        end
      end || []

    q =
      from(
        a in Activity,
        where: fragment("?->>'type' = 'Create'", a.data),
721
        where: "https://www.w3.org/ns/activitystreams#Public" in a.recipients,
lain's avatar
lain committed
722 723 724 725 726 727
        where:
          fragment(
            "to_tsvector('english', ?->'object'->>'content') @@ plainto_tsquery('english', ?)",
            a.data,
            ^query
          ),
lain's avatar
lain committed
728
        limit: 20,
lain's avatar
lain committed
729
        order_by: [desc: :id]
lain's avatar
lain committed
730
      )
731 732

    statuses = Repo.all(q) ++ fetched
733 734 735 736 737 738

    tags =
      String.split(query)
      |> Enum.uniq()
      |> Enum.filter(fn tag -> String.starts_with?(tag, "#") end)
      |> Enum.map(fn tag -> String.slice(tag, 1..-1) end)
Roger Braun's avatar
Roger Braun committed
739 740 741

    res = %{
      "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
lain's avatar
lain committed
742 743
      "statuses" =>
        StatusView.render("index.json", activities: statuses, for: user, as: :activity),
744
      "hashtags" => tags
Roger Braun's avatar
Roger Braun committed
745 746 747 748 749
    }

    json(conn, res)
  end

750 751
  def account_search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
    accounts = User.search(query, params["resolve"] == "true")
752 753 754 755 756 757

    res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)

    json(conn, res)
  end

758
  def favourites(%{assigns: %{user: user}} = conn, _) do
lain's avatar
lain committed
759 760 761 762 763
    params =
      %{}
      |> Map.put("type", "Create")
      |> Map.put("favorited_by", user.ap_id)
      |> Map.put("blocking_user", user)
764

lain's avatar
lain committed
765 766 767
    activities =
      ActivityPub.fetch_public_activities(params)
      |> Enum.reverse()
768 769 770 771 772

    conn
    |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
  end

eal's avatar
eal committed
773 774 775 776 777 778 779
  def get_lists(%{assigns: %{user: user}} = conn, opts) do
    lists = Pleroma.List.for_user(user, opts)
    res = ListView.render("lists.json", lists: lists)
    json(conn, res)
  end

  def get_list(%{assigns: %{user: user}} = conn, %{"id" => id}) do
eal's avatar
eal committed
780
    with %Pleroma.List{} = list <- Pleroma.List.get(id, user) do
eal's avatar
eal committed
781 782 783 784 785 786 787 788
      res = ListView.render("list.json", list: list)
      json(conn, res)
    else
      _e -> json(conn, "error")
    end
  end

  def delete_list(%{assigns: %{user: user}} = conn, %{"id" => id}) do
eal's avatar
eal committed
789
    with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
eal's avatar
eal committed
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
         {:ok, _list} <- Pleroma.List.delete(list) do
      json(conn, %{})
    else
      _e ->
        json(conn, "error")
    end
  end

  def create_list(%{assigns: %{user: user}} = conn, %{"title" => title}) do
    with {:ok, %Pleroma.List{} = list} <- Pleroma.List.create(title, user) do
      res = ListView.render("list.json", list: list)
      json(conn, res)
    end
  end

  def add_to_list(%{assigns: %{user: user}} = conn, %{"id" => id, "account_ids" => accounts}) do
    accounts
    |> Enum.each(fn account_id ->
eal's avatar
eal committed
808
      with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
eal's avatar
eal committed
809
           %User{} = followed <- Repo.get(User, account_id) do
eal's avatar
eal committed
810
        Pleroma.List.follow(list, followed)
eal's avatar
eal committed
811 812 813 814 815 816 817 818 819
      end
    end)

    json(conn, %{})
  end

  def remove_from_list(%{assigns: %{user: user}} = conn, %{"id" => id, "account_ids" => accounts}) do
    accounts
    |> Enum.each(fn account_id ->
eal's avatar
eal committed
820
      with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
eal's avatar
eal committed
821 822 823 824 825 826 827 828 829
           %User{} = followed <- Repo.get(Pleroma.User, account_id) do
        Pleroma.List.unfollow(list, followed)
      end
    end)

    json(conn, %{})
  end

  def list_accounts(%{assigns: %{user: user}} = conn, %{"id" => id}) do
eal's avatar
eal committed
830
    with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
eal's avatar
eal committed
831 832 833 834 835 836
         {:ok, users} = Pleroma.List.get_following(list) do
      render(conn, AccountView, "accounts.json", %{users: users, as: :user})
    end
  end

  def rename_list(%{assigns: %{user: user}} = conn, %{"id" => id, "title" => title}) do
eal's avatar
eal committed
837
    with %Pleroma.List{} = list <- Pleroma.List.get(id, user),
eal's avatar
eal committed
838 839 840 841 842 843 844 845 846 847
         {:ok, list} <- Pleroma.List.rename(list, title) do
      res = ListView.render("list.json", list: list)
      json(conn, res)
    else
      _e ->
        json(conn, "error")
    end
  end

  def list_timeline(%{assigns: %{user: user}} = conn, %{"list_id" => id} = params) do
eal's avatar
eal committed
848
    with %Pleroma.List{title: title, following: following} <- Pleroma.List.get(id, user) do
eal's avatar
eal committed
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
      params =
        params
        |> Map.put("type", "Create")
        |> Map.put("blocking_user", user)

      # adding title is a hack to not make empty lists function like a public timeline
      activities =
        ActivityPub.fetch_activities([title | following], params)
        |> Enum.reverse()

      conn
      |> render(StatusView, "index.json", %{activities: activities, for: user, as: :activity})
    else
      _e ->
        conn
        |> put_status(403)
        |> json(%{error: "Error."})
    end
  end

Roger Braun's avatar
Roger Braun committed
869
  def index(%{assigns: %{user: user}} = conn, _params) do
lain's avatar
lain committed
870 871 872
    token =
      conn
      |> get_session(:oauth_token)
Roger Braun's avatar
Roger Braun committed
873 874

    if user && token do
875
      mastodon_emoji = mastodonized_emoji()
Roger Braun's avatar
Roger Braun committed
876
      accounts = Map.put(%{}, user.id, AccountView.render("account.json", %{user: user}))
lain's avatar
lain committed
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891

      initial_state =
        %{
          meta: %{
            streaming_api_base_url:
              String.replace(Pleroma.Web.Endpoint.static_url(), "http", "ws"),
            access_token: token,
            locale: "en",
            domain: Pleroma.Web.Endpoint.host(),
            admin: "1",
            me: "#{user.id}",
            unfollow_modal: false,
            boost_modal: false,
            delete_modal: true,
            auto_play_gif: false,
Haelwenn Monnier's avatar
Haelwenn Monnier committed
892
            display_sensitive_media: false,
893 894
            reduce_motion: false,
            max_toot_chars: Keyword.get(@instance, :limit)
Roger Braun's avatar
Roger Braun committed
895
          },
896 897 898
          rights: %{
            delete_others_notice: !!user.info["is_moderator"]
          },
lain's avatar
lain committed
899 900
          compose: %{
            me: "#{user.id}",
901
            default_privacy: user.info["default_scope"] || "public",
lain's avatar
lain committed
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919
            default_sensitive: false
          },
          media_attachments: %{
            accept_content_types: [
              ".jpg",
              ".jpeg",
              ".png",
              ".gif",
              ".webm",
              ".mp4",
              ".m4v",
              "image\/jpeg",
              "image\/png",
              "image\/gif",
              "video\/webm",
              "video\/mp4"
            ]
          },
lain's avatar
lain committed
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
          settings:
            Map.get(user.info, "settings") ||
              %{
                onboarded: true,
                home: %{
                  shows: %{
                    reblog: true,
                    reply: true
                  }
                },
                notifications: %{
                  alerts: %{
                    follow: true,
                    favourite: true,
                    reblog: true,
                    mention: true
                  },
                  shows: %{
                    follow: true,
                    favourite: true,
                    reblog: true,
                    mention: true
                  },
                  sounds: %{
                    follow: true,
                    favourite: true,
                    reblog: true,
                    mention: true
                  }
                }
lain's avatar
lain committed
950 951 952 953 954 955 956 957
              },
          push_subscription: nil,
          accounts: accounts,
          custom_emojis: mastodon_emoji,
          char_limit: Keyword.get(@instance, :limit)
        }
        |> Jason.encode!()

Roger Braun's avatar
Roger Braun committed
958 959 960 961 962 963 964 965 966
      conn
      |> put_layout(false)
      |> render(MastodonView, "index.html", %{initial_state: initial_state})
    else
      conn
      |> redirect(to: "/web/login")
    end
  end

967 968 969 970 971 972
  def put_settings(%{assigns: %{user: user}} = conn, %{"data" => settings} = _params) do
    with new_info <- Map.put(user.info, "settings", settings),
         change <- User.info_changeset(user, %{info: new_info}),
         {:ok, _user} <- User.update_and_set_cache(change) do
      conn
      |> json(%{})
lain's avatar
lain committed
973 974
    else
      e ->
975 976 977 978 979
        conn
        |> json(%{error: inspect(e)})
    end
  end

980
  def login(conn, _) do
Roger Braun's avatar
Roger Braun committed
981
    conn
982
    |> render(MastodonView, "login.html", %{error: false})
Roger Braun's avatar
Roger Braun committed
983 984 985 986 987 988 989
  end

  defp get_or_make_app() do
    with %App{} = app <- Repo.get_by(App, client_name: "Mastodon-Local") do
      {:ok, app}
    else
      _e ->
lain's avatar
lain committed
990 991 992 993 994 995 996
        cs =
          App.register_changeset(%App{}, %{
            client_name: "Mastodon-Local",
            redirect_uris: ".",
            scopes: "read,write,follow"
          })

Roger Braun's avatar
Roger Braun committed
997 998 999 1000
        Repo.insert(cs)
    end
  end

lain's avatar
lain committed
1001
  def login_post(conn, %{"authorization" => %{"name" => name, "password" => password}}) do
1002
    with %User{} = user <- User.get_by_nickname_or_email(name),
Roger Braun's avatar
Roger Braun committed
1003 1004 1005 1006 1007 1008
         true <- Pbkdf2.checkpw(password, user.password_hash),
         {:ok, app} <- get_or_make_app(),
         {:ok, auth} <- Authorization.create_authorization(app, user),
         {:ok, token} <- Token.exchange_token(app, auth) do
      conn
      |> put_session(:oauth_token, token.token)
1009
      |> redirect(to: "/web/getting-started")
1010 1011 1012 1013
    else
      _e ->
        conn
        |> render(MastodonView, "login.html", %{error: "Wrong username or password"})
Roger Braun's avatar
Roger Braun committed
1014 1015 1016
    end
  end

Roger Braun's avatar
Roger Braun committed
1017 1018 1019 1020 1021 1022
  def logout(conn, _) do
    conn
    |> clear_session
    |> redirect(to: "/")
  end

1023 1024
  def relationship_noop(%{assigns: %{user: user}} = conn, %{"id" => id}) do
    Logger.debug("Unimplemented, returning unmodified relationship")
lain's avatar
lain committed
1025

1026
    with %User{} = target <- Repo.get(User, id) do
lain's avatar
lain committed
1027
      render(conn, AccountView, "relationship.json", %{user: user, target: target})
1028 1029 1030
    end
  end

1031 1032 1033 1034
  def empty_array(conn, _) do
    Logger.debug("Unimplemented, returning an empty array")
    json(conn, [])
  end
1035

1036 1037 1038 1039 1040
  def empty_object(conn, _) do
    Logger.debug("Unimplemented, returning an empty object")
    json(conn, %{})
  end

1041
  def render_notification(user, %{id: id, activity: activity, inserted_at: created_at} = _params) do
1042
    actor = User.get_cached_by_ap_id(activity.data["actor"])
lain's avatar
lain committed
1043 1044 1045 1046 1047

    created_at =
      NaiveDateTime.to_iso8601(created_at)
      |> String.replace(~r/(\.\d+)?$/, ".000Z", global: false)

1048 1049
    case activity.data["type"] do
      "Create" ->
lain's avatar
lain committed
1050 1051 1052 1053 1054 1055 1056 1057
        %{
          id: id,
          type: "mention",
          created_at: created_at,
          account: AccountView.render("account.json", %{user: actor}),
          status: StatusView.render("status.json", %{activity: activity, for: user})
        }

1058 1059
      "Like" ->
        liked_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
lain's avatar
lain committed
1060 1061 1062 1063 1064 1065 1066 1067 1068

        %{
          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})
        }

1069 1070
      "Announce" ->
        announced_activity = Activity.get_create_activity_by_object_ap_id(activity.data["object"])
lain's avatar
lain committed
1071 1072 1073 1074 1075 1076 1077 1078 1079

        %{
          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})
        }

1080
      "Follow" ->
lain's avatar
lain committed
1081 1082 1083 1084 1085 1086 1087 1088 1089
        %{
          id: id,
          type: "follow",
          created_at: created_at,
          account: AccountView.render("account.json", %{user: actor})
        }

      _ ->
        nil
1090 1091
    end
  end
1092 1093 1094 1095 1096 1097

  def errors(conn, _) do
    conn
    |> put_status(500)
    |> json("Something went wrong")
  end
1098

hakabahitoyo's avatar
hakabahitoyo committed
1099 1100
  @suggestions Application.get_env(:pleroma, :suggestions)

hakabahitoyo's avatar
hakabahitoyo committed
1101
  def suggestions(%{assigns: %{user: user}} = conn, _) do
Hakaba Hitoyo's avatar
Hakaba Hitoyo committed
1102
    if Keyword.get(@suggestions, :enabled, false) do
Hakaba Hitoyo's avatar
Hakaba Hitoyo committed
1103 1104
      api = Keyword.get(@suggestions, :third_party_engine, "")
      timeout = Keyword.get(@suggestions, :timeout, 5000)
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114

      host =
        Application.get_env(:pleroma, Pleroma.Web.Endpoint)
        |> Keyword.get(:url)
        |> Keyword.get(:host)

      user = user.nickname
      url = String.replace(api, "{{host}}", host) |> String.replace("{{user}}", user)

      with {:ok, %{status_code: 200, body: body}} <-
Hakaba Hitoyo's avatar
Hakaba Hitoyo committed
1115
             @httpoison.get(url, [], timeout: timeout, recv_timeout: timeout),
1116 1117 1118 1119 1120 1121
           {:ok, data} <- Jason.decode(body) do
        data2 =
          Enum.slice(data, 0, 40)
          |> Enum.map(fn x ->
            Map.put(x, "id", User.get_or_fetch(x["acct"]).id)
          end)
hakabahitoyo's avatar
hakabahitoyo committed
1122

1123 1124 1125
        conn
        |> json(data2)
      else
Hakaba Hitoyo's avatar
Hakaba Hitoyo committed
1126
        e -> Logger.error("Could not retrieve suggestions at fetch #{url}, #{inspect(e)}")
1127
      end
1128
    else
1129
      json(conn, [])
1130
    end
1131
  end
1132

Mayel's avatar
Mayel committed
1133
  def register(conn, _) do
Mayel's avatar
s  
Mayel committed
1134
    conn
Mayel's avatar
Mayel committed
1135 1136 1137 1138 1139 1140 1141 1142
    |> render(MastodonView, "register.html", %{error: false})
  end

  def register_post(conn, params) do
    with {:ok, user} <- TwitterAPI.register_user(params),
         {:ok, app} <- get_or_make_app(),
         {:ok, auth} <- Authorization.create_authorization(app, user),
         {:ok, token} <- Token.exchange_token(app, auth) do
1143
      conn
Mayel's avatar
Mayel committed
1144 1145 1146 1147 1148 1149 1150
      |> put_session(:oauth_token, token.token)
      |> redirect(to: "/web/getting-started")
    else
      _e ->
        conn
        |> render(MastodonView, "register.html", %{error: "Wrong details"})
    end
1151 1152
  end
end