twitter_api_controller.ex 20.2 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
    token = Phoenix.Token.sign(conn, "user socket", user.id)
href's avatar
href committed
20
21
22
23

    conn
    |> put_view(UserView)
    |> render("show.json", %{user: user, token: token})
24
25
  end

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

dtluna's avatar
dtluna committed
37
38
39
40
41
42
43
44
  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
45
46
47
  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
48
49
50
51
         clean_ids <- Enum.reject(split_ids, fn id -> String.length(id) == 0 end) do
      clean_ids
    else
      _e -> []
lain's avatar
lain committed
52
53
54
    end
  end

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

    activities = ActivityPub.fetch_public_activities(params)
lain's avatar
lain committed
62
63

    conn
href's avatar
href committed
64
65
    |> put_view(ActivityView)
    |> render("index.json", %{activities: activities, for: user})
lain's avatar
lain committed
66
67
  end

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

    activities = ActivityPub.fetch_public_activities(params)
lain's avatar
lain committed
76
77

    conn
href's avatar
href committed
78
79
    |> put_view(ActivityView)
    |> render("index.json", %{activities: activities, for: user})
lain's avatar
lain committed
80
81
  end

lain's avatar
lain committed
82
  def friends_timeline(%{assigns: %{user: user}} = conn, params) do
lain's avatar
lain committed
83
84
85
86
87
88
    params =
      params
      |> Map.put("type", ["Create", "Announce", "Follow", "Like"])
      |> Map.put("blocking_user", user)
      |> Map.put("user", user)

89
90
91
    activities =
      ActivityPub.fetch_activities([user.ap_id | user.following], params)
      |> ActivityPub.contain_timeline(user)
lain's avatar
lain committed
92
93

    conn
href's avatar
href committed
94
95
    |> put_view(ActivityView)
    |> render("index.json", %{activities: activities, for: user})
lain's avatar
lain committed
96
97
  end

eal's avatar
eal committed
98
  def show_user(conn, params) do
99
100
101
    for_user = conn.assigns.user

    with {:ok, shown} <- TwitterAPI.get_user(params),
Ivan Tashkinov's avatar
Ivan Tashkinov committed
102
103
104
         true <-
           User.auth_active?(shown) ||
             (for_user && (for_user.id == shown.id || User.superuser?(for_user))) do
href's avatar
href committed
105
      params =
106
107
        if for_user do
          %{user: shown, for: for_user}
href's avatar
href committed
108
109
110
111
112
113
114
        else
          %{user: shown}
        end

      conn
      |> put_view(UserView)
      |> render("show.json", params)
eal's avatar
eal committed
115
116
117
    else
      {:error, msg} ->
        bad_request_reply(conn, msg)
118
119
120
121
122

      false ->
        conn
        |> put_status(404)
        |> json(%{error: "Unconfirmed user"})
eal's avatar
eal committed
123
124
125
    end
  end

dtluna's avatar
dtluna committed
126
  def user_timeline(%{assigns: %{user: user}} = conn, params) do
127
128
    case TwitterAPI.get_user(user, params) do
      {:ok, target_user} ->
129
        activities = ActivityPub.fetch_user_activities(target_user, user, params)
lain's avatar
lain committed
130

131
        conn
href's avatar
href committed
132
133
        |> put_view(ActivityView)
        |> render("index.json", %{activities: activities, for: user})
lain's avatar
lain committed
134

135
136
137
      {:error, msg} ->
        bad_request_reply(conn, msg)
    end
dtluna's avatar
dtluna committed
138
139
  end

dtluna's avatar
dtluna committed
140
  def mentions_timeline(%{assigns: %{user: user}} = conn, params) do
141
142
143
144
145
    params =
      params
      |> Map.put("type", ["Create", "Announce", "Follow", "Like"])
      |> Map.put("blocking_user", user)

lain's avatar
lain committed
146
    activities = ActivityPub.fetch_activities([user.ap_id], params)
dtluna's avatar
dtluna committed
147
148

    conn
href's avatar
href committed
149
150
    |> put_view(ActivityView)
    |> render("index.json", %{activities: activities, for: user})
lain's avatar
lain committed
151
152
153
154
155
156
  end

  def dm_timeline(%{assigns: %{user: user}} = conn, params) do
    query =
      ActivityPub.fetch_activities_query(
        [user.ap_id],
157
        Map.merge(params, %{"type" => "Create", "user" => user, visibility: "direct"})
lain's avatar
lain committed
158
159
160
161
162
      )

    activities = Repo.all(query)

    conn
href's avatar
href committed
163
164
    |> put_view(ActivityView)
    |> render("index.json", %{activities: activities, for: user})
dtluna's avatar
dtluna committed
165
166
  end

167
168
169
170
  def notifications(%{assigns: %{user: user}} = conn, params) do
    notifications = Notification.for_user(user, params)

    conn
href's avatar
href committed
171
172
    |> put_view(NotificationView)
    |> render("notification.json", %{notifications: notifications, for: user})
173
174
  end

175
176
177
178
179
180
  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
href's avatar
href committed
181
182
    |> put_view(NotificationView)
    |> render("notification.json", %{notifications: notifications, for: user})
183
184
  end

Maksim's avatar
Maksim committed
185
  def notifications_read(%{assigns: %{user: _user}} = conn, _) do
186
187
188
    bad_request_reply(conn, "You need to specify latest_id")
  end

189
190
  def follow(%{assigns: %{user: user}} = conn, params) do
    case TwitterAPI.follow(user, params) do
191
      {:ok, user, followed, _activity} ->
href's avatar
href committed
192
193
194
        conn
        |> put_view(UserView)
        |> render("show.json", %{user: followed, for: user})
lain's avatar
lain committed
195
196
197

      {:error, msg} ->
        forbidden_json_reply(conn, msg)
198
    end
lain's avatar
lain committed
199
200
  end

eal's avatar
eal committed
201
202
203
  def block(%{assigns: %{user: user}} = conn, params) do
    case TwitterAPI.block(user, params) do
      {:ok, user, blocked} ->
href's avatar
href committed
204
205
206
        conn
        |> put_view(UserView)
        |> render("show.json", %{user: blocked, for: user})
lain's avatar
lain committed
207
208
209

      {:error, msg} ->
        forbidden_json_reply(conn, msg)
eal's avatar
eal committed
210
211
212
213
214
215
    end
  end

  def unblock(%{assigns: %{user: user}} = conn, params) do
    case TwitterAPI.unblock(user, params) do
      {:ok, user, blocked} ->
href's avatar
href committed
216
217
218
        conn
        |> put_view(UserView)
        |> render("show.json", %{user: blocked, for: user})
lain's avatar
lain committed
219
220
221

      {:error, msg} ->
        forbidden_json_reply(conn, msg)
eal's avatar
eal committed
222
223
224
    end
  end

lain's avatar
lain committed
225
  def delete_post(%{assigns: %{user: user}} = conn, %{"id" => id}) do
normandy's avatar
normandy committed
226
    with {:ok, activity} <- TwitterAPI.delete(user, id) do
href's avatar
href committed
227
228
229
      conn
      |> put_view(ActivityView)
      |> render("activity.json", %{activity: activity, for: user})
lain's avatar
lain committed
230
231
232
    end
  end

233
  def unfollow(%{assigns: %{user: user}} = conn, params) do
234
    case TwitterAPI.unfollow(user, params) do
235
      {:ok, user, unfollowed} ->
href's avatar
href committed
236
237
238
        conn
        |> put_view(UserView)
        |> render("show.json", %{user: unfollowed, for: user})
lain's avatar
lain committed
239
240
241

      {:error, msg} ->
        forbidden_json_reply(conn, msg)
242
    end
lain's avatar
lain committed
243
244
  end

245
  def fetch_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
lain's avatar
lain committed
246
247
    with %Activity{} = activity <- Repo.get(Activity, id),
         true <- ActivityPub.visible_for_user?(activity, user) do
href's avatar
href committed
248
249
250
      conn
      |> put_view(ActivityView)
      |> render("activity.json", %{activity: activity, for: user})
lain's avatar
lain committed
251
    end
lain's avatar
lain committed
252
253
  end

254
  def fetch_conversation(%{assigns: %{user: user}} = conn, %{"id" => id}) do
255
256
    id = String.to_integer(id)

lain's avatar
lain committed
257
258
259
260
261
262
263
    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
href's avatar
href committed
264
265
      |> put_view(ActivityView)
      |> render("index.json", %{activities: activities, for: user})
lain's avatar
lain committed
266
    end
267
268
  end

Ivan Tashkinov's avatar
Ivan Tashkinov committed
269
270
271
272
  @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).
  """
273
274
  def update_media(%{assigns: %{user: user}} = conn, %{"media_id" => id} = data) do
    object = Repo.get(Object, id)
275
276
    description = get_in(data, ["alt_text", "text"]) || data["name"] || data["description"]

277
278
279
280
    {conn, status, response_body} =
      cond do
        !object ->
          {halt(conn), :not_found, ""}
Ivan Tashkinov's avatar
Ivan Tashkinov committed
281

282
        !Object.authorize_mutation(object, user) ->
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
          {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
298
299

    conn
300
301
    |> put_status(status)
    |> json(response_body)
302
303
  end

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

lain's avatar
lain committed
307
308
309
310
    conn
    |> put_resp_content_type("application/atom+xml")
    |> send_resp(200, response)
  end
311

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

315
316
317
318
    conn
    |> json_reply(200, response)
  end

lain's avatar
lain committed
319
  def get_by_id_or_ap_id(id) do
320
    activity = Repo.get(Activity, id) || Activity.get_create_activity_by_object_ap_id(id)
lain's avatar
lain committed
321

322
323
324
325
326
    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
327
328
  end

lain's avatar
lain committed
329
  def favorite(%{assigns: %{user: user}} = conn, %{"id" => id}) do
330
331
    with {_, {:ok, id}} <- {:param_cast, Ecto.Type.cast(:integer, id)},
         {:ok, activity} <- TwitterAPI.fav(user, id) do
href's avatar
href committed
332
333
334
      conn
      |> put_view(ActivityView)
      |> render("activity.json", %{activity: activity, for: user})
lain's avatar
lain committed
335
    end
lain's avatar
lain committed
336
337
  end

lain's avatar
lain committed
338
  def unfavorite(%{assigns: %{user: user}} = conn, %{"id" => id}) do
339
340
    with {_, {:ok, id}} <- {:param_cast, Ecto.Type.cast(:integer, id)},
         {:ok, activity} <- TwitterAPI.unfav(user, id) do
href's avatar
href committed
341
342
343
      conn
      |> put_view(ActivityView)
      |> render("activity.json", %{activity: activity, for: user})
lain's avatar
lain committed
344
    end
lain's avatar
lain committed
345
346
  end

lain's avatar
lain committed
347
  def retweet(%{assigns: %{user: user}} = conn, %{"id" => id}) do
348
349
    with {_, {:ok, id}} <- {:param_cast, Ecto.Type.cast(:integer, id)},
         {:ok, activity} <- TwitterAPI.repeat(user, id) do
href's avatar
href committed
350
351
352
      conn
      |> put_view(ActivityView)
      |> render("activity.json", %{activity: activity, for: user})
dtluna's avatar
dtluna committed
353
    end
lain's avatar
lain committed
354
355
  end

356
357
358
  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
href's avatar
href committed
359
360
361
      conn
      |> put_view(ActivityView)
      |> render("activity.json", %{activity: activity, for: user})
362
363
364
    end
  end

365
366
  def register(conn, params) do
    with {:ok, user} <- TwitterAPI.register_user(params) do
href's avatar
href committed
367
368
369
      conn
      |> put_view(UserView)
      |> render("show.json", %{user: user})
370
371
    else
      {:error, errors} ->
lain's avatar
lain committed
372
373
        conn
        |> json_reply(400, Jason.encode!(errors))
374
375
376
    end
  end

377
378
379
  def password_reset(conn, params) do
    nickname_or_email = params["email"] || params["nickname"]

380
    with {:ok, _} <- TwitterAPI.password_reset(nickname_or_email) do
381
382
383
384
      json_response(conn, :no_content, "")
    end
  end

385
386
  def confirm_email(conn, %{"user_id" => uid, "token" => token}) do
    with %User{} = user <- Repo.get(User, uid),
387
         true <- user.local,
388
389
         true <- user.info.confirmation_pending,
         true <- user.info.confirmation_token == token,
390
         info_change <- User.Info.confirmation_changeset(user.info, :confirmed),
391
392
393
394
395
396
397
         changeset <- Changeset.change(user) |> Changeset.put_embed(:info, info_change),
         {:ok, _} <- User.update_and_set_cache(changeset) do
      conn
      |> redirect(to: "/")
    end
  end

398
399
400
401
402
403
404
405
406
407
  def resend_confirmation_email(conn, params) do
    nickname_or_email = params["email"] || params["nickname"]

    with %User{} = user <- User.get_by_nickname_or_email(nickname_or_email),
         {:ok, _} <- User.try_send_confirmation_email(user) do
      conn
      |> json_response(:no_content, "")
    end
  end

lain's avatar
lain committed
408
  def update_avatar(%{assigns: %{user: user}} = conn, params) do
href's avatar
href committed
409
    {:ok, object} = ActivityPub.upload(params, type: :avatar)
410
    change = Changeset.change(user, %{avatar: object.data})
lain's avatar
lain committed
411
    {:ok, user} = User.update_and_set_cache(change)
lain's avatar
lain committed
412
    CommonAPI.update(user)
lain's avatar
lain committed
413

href's avatar
href committed
414
415
416
    conn
    |> put_view(UserView)
    |> render("show.json", %{user: user, for: user})
lain's avatar
lain committed
417
418
  end

lain's avatar
lain committed
419
  def update_banner(%{assigns: %{user: user}} = conn, params) do
href's avatar
href committed
420
    with {:ok, object} <- ActivityPub.upload(%{"img" => params["banner"]}, type: :banner),
421
422
423
424
         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
425
      CommonAPI.update(user)
lain's avatar
lain committed
426
427
428
      %{"url" => [%{"href" => href} | _]} = object.data
      response = %{url: href} |> Jason.encode!()

lain's avatar
lain committed
429
430
431
432
433
434
      conn
      |> json_reply(200, response)
    end
  end

  def update_background(%{assigns: %{user: user}} = conn, params) do
href's avatar
href committed
435
    with {:ok, object} <- ActivityPub.upload(params, type: :background),
436
437
438
439
         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
440
441
442
      %{"url" => [%{"href" => href} | _]} = object.data
      response = %{url: href} |> Jason.encode!()

lain's avatar
lain committed
443
444
445
446
447
      conn
      |> json_reply(200, response)
    end
  end

lain's avatar
lain committed
448
449
  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
450
         response <- Jason.encode!(user_map) do
lain's avatar
lain committed
451
452
      conn
      |> json_reply(200, response)
lain's avatar
lain committed
453
454
455
456
457
    else
      _e ->
        conn
        |> put_status(404)
        |> json(%{error: "Can't find user"})
lain's avatar
lain committed
458
459
460
    end
  end

461
462
  def followers(%{assigns: %{user: for_user}} = conn, params) do
    with {:ok, user} <- TwitterAPI.get_user(for_user, params),
eal's avatar
eal committed
463
         {:ok, followers} <- User.get_followers(user) do
464
465
466
467
468
469
470
      followers =
        cond do
          for_user && user.id == for_user.id -> followers
          user.info.hide_network -> []
          true -> followers
        end

href's avatar
href committed
471
472
473
      conn
      |> put_view(UserView)
      |> render("index.json", %{users: followers, for: conn.assigns[:user]})
lain's avatar
lain committed
474
475
476
477
478
    else
      _e -> bad_request_reply(conn, "Can't get followers")
    end
  end

479
  def friends(%{assigns: %{user: for_user}} = conn, params) do
480
    with {:ok, user} <- TwitterAPI.get_user(conn.assigns[:user], params),
eal's avatar
eal committed
481
         {:ok, friends} <- User.get_friends(user) do
482
483
484
485
486
487
488
      friends =
        cond do
          for_user && user.id == for_user.id -> friends
          user.info.hide_network -> []
          true -> friends
        end

href's avatar
href committed
489
490
491
      conn
      |> put_view(UserView)
      |> render("index.json", %{users: friends, for: conn.assigns[:user]})
lain's avatar
lain committed
492
493
494
495
496
    else
      _e -> bad_request_reply(conn, "Can't get friends")
    end
  end

497
  def friend_requests(conn, params) do
498
    with {:ok, user} <- TwitterAPI.get_user(conn.assigns[:user], params),
499
         {:ok, friend_requests} <- User.get_follow_requests(user) do
href's avatar
href committed
500
501
502
      conn
      |> put_view(UserView)
      |> render("index.json", %{users: friend_requests, for: conn.assigns[:user]})
503
504
505
506
507
    else
      _e -> bad_request_reply(conn, "Can't get friend requests")
    end
  end

Maksim's avatar
Maksim committed
508
  def approve_friend_request(conn, %{"user_id" => uid} = _params) do
509
510
511
512
513
514
515
516
517
518
519
520
521
    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
href's avatar
href committed
522
523
524
      conn
      |> put_view(UserView)
      |> render("show.json", %{user: follower, for: followed})
525
526
527
528
529
    else
      e -> bad_request_reply(conn, "Can't approve user: #{inspect(e)}")
    end
  end

Maksim's avatar
Maksim committed
530
  def deny_friend_request(conn, %{"user_id" => uid} = _params) do
531
532
533
534
535
536
537
538
539
540
541
542
    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
href's avatar
href committed
543
544
545
      conn
      |> put_view(UserView)
      |> render("show.json", %{user: follower, for: followed})
546
547
548
549
550
    else
      e -> bad_request_reply(conn, "Can't deny user: #{inspect(e)}")
    end
  end

eal's avatar
eal committed
551
552
  def friends_ids(%{assigns: %{user: user}} = conn, _params) do
    with {:ok, friends} <- User.get_friends(user) do
lain's avatar
lain committed
553
554
555
556
      ids =
        friends
        |> Enum.map(fn x -> x.id end)
        |> Jason.encode!()
557

eal's avatar
eal committed
558
559
560
561
562
563
      json(conn, ids)
    else
      _e -> bad_request_reply(conn, "Can't get friends")
    end
  end

564
  def empty_array(conn, _params) do
lain's avatar
lain committed
565
    json(conn, Jason.encode!([]))
566
  end
eal's avatar
eal committed
567

568
569
570
571
  def raw_empty_array(conn, _params) do
    json(conn, [])
  end

lain's avatar
lain committed
572
573
  defp build_info_cng(user, params) do
    info_params =
lain's avatar
lain committed
574
      ["no_rich_text", "locked", "hide_network"]
lain's avatar
lain committed
575
576
577
      |> Enum.reduce(%{}, fn key, res ->
        if value = params[key] do
          Map.put(res, key, value == "true")
578
        else
lain's avatar
lain committed
579
          res
580
        end
lain's avatar
lain committed
581
      end)
582

lain's avatar
lain committed
583
584
585
    info_params =
      if value = params["default_scope"] do
        Map.put(info_params, "default_scope", value)
586
      else
lain's avatar
lain committed
587
        info_params
588
589
      end

lain's avatar
lain committed
590
591
592
    User.Info.profile_update(user.info, info_params)
  end

Maxim Filippov's avatar
Maxim Filippov committed
593
  defp parse_profile_bio(user, params) do
lain's avatar
lain committed
594
    if bio = params["description"] do
Maxim Filippov's avatar
Maxim Filippov committed
595
      Map.put(params, "bio", User.parse_bio(bio, user))
lain's avatar
lain committed
596
597
598
599
600
601
    else
      params
    end
  end

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

lain's avatar
lain committed
605
    with changeset <- User.update_changeset(user, params),
lain's avatar
lain committed
606
         changeset <- Ecto.Changeset.put_embed(changeset, :info, info_cng),
lain's avatar
lain committed
607
         {:ok, user} <- User.update_and_set_cache(changeset) do
lain's avatar
lain committed
608
      CommonAPI.update(user)
href's avatar
href committed
609
610
611
612

      conn
      |> put_view(UserView)
      |> render("user.json", %{user: user, for: user})
lain's avatar
lain committed
613
614
615
616
617
618
619
    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
620
  def search(%{assigns: %{user: user}} = conn, %{"q" => _query} = params) do
lain's avatar
lain committed
621
622
    activities = TwitterAPI.search(user, params)

lain's avatar
lain committed
623
    conn
href's avatar
href committed
624
625
    |> put_view(ActivityView)
    |> render("index.json", %{activities: activities, for: user})
lain's avatar
lain committed
626
627
  end

628
629
630
631
  def search_user(%{assigns: %{user: user}} = conn, %{"query" => query}) do
    users = User.search(query, true)

    conn
href's avatar
href committed
632
633
    |> put_view(UserView)
    |> render("index.json", %{users: users, for: user})
634
635
  end

636
  defp bad_request_reply(conn, error_message) do
dtluna's avatar
dtluna committed
637
    json = error_json(conn, error_message)
638
639
640
    json_reply(conn, 400, json)
  end

641
642
643
644
645
  defp json_reply(conn, status, json) do
    conn
    |> put_resp_content_type("application/json")
    |> send_resp(status, json)
  end
646
647

  defp forbidden_json_reply(conn, error_message) do
dtluna's avatar
dtluna committed
648
    json = error_json(conn, error_message)
649
650
    json_reply(conn, 403, json)
  end
dtluna's avatar
dtluna committed
651

href's avatar
href committed
652
653
654
655
656
657
658
659
  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
660
      |> halt()
href's avatar
href committed
661
662
663
    end
  end

dtluna's avatar
dtluna committed
664
  defp error_json(conn, error_message) do
lain's avatar
lain committed
665
    %{"error" => error_message, "request" => conn.request_path} |> Jason.encode!()
dtluna's avatar
dtluna committed
666
  end
667
668
669
670
671
672
673
674
675
676
677
678

  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
679
end