twitter_api_controller.ex 19.7 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
99
  def show_user(conn, params) do
    with {:ok, shown} <- TwitterAPI.get_user(params) do
href's avatar
href committed
100
101
102
103
104
105
106
107
108
109
      params =
        if user = conn.assigns.user do
          %{user: shown, for: user}
        else
          %{user: shown}
        end

      conn
      |> put_view(UserView)
      |> render("show.json", params)
eal's avatar
eal committed
110
111
112
113
114
115
    else
      {:error, msg} ->
        bad_request_reply(conn, msg)
    end
  end

dtluna's avatar
dtluna committed
116
  def user_timeline(%{assigns: %{user: user}} = conn, params) do
117
118
    case TwitterAPI.get_user(user, params) do
      {:ok, target_user} ->
119
        activities = ActivityPub.fetch_user_activities(target_user, user, params)
lain's avatar
lain committed
120

121
        conn
href's avatar
href committed
122
123
        |> put_view(ActivityView)
        |> render("index.json", %{activities: activities, for: user})
lain's avatar
lain committed
124

125
126
127
      {:error, msg} ->
        bad_request_reply(conn, msg)
    end
dtluna's avatar
dtluna committed
128
129
  end

dtluna's avatar
dtluna committed
130
  def mentions_timeline(%{assigns: %{user: user}} = conn, params) do
131
132
133
134
135
    params =
      params
      |> Map.put("type", ["Create", "Announce", "Follow", "Like"])
      |> Map.put("blocking_user", user)

lain's avatar
lain committed
136
    activities = ActivityPub.fetch_activities([user.ap_id], params)
dtluna's avatar
dtluna committed
137
138

    conn
href's avatar
href committed
139
140
    |> put_view(ActivityView)
    |> render("index.json", %{activities: activities, for: user})
lain's avatar
lain committed
141
142
143
144
145
146
  end

  def dm_timeline(%{assigns: %{user: user}} = conn, params) do
    query =
      ActivityPub.fetch_activities_query(
        [user.ap_id],
147
        Map.merge(params, %{"type" => "Create", "user" => user, visibility: "direct"})
lain's avatar
lain committed
148
149
150
151
152
      )

    activities = Repo.all(query)

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

157
158
159
160
  def notifications(%{assigns: %{user: user}} = conn, params) do
    notifications = Notification.for_user(user, params)

    conn
href's avatar
href committed
161
162
    |> put_view(NotificationView)
    |> render("notification.json", %{notifications: notifications, for: user})
163
164
  end

165
166
167
168
169
170
  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
171
172
    |> put_view(NotificationView)
    |> render("notification.json", %{notifications: notifications, for: user})
173
174
  end

Maksim's avatar
Maksim committed
175
  def notifications_read(%{assigns: %{user: _user}} = conn, _) do
176
177
178
    bad_request_reply(conn, "You need to specify latest_id")
  end

179
180
  def follow(%{assigns: %{user: user}} = conn, params) do
    case TwitterAPI.follow(user, params) do
181
      {:ok, user, followed, _activity} ->
href's avatar
href committed
182
183
184
        conn
        |> put_view(UserView)
        |> render("show.json", %{user: followed, for: user})
lain's avatar
lain committed
185
186
187

      {:error, msg} ->
        forbidden_json_reply(conn, msg)
188
    end
lain's avatar
lain committed
189
190
  end

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

      {:error, msg} ->
        forbidden_json_reply(conn, msg)
eal's avatar
eal committed
200
201
202
203
204
205
    end
  end

  def unblock(%{assigns: %{user: user}} = conn, params) do
    case TwitterAPI.unblock(user, params) do
      {:ok, user, blocked} ->
href's avatar
href committed
206
207
208
        conn
        |> put_view(UserView)
        |> render("show.json", %{user: blocked, for: user})
lain's avatar
lain committed
209
210
211

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

lain's avatar
lain committed
215
  def delete_post(%{assigns: %{user: user}} = conn, %{"id" => id}) do
normandy's avatar
normandy committed
216
    with {:ok, activity} <- TwitterAPI.delete(user, id) do
href's avatar
href committed
217
218
219
      conn
      |> put_view(ActivityView)
      |> render("activity.json", %{activity: activity, for: user})
lain's avatar
lain committed
220
221
222
    end
  end

223
  def unfollow(%{assigns: %{user: user}} = conn, params) do
224
    case TwitterAPI.unfollow(user, params) do
225
      {:ok, user, unfollowed} ->
href's avatar
href committed
226
227
228
        conn
        |> put_view(UserView)
        |> render("show.json", %{user: unfollowed, for: user})
lain's avatar
lain committed
229
230
231

      {:error, msg} ->
        forbidden_json_reply(conn, msg)
232
    end
lain's avatar
lain committed
233
234
  end

235
  def fetch_status(%{assigns: %{user: user}} = conn, %{"id" => id}) do
lain's avatar
lain committed
236
237
    with %Activity{} = activity <- Repo.get(Activity, id),
         true <- ActivityPub.visible_for_user?(activity, user) do
href's avatar
href committed
238
239
240
      conn
      |> put_view(ActivityView)
      |> render("activity.json", %{activity: activity, for: user})
lain's avatar
lain committed
241
    end
lain's avatar
lain committed
242
243
  end

244
  def fetch_conversation(%{assigns: %{user: user}} = conn, %{"id" => id}) do
245
246
    id = String.to_integer(id)

lain's avatar
lain committed
247
248
249
250
251
252
253
    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
254
255
      |> put_view(ActivityView)
      |> render("index.json", %{activities: activities, for: user})
lain's avatar
lain committed
256
    end
257
258
  end

Ivan Tashkinov's avatar
Ivan Tashkinov committed
259
260
261
262
  @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).
  """
263
264
  def update_media(%{assigns: %{user: user}} = conn, %{"media_id" => id} = data) do
    object = Repo.get(Object, id)
265
266
    description = get_in(data, ["alt_text", "text"]) || data["name"] || data["description"]

267
268
269
270
    {conn, status, response_body} =
      cond do
        !object ->
          {halt(conn), :not_found, ""}
Ivan Tashkinov's avatar
Ivan Tashkinov committed
271

272
        !Object.authorize_mutation(object, user) ->
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
          {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
288
289

    conn
290
291
    |> put_status(status)
    |> json(response_body)
292
293
  end

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

lain's avatar
lain committed
297
298
299
300
    conn
    |> put_resp_content_type("application/atom+xml")
    |> send_resp(200, response)
  end
301

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

305
306
307
308
    conn
    |> json_reply(200, response)
  end

lain's avatar
lain committed
309
  def get_by_id_or_ap_id(id) do
310
    activity = Repo.get(Activity, id) || Activity.get_create_activity_by_object_ap_id(id)
lain's avatar
lain committed
311

312
313
314
315
316
    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
317
318
  end

lain's avatar
lain committed
319
  def favorite(%{assigns: %{user: user}} = conn, %{"id" => id}) do
320
321
    with {_, {:ok, id}} <- {:param_cast, Ecto.Type.cast(:integer, id)},
         {:ok, activity} <- TwitterAPI.fav(user, id) do
href's avatar
href committed
322
323
324
      conn
      |> put_view(ActivityView)
      |> render("activity.json", %{activity: activity, for: user})
lain's avatar
lain committed
325
    end
lain's avatar
lain committed
326
327
  end

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

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

346
347
348
  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
349
350
351
      conn
      |> put_view(ActivityView)
      |> render("activity.json", %{activity: activity, for: user})
352
353
354
    end
  end

355
356
  def register(conn, params) do
    with {:ok, user} <- TwitterAPI.register_user(params) do
href's avatar
href committed
357
358
359
      conn
      |> put_view(UserView)
      |> render("show.json", %{user: user})
360
361
    else
      {:error, errors} ->
lain's avatar
lain committed
362
363
        conn
        |> json_reply(400, Jason.encode!(errors))
364
365
366
    end
  end

367
368
369
  def password_reset(conn, params) do
    nickname_or_email = params["email"] || params["nickname"]

370
    with {:ok, _} <- TwitterAPI.password_reset(nickname_or_email) do
371
372
373
374
      json_response(conn, :no_content, "")
    end
  end

375
376
377
378
379
380
381
382
383
384
385
386
387
  def confirm_email(conn, %{"token" => token}) do
    with %User{} = user <- User.get_by_confirmation_token(token),
         true <- user.local,
         new_info_fields <- %{confirmation_pending: false, confirmation_token: nil},
         info_change <- User.Info.confirmation_update(user.info, new_info_fields),
         changeset <- Changeset.change(user) |> Changeset.put_embed(:info, info_change),
         {:ok, _} <- User.update_and_set_cache(changeset) do
      conn
      |> put_flash(:info, "Email confirmed. Please sign in.")
      |> redirect(to: "/")
    end
  end

lain's avatar
lain committed
388
  def update_avatar(%{assigns: %{user: user}} = conn, params) do
href's avatar
href committed
389
    {:ok, object} = ActivityPub.upload(params, type: :avatar)
390
    change = Changeset.change(user, %{avatar: object.data})
lain's avatar
lain committed
391
    {:ok, user} = User.update_and_set_cache(change)
lain's avatar
lain committed
392
    CommonAPI.update(user)
lain's avatar
lain committed
393

href's avatar
href committed
394
395
396
    conn
    |> put_view(UserView)
    |> render("show.json", %{user: user, for: user})
lain's avatar
lain committed
397
398
  end

lain's avatar
lain committed
399
  def update_banner(%{assigns: %{user: user}} = conn, params) do
href's avatar
href committed
400
    with {:ok, object} <- ActivityPub.upload(%{"img" => params["banner"]}, type: :banner),
401
402
403
404
         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
405
      CommonAPI.update(user)
lain's avatar
lain committed
406
407
408
      %{"url" => [%{"href" => href} | _]} = object.data
      response = %{url: href} |> Jason.encode!()

lain's avatar
lain committed
409
410
411
412
413
414
      conn
      |> json_reply(200, response)
    end
  end

  def update_background(%{assigns: %{user: user}} = conn, params) do
href's avatar
href committed
415
    with {:ok, object} <- ActivityPub.upload(params, type: :background),
416
417
418
419
         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
420
421
422
      %{"url" => [%{"href" => href} | _]} = object.data
      response = %{url: href} |> Jason.encode!()

lain's avatar
lain committed
423
424
425
426
427
      conn
      |> json_reply(200, response)
    end
  end

lain's avatar
lain committed
428
429
  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
430
         response <- Jason.encode!(user_map) do
lain's avatar
lain committed
431
432
      conn
      |> json_reply(200, response)
lain's avatar
lain committed
433
434
435
436
437
    else
      _e ->
        conn
        |> put_status(404)
        |> json(%{error: "Can't find user"})
lain's avatar
lain committed
438
439
440
    end
  end

441
442
  def followers(%{assigns: %{user: for_user}} = conn, params) do
    with {:ok, user} <- TwitterAPI.get_user(for_user, params),
eal's avatar
eal committed
443
         {:ok, followers} <- User.get_followers(user) do
444
445
446
447
448
449
450
      followers =
        cond do
          for_user && user.id == for_user.id -> followers
          user.info.hide_network -> []
          true -> followers
        end

href's avatar
href committed
451
452
453
      conn
      |> put_view(UserView)
      |> render("index.json", %{users: followers, for: conn.assigns[:user]})
lain's avatar
lain committed
454
455
456
457
458
    else
      _e -> bad_request_reply(conn, "Can't get followers")
    end
  end

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

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

477
  def friend_requests(conn, params) do
478
    with {:ok, user} <- TwitterAPI.get_user(conn.assigns[:user], params),
479
         {:ok, friend_requests} <- User.get_follow_requests(user) do
href's avatar
href committed
480
481
482
      conn
      |> put_view(UserView)
      |> render("index.json", %{users: friend_requests, for: conn.assigns[:user]})
483
484
485
486
487
    else
      _e -> bad_request_reply(conn, "Can't get friend requests")
    end
  end

Maksim's avatar
Maksim committed
488
  def approve_friend_request(conn, %{"user_id" => uid} = _params) do
489
490
491
492
493
494
495
496
497
498
499
500
501
    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
502
503
504
      conn
      |> put_view(UserView)
      |> render("show.json", %{user: follower, for: followed})
505
506
507
508
509
    else
      e -> bad_request_reply(conn, "Can't approve user: #{inspect(e)}")
    end
  end

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

eal's avatar
eal committed
531
532
  def friends_ids(%{assigns: %{user: user}} = conn, _params) do
    with {:ok, friends} <- User.get_friends(user) do
lain's avatar
lain committed
533
534
535
536
      ids =
        friends
        |> Enum.map(fn x -> x.id end)
        |> Jason.encode!()
537

eal's avatar
eal committed
538
539
540
541
542
543
      json(conn, ids)
    else
      _e -> bad_request_reply(conn, "Can't get friends")
    end
  end

544
  def empty_array(conn, _params) do
lain's avatar
lain committed
545
    json(conn, Jason.encode!([]))
546
  end
eal's avatar
eal committed
547

548
549
550
551
  def raw_empty_array(conn, _params) do
    json(conn, [])
  end

lain's avatar
lain committed
552
553
  defp build_info_cng(user, params) do
    info_params =
lain's avatar
lain committed
554
      ["no_rich_text", "locked", "hide_network"]
lain's avatar
lain committed
555
556
557
      |> Enum.reduce(%{}, fn key, res ->
        if value = params[key] do
          Map.put(res, key, value == "true")
558
        else
lain's avatar
lain committed
559
          res
560
        end
lain's avatar
lain committed
561
      end)
562

lain's avatar
lain committed
563
564
565
    info_params =
      if value = params["default_scope"] do
        Map.put(info_params, "default_scope", value)
566
      else
lain's avatar
lain committed
567
        info_params
568
569
      end

lain's avatar
lain committed
570
571
572
    User.Info.profile_update(user.info, info_params)
  end

Maxim Filippov's avatar
Maxim Filippov committed
573
  defp parse_profile_bio(user, params) do
lain's avatar
lain committed
574
    if bio = params["description"] do
Maxim Filippov's avatar
Maxim Filippov committed
575
      Map.put(params, "bio", User.parse_bio(bio, user))
lain's avatar
lain committed
576
577
578
579
580
581
    else
      params
    end
  end

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

lain's avatar
lain committed
585
    with changeset <- User.update_changeset(user, params),
lain's avatar
lain committed
586
         changeset <- Ecto.Changeset.put_embed(changeset, :info, info_cng),
lain's avatar
lain committed
587
         {:ok, user} <- User.update_and_set_cache(changeset) do
lain's avatar
lain committed
588
      CommonAPI.update(user)
href's avatar
href committed
589
590
591
592

      conn
      |> put_view(UserView)
      |> render("user.json", %{user: user, for: user})
lain's avatar
lain committed
593
594
595
596
597
598
599
    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
600
  def search(%{assigns: %{user: user}} = conn, %{"q" => _query} = params) do
lain's avatar
lain committed
601
602
    activities = TwitterAPI.search(user, params)

lain's avatar
lain committed
603
    conn
href's avatar
href committed
604
605
    |> put_view(ActivityView)
    |> render("index.json", %{activities: activities, for: user})
lain's avatar
lain committed
606
607
  end

608
609
610
611
  def search_user(%{assigns: %{user: user}} = conn, %{"query" => query}) do
    users = User.search(query, true)

    conn
href's avatar
href committed
612
613
    |> put_view(UserView)
    |> render("index.json", %{users: users, for: user})
614
615
  end

616
  defp bad_request_reply(conn, error_message) do
dtluna's avatar
dtluna committed
617
    json = error_json(conn, error_message)
618
619
620
    json_reply(conn, 400, json)
  end

621
622
623
624
625
  defp json_reply(conn, status, json) do
    conn
    |> put_resp_content_type("application/json")
    |> send_resp(status, json)
  end
626
627

  defp forbidden_json_reply(conn, error_message) do
dtluna's avatar
dtluna committed
628
    json = error_json(conn, error_message)
629
630
    json_reply(conn, 403, json)
  end
dtluna's avatar
dtluna committed
631

href's avatar
href committed
632
633
634
635
636
637
638
639
  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
640
      |> halt()
href's avatar
href committed
641
642
643
    end
  end

dtluna's avatar
dtluna committed
644
  defp error_json(conn, error_message) do
lain's avatar
lain committed
645
    %{"error" => error_message, "request" => conn.request_path} |> Jason.encode!()
dtluna's avatar
dtluna committed
646
  end
647
648
649
650
651
652
653
654
655
656
657
658

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