twitter_api_controller.ex 18.8 KB
Newer Older
1
2
defmodule Pleroma.Web.TwitterAPI.Controller do
  use Pleroma.Web, :controller
3
4
5

  import Pleroma.Web.ControllerHelper, only: [json_response: 3]

6
  alias Pleroma.Web.TwitterAPI.{TwitterAPI, UserView, ActivityView, NotificationView}
lain's avatar
lain committed
7
  alias Pleroma.Web.CommonAPI
8
  alias Pleroma.{Repo, Activity, Object, User, Notification}
lain's avatar
lain committed
9
  alias Pleroma.Web.ActivityPub.ActivityPub
10
  alias Pleroma.Web.ActivityPub.Utils
11
  alias Ecto.Changeset
12

lain's avatar
lain committed
13
14
  require Logger

href's avatar
href committed
15
  plug(:only_if_public_instance when action in [:public_timeline, :public_and_external_timeline])
16
17
  action_fallback(:errors)

18
  def verify_credentials(%{assigns: %{user: user}} = conn, _params) do
lain's avatar
lain committed
19
20
    token = Phoenix.Token.sign(conn, "user socket", user.id)
    render(conn, UserView, "show.json", %{user: user, token: token})
21
22
  end

Thog's avatar
Thog committed
23
  def status_update(%{assigns: %{user: user}} = conn, %{"status" => _} = status_data) do
24
    with media_ids <- extract_media_ids(status_data),
lain's avatar
lain committed
25
26
         {:ok, activity} <-
           TwitterAPI.create_status(user, Map.put(status_data, "media_ids", media_ids)) do
dtluna's avatar
dtluna committed
27
      conn
lain's avatar
lain committed
28
      |> json(ActivityView.render("activity.json", activity: activity, for: user))
dtluna's avatar
dtluna committed
29
    else
30
      _ -> empty_status_reply(conn)
dtluna's avatar
dtluna committed
31
    end
lain's avatar
lain committed
32
33
  end

dtluna's avatar
dtluna committed
34
35
36
37
38
39
40
41
  def status_update(conn, _status_data) do
    empty_status_reply(conn)
  end

  defp empty_status_reply(conn) do
    bad_request_reply(conn, "Client must provide a 'status' parameter with a value.")
  end

lain's avatar
lain committed
42
43
44
  defp extract_media_ids(status_data) do
    with media_ids when not is_nil(media_ids) <- status_data["media_ids"],
         split_ids <- String.split(media_ids, ","),
lain's avatar
lain committed
45
46
47
48
         clean_ids <- Enum.reject(split_ids, fn id -> String.length(id) == 0 end) do
      clean_ids
    else
      _e -> []
lain's avatar
lain committed
49
50
51
    end
  end

lain's avatar
lain committed
52
  def public_and_external_timeline(%{assigns: %{user: user}} = conn, params) do
lain's avatar
lain committed
53
54
    params =
      params
55
      |> Map.put("type", ["Create", "Announce"])
lain's avatar
lain committed
56
57
58
      |> Map.put("blocking_user", user)

    activities = ActivityPub.fetch_public_activities(params)
lain's avatar
lain committed
59
60

    conn
lain's avatar
lain committed
61
    |> render(ActivityView, "index.json", %{activities: activities, for: user})
lain's avatar
lain committed
62
63
  end

64
  def public_timeline(%{assigns: %{user: user}} = conn, params) do
lain's avatar
lain committed
65
66
    params =
      params
67
      |> Map.put("type", ["Create", "Announce"])
lain's avatar
lain committed
68
69
70
71
      |> Map.put("local_only", true)
      |> Map.put("blocking_user", user)

    activities = ActivityPub.fetch_public_activities(params)
lain's avatar
lain committed
72
73

    conn
lain's avatar
lain committed
74
    |> render(ActivityView, "index.json", %{activities: activities, for: user})
lain's avatar
lain committed
75
76
  end

lain's avatar
lain committed
77
  def friends_timeline(%{assigns: %{user: user}} = conn, params) do
lain's avatar
lain committed
78
79
80
81
82
83
    params =
      params
      |> Map.put("type", ["Create", "Announce", "Follow", "Like"])
      |> Map.put("blocking_user", user)
      |> Map.put("user", user)

84
85
86
    activities =
      ActivityPub.fetch_activities([user.ap_id | user.following], params)
      |> ActivityPub.contain_timeline(user)
lain's avatar
lain committed
87
88

    conn
lain's avatar
lain committed
89
    |> render(ActivityView, "index.json", %{activities: activities, for: user})
lain's avatar
lain committed
90
91
  end

eal's avatar
eal committed
92
93
94
  def show_user(conn, params) do
    with {:ok, shown} <- TwitterAPI.get_user(params) do
      if user = conn.assigns.user do
lain's avatar
lain committed
95
        render(conn, UserView, "show.json", %{user: shown, for: user})
eal's avatar
eal committed
96
      else
lain's avatar
lain committed
97
        render(conn, UserView, "show.json", %{user: shown})
eal's avatar
eal committed
98
99
100
101
102
103
104
      end
    else
      {:error, msg} ->
        bad_request_reply(conn, msg)
    end
  end

dtluna's avatar
dtluna committed
105
  def user_timeline(%{assigns: %{user: user}} = conn, params) do
106
107
    case TwitterAPI.get_user(user, params) do
      {:ok, target_user} ->
108
        activities = ActivityPub.fetch_user_activities(target_user, user, params)
lain's avatar
lain committed
109

110
        conn
lain's avatar
lain committed
111
        |> render(ActivityView, "index.json", %{activities: activities, for: user})
lain's avatar
lain committed
112

113
114
115
      {:error, msg} ->
        bad_request_reply(conn, msg)
    end
dtluna's avatar
dtluna committed
116
117
  end

dtluna's avatar
dtluna committed
118
  def mentions_timeline(%{assigns: %{user: user}} = conn, params) do
119
120
121
122
123
    params =
      params
      |> Map.put("type", ["Create", "Announce", "Follow", "Like"])
      |> Map.put("blocking_user", user)

lain's avatar
lain committed
124
    activities = ActivityPub.fetch_activities([user.ap_id], params)
dtluna's avatar
dtluna committed
125
126

    conn
lain's avatar
lain committed
127
128
129
130
131
132
133
    |> render(ActivityView, "index.json", %{activities: activities, for: user})
  end

  def dm_timeline(%{assigns: %{user: user}} = conn, params) do
    query =
      ActivityPub.fetch_activities_query(
        [user.ap_id],
134
        Map.merge(params, %{"type" => "Create", "user" => user, visibility: "direct"})
lain's avatar
lain committed
135
136
137
138
139
      )

    activities = Repo.all(query)

    conn
lain's avatar
lain committed
140
    |> render(ActivityView, "index.json", %{activities: activities, for: user})
dtluna's avatar
dtluna committed
141
142
  end

143
144
145
146
147
148
149
  def notifications(%{assigns: %{user: user}} = conn, params) do
    notifications = Notification.for_user(user, params)

    conn
    |> render(NotificationView, "notification.json", %{notifications: notifications, for: user})
  end

150
151
152
153
154
155
156
157
158
  def notifications_read(%{assigns: %{user: user}} = conn, %{"latest_id" => latest_id} = params) do
    Notification.set_read_up_to(user, latest_id)

    notifications = Notification.for_user(user, params)

    conn
    |> render(NotificationView, "notification.json", %{notifications: notifications, for: user})
  end

Maksim's avatar
Maksim committed
159
  def notifications_read(%{assigns: %{user: _user}} = conn, _) do
160
161
162
    bad_request_reply(conn, "You need to specify latest_id")
  end

163
164
  def follow(%{assigns: %{user: user}} = conn, params) do
    case TwitterAPI.follow(user, params) do
165
      {:ok, user, followed, _activity} ->
dtluna's avatar
dtluna committed
166
        render(conn, UserView, "show.json", %{user: followed, for: user})
lain's avatar
lain committed
167
168
169

      {:error, msg} ->
        forbidden_json_reply(conn, msg)
170
    end
lain's avatar
lain committed
171
172
  end

eal's avatar
eal committed
173
174
175
  def block(%{assigns: %{user: user}} = conn, params) do
    case TwitterAPI.block(user, params) do
      {:ok, user, blocked} ->
lain's avatar
lain committed
176
177
178
179
        render(conn, UserView, "show.json", %{user: blocked, for: user})

      {:error, msg} ->
        forbidden_json_reply(conn, msg)
eal's avatar
eal committed
180
181
182
183
184
185
    end
  end

  def unblock(%{assigns: %{user: user}} = conn, params) do
    case TwitterAPI.unblock(user, params) do
      {:ok, user, blocked} ->
lain's avatar
lain committed
186
187
188
189
        render(conn, UserView, "show.json", %{user: blocked, for: user})

      {:error, msg} ->
        forbidden_json_reply(conn, msg)
eal's avatar
eal committed
190
191
192
    end
  end

lain's avatar
lain committed
193
  def delete_post(%{assigns: %{user: user}} = conn, %{"id" => id}) do
normandy's avatar
normandy committed
194
    with {:ok, activity} <- TwitterAPI.delete(user, id) do
normandy's avatar
normandy committed
195
      render(conn, ActivityView, "activity.json", %{activity: activity, for: user})
lain's avatar
lain committed
196
197
198
    end
  end

199
  def unfollow(%{assigns: %{user: user}} = conn, params) do
200
    case TwitterAPI.unfollow(user, params) do
201
      {:ok, user, unfollowed} ->
dtluna's avatar
dtluna committed
202
        render(conn, UserView, "show.json", %{user: unfollowed, for: user})
lain's avatar
lain committed
203
204
205

      {:error, msg} ->
        forbidden_json_reply(conn, msg)
206
    end
lain's avatar
lain committed
207
208
  end

209
  def fetch_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
lain's avatar
lain committed
210
211
    with %Activity{} = activity <- Repo.get(Activity, id),
         true <- ActivityPub.visible_for_user?(activity, user) do
lain's avatar
lain committed
212
      render(conn, ActivityView, "activity.json", %{activity: activity, for: user})
lain's avatar
lain committed
213
    end
lain's avatar
lain committed
214
215
  end

216
  def fetch_conversation(%{assigns: %{user: user}} = conn, %{"id" => id}) do
217
218
    id = String.to_integer(id)

lain's avatar
lain committed
219
220
221
222
223
224
225
226
227
    with context when is_binary(context) <- TwitterAPI.conversation_id_to_context(id),
         activities <-
           ActivityPub.fetch_activities_for_context(context, %{
             "blocking_user" => user,
             "user" => user
           }) do
      conn
      |> render(ActivityView, "index.json", %{activities: activities, for: user})
    end
228
229
  end

Ivan Tashkinov's avatar
Ivan Tashkinov committed
230
231
232
233
  @doc """
  Updates metadata of uploaded media object.
  Derived from [Twitter API endpoint](https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-metadata-create).
  """
234
235
  def update_media(%{assigns: %{user: user}} = conn, %{"media_id" => id} = data) do
    object = Repo.get(Object, id)
236
237
    description = get_in(data, ["alt_text", "text"]) || data["name"] || data["description"]

238
239
240
241
    {conn, status, response_body} =
      cond do
        !object ->
          {halt(conn), :not_found, ""}
Ivan Tashkinov's avatar
Ivan Tashkinov committed
242

243
        !Object.authorize_mutation(object, user) ->
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
          {halt(conn), :forbidden, "You can only update your own uploads."}

        !is_binary(description) ->
          {conn, :not_modified, ""}

        true ->
          new_data = Map.put(object.data, "name", description)

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

          {conn, :no_content, ""}
      end
259
260

    conn
261
262
    |> put_status(status)
    |> json(response_body)
263
264
  end

265
266
  def upload(%{assigns: %{user: user}} = conn, %{"media" => media}) do
    response = TwitterAPI.upload(media, user)
lain's avatar
lain committed
267

lain's avatar
lain committed
268
269
270
271
    conn
    |> put_resp_content_type("application/atom+xml")
    |> send_resp(200, response)
  end
272

273
274
  def upload_json(%{assigns: %{user: user}} = conn, %{"media" => media}) do
    response = TwitterAPI.upload(media, user, "json")
lain's avatar
lain committed
275

276
277
278
279
    conn
    |> json_reply(200, response)
  end

lain's avatar
lain committed
280
  def get_by_id_or_ap_id(id) do
281
    activity = Repo.get(Activity, id) || Activity.get_create_activity_by_object_ap_id(id)
lain's avatar
lain committed
282

283
284
285
286
287
    if activity.data["type"] == "Create" do
      activity
    else
      Activity.get_create_activity_by_object_ap_id(activity.data["object"])
    end
lain's avatar
lain committed
288
289
  end

lain's avatar
lain committed
290
  def favorite(%{assigns: %{user: user}} = conn, %{"id" => id}) do
291
292
    with {_, {:ok, id}} <- {:param_cast, Ecto.Type.cast(:integer, id)},
         {:ok, activity} <- TwitterAPI.fav(user, id) do
293
      render(conn, ActivityView, "activity.json", %{activity: activity, for: user})
lain's avatar
lain committed
294
    end
lain's avatar
lain committed
295
296
  end

lain's avatar
lain committed
297
  def unfavorite(%{assigns: %{user: user}} = conn, %{"id" => id}) do
298
299
    with {_, {:ok, id}} <- {:param_cast, Ecto.Type.cast(:integer, id)},
         {:ok, activity} <- TwitterAPI.unfav(user, id) do
300
      render(conn, ActivityView, "activity.json", %{activity: activity, for: user})
lain's avatar
lain committed
301
    end
lain's avatar
lain committed
302
303
  end

lain's avatar
lain committed
304
  def retweet(%{assigns: %{user: user}} = conn, %{"id" => id}) do
305
306
    with {_, {:ok, id}} <- {:param_cast, Ecto.Type.cast(:integer, id)},
         {:ok, activity} <- TwitterAPI.repeat(user, id) do
307
      render(conn, ActivityView, "activity.json", %{activity: activity, for: user})
dtluna's avatar
dtluna committed
308
    end
lain's avatar
lain committed
309
310
  end

311
312
313
314
315
316
317
  def unretweet(%{assigns: %{user: user}} = conn, %{"id" => id}) do
    with {_, {:ok, id}} <- {:param_cast, Ecto.Type.cast(:integer, id)},
         {:ok, activity} <- TwitterAPI.unrepeat(user, id) do
      render(conn, ActivityView, "activity.json", %{activity: activity, for: user})
    end
  end

318
319
  def register(conn, params) do
    with {:ok, user} <- TwitterAPI.register_user(params) do
dtluna's avatar
dtluna committed
320
      render(conn, UserView, "show.json", %{user: user})
321
322
    else
      {:error, errors} ->
lain's avatar
lain committed
323
324
        conn
        |> json_reply(400, Jason.encode!(errors))
325
326
327
    end
  end

328
329
330
  def password_reset(conn, params) do
    nickname_or_email = params["email"] || params["nickname"]

331
    with true <- is_binary(nickname_or_email),
332
333
334
335
336
337
338
339
340
341
342
         %User{local: true} = user <- User.get_by_nickname_or_email(nickname_or_email) do
      {:ok, token_record} = Pleroma.PasswordResetToken.create_token(user)

      user
      |> Pleroma.UserEmail.password_reset_email(token_record.token)
      |> Pleroma.Mailer.deliver()

      json_response(conn, :no_content, "")
    end
  end

343
344
345
346
  def confirm_email(_conn, _params), do: :noop

  def email_invite(_conn, _params), do: :noop

lain's avatar
lain committed
347
  def update_avatar(%{assigns: %{user: user}} = conn, params) do
href's avatar
href committed
348
    {:ok, object} = ActivityPub.upload(params, type: :avatar)
349
    change = Changeset.change(user, %{avatar: object.data})
lain's avatar
lain committed
350
    {:ok, user} = User.update_and_set_cache(change)
lain's avatar
lain committed
351
    CommonAPI.update(user)
lain's avatar
lain committed
352

dtluna's avatar
dtluna committed
353
    render(conn, UserView, "show.json", %{user: user, for: user})
lain's avatar
lain committed
354
355
  end

lain's avatar
lain committed
356
  def update_banner(%{assigns: %{user: user}} = conn, params) do
href's avatar
href committed
357
    with {:ok, object} <- ActivityPub.upload(%{"img" => params["banner"]}, type: :banner),
358
359
360
361
         new_info <- %{"banner" => object.data},
         info_cng <- User.Info.profile_update(user.info, new_info),
         changeset <- Ecto.Changeset.change(user) |> Ecto.Changeset.put_embed(:info, info_cng),
         {:ok, user} <- User.update_and_set_cache(changeset) do
lain's avatar
lain committed
362
      CommonAPI.update(user)
lain's avatar
lain committed
363
364
365
      %{"url" => [%{"href" => href} | _]} = object.data
      response = %{url: href} |> Jason.encode!()

lain's avatar
lain committed
366
367
368
369
370
371
      conn
      |> json_reply(200, response)
    end
  end

  def update_background(%{assigns: %{user: user}} = conn, params) do
href's avatar
href committed
372
    with {:ok, object} <- ActivityPub.upload(params, type: :background),
373
374
375
376
         new_info <- %{"background" => object.data},
         info_cng <- User.Info.profile_update(user.info, new_info),
         changeset <- Ecto.Changeset.change(user) |> Ecto.Changeset.put_embed(:info, info_cng),
         {:ok, _user} <- User.update_and_set_cache(changeset) do
lain's avatar
lain committed
377
378
379
      %{"url" => [%{"href" => href} | _]} = object.data
      response = %{url: href} |> Jason.encode!()

lain's avatar
lain committed
380
381
382
383
384
      conn
      |> json_reply(200, response)
    end
  end

lain's avatar
lain committed
385
386
  def external_profile(%{assigns: %{user: current_user}} = conn, %{"profileurl" => uri}) do
    with {:ok, user_map} <- TwitterAPI.get_external_profile(current_user, uri),
lain's avatar
lain committed
387
         response <- Jason.encode!(user_map) do
lain's avatar
lain committed
388
389
      conn
      |> json_reply(200, response)
lain's avatar
lain committed
390
391
392
393
394
    else
      _e ->
        conn
        |> put_status(404)
        |> json(%{error: "Can't find user"})
lain's avatar
lain committed
395
396
397
    end
  end

398
399
  def followers(%{assigns: %{user: for_user}} = conn, params) do
    with {:ok, user} <- TwitterAPI.get_user(for_user, params),
eal's avatar
eal committed
400
         {:ok, followers} <- User.get_followers(user) do
401
402
403
404
405
406
407
      followers =
        cond do
          for_user && user.id == for_user.id -> followers
          user.info.hide_network -> []
          true -> followers
        end

408
      render(conn, UserView, "index.json", %{users: followers, for: conn.assigns[:user]})
lain's avatar
lain committed
409
410
411
412
413
    else
      _e -> bad_request_reply(conn, "Can't get followers")
    end
  end

414
  def friends(%{assigns: %{user: for_user}} = conn, params) do
415
    with {:ok, user} <- TwitterAPI.get_user(conn.assigns[:user], params),
eal's avatar
eal committed
416
         {:ok, friends} <- User.get_friends(user) do
417
418
419
420
421
422
423
      friends =
        cond do
          for_user && user.id == for_user.id -> friends
          user.info.hide_network -> []
          true -> friends
        end

424
      render(conn, UserView, "index.json", %{users: friends, for: conn.assigns[:user]})
lain's avatar
lain committed
425
426
427
428
429
    else
      _e -> bad_request_reply(conn, "Can't get friends")
    end
  end

430
  def friend_requests(conn, params) do
431
    with {:ok, user} <- TwitterAPI.get_user(conn.assigns[:user], params),
432
         {:ok, friend_requests} <- User.get_follow_requests(user) do
433
      render(conn, UserView, "index.json", %{users: friend_requests, for: conn.assigns[:user]})
434
435
436
437
438
    else
      _e -> bad_request_reply(conn, "Can't get friend requests")
    end
  end

Maksim's avatar
Maksim committed
439
  def approve_friend_request(conn, %{"user_id" => uid} = _params) do
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
    with followed <- conn.assigns[:user],
         uid when is_number(uid) <- String.to_integer(uid),
         %User{} = follower <- Repo.get(User, uid),
         {:ok, follower} <- User.maybe_follow(follower, followed),
         %Activity{} = follow_activity <- Utils.fetch_latest_follow(follower, followed),
         {:ok, follow_activity} <- Utils.update_follow_state(follow_activity, "accept"),
         {:ok, _activity} <-
           ActivityPub.accept(%{
             to: [follower.ap_id],
             actor: followed.ap_id,
             object: follow_activity.data["id"],
             type: "Accept"
           }) do
      render(conn, UserView, "show.json", %{user: follower, for: followed})
    else
      e -> bad_request_reply(conn, "Can't approve user: #{inspect(e)}")
    end
  end

Maksim's avatar
Maksim committed
459
  def deny_friend_request(conn, %{"user_id" => uid} = _params) do
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
    with followed <- conn.assigns[:user],
         uid when is_number(uid) <- String.to_integer(uid),
         %User{} = follower <- Repo.get(User, uid),
         %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, UserView, "show.json", %{user: follower, for: followed})
    else
      e -> bad_request_reply(conn, "Can't deny user: #{inspect(e)}")
    end
  end

eal's avatar
eal committed
478
479
  def friends_ids(%{assigns: %{user: user}} = conn, _params) do
    with {:ok, friends} <- User.get_friends(user) do
lain's avatar
lain committed
480
481
482
483
      ids =
        friends
        |> Enum.map(fn x -> x.id end)
        |> Jason.encode!()
484

eal's avatar
eal committed
485
486
487
488
489
490
      json(conn, ids)
    else
      _e -> bad_request_reply(conn, "Can't get friends")
    end
  end

491
  def empty_array(conn, _params) do
lain's avatar
lain committed
492
    json(conn, Jason.encode!([]))
493
  end
eal's avatar
eal committed
494

495
496
497
498
  def raw_empty_array(conn, _params) do
    json(conn, [])
  end

lain's avatar
lain committed
499
500
  defp build_info_cng(user, params) do
    info_params =
lain's avatar
lain committed
501
      ["no_rich_text", "locked", "hide_network"]
lain's avatar
lain committed
502
503
504
      |> Enum.reduce(%{}, fn key, res ->
        if value = params[key] do
          Map.put(res, key, value == "true")
505
        else
lain's avatar
lain committed
506
          res
507
        end
lain's avatar
lain committed
508
      end)
509

lain's avatar
lain committed
510
511
512
    info_params =
      if value = params["default_scope"] do
        Map.put(info_params, "default_scope", value)
513
      else
lain's avatar
lain committed
514
        info_params
515
516
      end

lain's avatar
lain committed
517
518
519
    User.Info.profile_update(user.info, info_params)
  end

Maxim Filippov's avatar
Maxim Filippov committed
520
  defp parse_profile_bio(user, params) do
lain's avatar
lain committed
521
    if bio = params["description"] do
Maxim Filippov's avatar
Maxim Filippov committed
522
      Map.put(params, "bio", User.parse_bio(bio, user))
lain's avatar
lain committed
523
524
525
526
527
528
    else
      params
    end
  end

  def update_profile(%{assigns: %{user: user}} = conn, params) do
Maxim Filippov's avatar
Maxim Filippov committed
529
    params = parse_profile_bio(user, params)
lain's avatar
lain committed
530
    info_cng = build_info_cng(user, params)
531

lain's avatar
lain committed
532
    with changeset <- User.update_changeset(user, params),
lain's avatar
lain committed
533
         changeset <- Ecto.Changeset.put_embed(changeset, :info, info_cng),
lain's avatar
lain committed
534
         {:ok, user} <- User.update_and_set_cache(changeset) do
lain's avatar
lain committed
535
      CommonAPI.update(user)
lain's avatar
lain committed
536
537
538
539
540
541
542
543
      render(conn, UserView, "user.json", %{user: user, for: user})
    else
      error ->
        Logger.debug("Can't update user: #{inspect(error)}")
        bad_request_reply(conn, "Can't update user")
    end
  end

Thog's avatar
Thog committed
544
  def search(%{assigns: %{user: user}} = conn, %{"q" => _query} = params) do
lain's avatar
lain committed
545
546
    activities = TwitterAPI.search(user, params)

lain's avatar
lain committed
547
    conn
lain's avatar
lain committed
548
    |> render(ActivityView, "index.json", %{activities: activities, for: user})
lain's avatar
lain committed
549
550
  end

551
552
553
554
555
556
557
  def search_user(%{assigns: %{user: user}} = conn, %{"query" => query}) do
    users = User.search(query, true)

    conn
    |> render(UserView, "index.json", %{users: users, for: user})
  end

558
  defp bad_request_reply(conn, error_message) do
dtluna's avatar
dtluna committed
559
    json = error_json(conn, error_message)
560
561
562
    json_reply(conn, 400, json)
  end

563
564
565
566
567
  defp json_reply(conn, status, json) do
    conn
    |> put_resp_content_type("application/json")
    |> send_resp(status, json)
  end
568
569

  defp forbidden_json_reply(conn, error_message) do
dtluna's avatar
dtluna committed
570
    json = error_json(conn, error_message)
571
572
    json_reply(conn, 403, json)
  end
dtluna's avatar
dtluna committed
573

href's avatar
href committed
574
575
576
577
578
579
580
581
  def only_if_public_instance(conn = %{conn: %{assigns: %{user: _user}}}, _), do: conn

  def only_if_public_instance(conn, _) do
    if Keyword.get(Application.get_env(:pleroma, :instance), :public) do
      conn
    else
      conn
      |> forbidden_json_reply("Invalid credentials.")
href's avatar
href committed
582
      |> halt()
href's avatar
href committed
583
584
585
    end
  end

dtluna's avatar
dtluna committed
586
  defp error_json(conn, error_message) do
lain's avatar
lain committed
587
    %{"error" => error_message, "request" => conn.request_path} |> Jason.encode!()
dtluna's avatar
dtluna committed
588
  end
589
590
591
592
593
594
595
596
597
598
599
600

  def errors(conn, {:param_cast, _}) do
    conn
    |> put_status(400)
    |> json("Invalid parameters")
  end

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