common_api.ex 14.8 KB
Newer Older
1
# Pleroma: A lightweight social networking server
kaniini's avatar
kaniini committed
2
# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3
4
# SPDX-License-Identifier: AGPL-3.0-only

lain's avatar
lain committed
5
defmodule Pleroma.Web.CommonAPI do
Haelwenn's avatar
Haelwenn committed
6
  alias Pleroma.Activity
7
  alias Pleroma.Formatter
Haelwenn's avatar
Haelwenn committed
8
  alias Pleroma.Object
9
  alias Pleroma.ThreadMute
10
  alias Pleroma.User
lain's avatar
lain committed
11
  alias Pleroma.Web.ActivityPub.ActivityPub
12
  alias Pleroma.Web.ActivityPub.Utils
13
  alias Pleroma.Web.ActivityPub.Visibility
14

15
  import Pleroma.Web.Gettext
16
  import Pleroma.Web.CommonAPI.Utils
lain's avatar
lain committed
17

18
19
20
21
22
23
24
25
26
27
28
29
30
  def follow(follower, followed) do
    with {:ok, follower} <- User.maybe_direct_follow(follower, followed),
         {:ok, activity} <- ActivityPub.follow(follower, followed),
         {:ok, follower, followed} <-
           User.wait_and_refresh(
             Pleroma.Config.get([:activitypub, :follow_handshake_timeout]),
             follower,
             followed
           ) do
      {:ok, follower, followed, activity}
    end
  end

31
32
  def unfollow(follower, unfollowed) do
    with {:ok, follower, _follow_activity} <- User.unfollow(follower, unfollowed),
33
34
         {:ok, _activity} <- ActivityPub.unfollow(follower, unfollowed),
         {:ok, _unfollowed} <- User.unsubscribe(follower, unfollowed) do
35
36
37
38
39
      {:ok, follower}
    end
  end

  def accept_follow_request(follower, followed) do
40
    with {:ok, follower} <- User.follow(follower, followed),
41
         %Activity{} = follow_activity <- Utils.fetch_latest_follow(follower, followed),
42
         {:ok, follow_activity} <- Utils.update_follow_state_for_all(follow_activity, "accept"),
43
44
45
46
47
48
49
50
51
52
53
54
55
         {:ok, _activity} <-
           ActivityPub.accept(%{
             to: [follower.ap_id],
             actor: followed,
             object: follow_activity.data["id"],
             type: "Accept"
           }) do
      {:ok, follower}
    end
  end

  def reject_follow_request(follower, followed) do
    with %Activity{} = follow_activity <- Utils.fetch_latest_follow(follower, followed),
56
         {:ok, follow_activity} <- Utils.update_follow_state_for_all(follow_activity, "reject"),
57
58
59
60
61
62
63
64
65
66
67
         {:ok, _activity} <-
           ActivityPub.reject(%{
             to: [follower.ap_id],
             actor: followed,
             object: follow_activity.data["id"],
             type: "Reject"
           }) do
      {:ok, follower}
    end
  end

lain's avatar
lain committed
68
  def delete(activity_id, user) do
kaniini's avatar
kaniini committed
69
70
    with %Activity{data: %{"object" => _}} = activity <-
           Activity.get_by_id_with_object(activity_id),
71
         %Object{} = object <- Object.normalize(activity),
72
         true <- User.superuser?(user) || user.ap_id == object.data["actor"],
minibikini's avatar
minibikini committed
73
         {:ok, _} <- unpin(activity_id, user),
74
         {:ok, delete} <- ActivityPub.delete(object) do
lain's avatar
lain committed
75
      {:ok, delete}
Sergey Suprunenko's avatar
Sergey Suprunenko committed
76
77
    else
      _ ->
78
        {:error, dgettext("errors", "Could not delete")}
lain's avatar
lain committed
79
80
    end
  end
lain's avatar
lain committed
81
82
83

  def repeat(id_or_ap_id, user) do
    with %Activity{} = activity <- get_by_id_or_ap_id(id_or_ap_id),
84
         object <- Object.normalize(activity),
85
         nil <- Utils.get_existing_announce(user.ap_id, object) do
lain's avatar
lain committed
86
87
88
      ActivityPub.announce(user, object)
    else
      _ ->
89
        {:error, dgettext("errors", "Could not repeat")}
lain's avatar
lain committed
90
91
92
    end
  end

normandy's avatar
normandy committed
93
94
  def unrepeat(id_or_ap_id, user) do
    with %Activity{} = activity <- get_by_id_or_ap_id(id_or_ap_id),
95
         object <- Object.normalize(activity) do
normandy's avatar
normandy committed
96
97
98
      ActivityPub.unannounce(user, object)
    else
      _ ->
99
        {:error, dgettext("errors", "Could not unrepeat")}
normandy's avatar
normandy committed
100
101
102
    end
  end

lain's avatar
lain committed
103
104
  def favorite(id_or_ap_id, user) do
    with %Activity{} = activity <- get_by_id_or_ap_id(id_or_ap_id),
105
         object <- Object.normalize(activity),
106
         nil <- Utils.get_existing_like(user.ap_id, object) do
lain's avatar
lain committed
107
108
109
      ActivityPub.like(user, object)
    else
      _ ->
110
        {:error, dgettext("errors", "Could not favorite")}
lain's avatar
lain committed
111
112
113
    end
  end

lain's avatar
lain committed
114
115
  def unfavorite(id_or_ap_id, user) do
    with %Activity{} = activity <- get_by_id_or_ap_id(id_or_ap_id),
116
         object <- Object.normalize(activity) do
lain's avatar
lain committed
117
118
119
      ActivityPub.unlike(user, object)
    else
      _ ->
120
        {:error, dgettext("errors", "Could not unfavorite")}
lain's avatar
lain committed
121
122
123
    end
  end

rinpatch's avatar
rinpatch committed
124
125
126
127
128
129
130
131
132
133
134
135
136
  def vote(user, object, choices) do
    with "Question" <- object.data["type"],
         {:author, false} <- {:author, object.data["actor"] == user.ap_id},
         {:existing_votes, []} <- {:existing_votes, Utils.get_existing_votes(user.ap_id, object)},
         {options, max_count} <- get_options_and_max_count(object),
         option_count <- Enum.count(options),
         {:choice_check, {choices, true}} <-
           {:choice_check, normalize_and_validate_choice_indices(choices, option_count)},
         {:count_check, true} <- {:count_check, Enum.count(choices) <= max_count} do
      answer_activities =
        Enum.map(choices, fn index ->
          answer_data = make_answer_data(user, object, Enum.at(options, index)["name"])

137
138
139
140
141
142
143
144
145
146
          {:ok, activity} =
            ActivityPub.create(%{
              to: answer_data["to"],
              actor: user,
              context: object.data["context"],
              object: answer_data,
              additional: %{"cc" => answer_data["cc"]}
            })

          activity
rinpatch's avatar
rinpatch committed
147
148
        end)

149
      object = Object.get_cached_by_ap_id(object.data["id"])
rinpatch's avatar
rinpatch committed
150
151
      {:ok, answer_activities, object}
    else
152
153
154
155
      {:author, _} -> {:error, dgettext("errors", "Poll's author can't vote")}
      {:existing_votes, _} -> {:error, dgettext("errors", "Already voted")}
      {:choice_check, {_, false}} -> {:error, dgettext("errors", "Invalid indices")}
      {:count_check, false} -> {:error, dgettext("errors", "Too many choices")}
rinpatch's avatar
rinpatch committed
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
    end
  end

  defp get_options_and_max_count(object) do
    if Map.has_key?(object.data, "anyOf") do
      {object.data["anyOf"], Enum.count(object.data["anyOf"])}
    else
      {object.data["oneOf"], 1}
    end
  end

  defp normalize_and_validate_choice_indices(choices, count) do
    Enum.map_reduce(choices, true, fn index, valid ->
      index = if is_binary(index), do: String.to_integer(index), else: index
      {index, if(valid, do: index < count, else: valid)}
    end)
  end

lain's avatar
lain committed
174
  def get_visibility(%{"visibility" => visibility}, in_reply_to)
lain's avatar
lain committed
175
      when visibility in ~w{public unlisted private direct},
lain's avatar
lain committed
176
      do: {visibility, get_replied_to_visibility(in_reply_to)}
lain's avatar
lain committed
177

178
179
180
  def get_visibility(%{"visibility" => "list:" <> list_id}, in_reply_to) do
    visibility = {:list, String.to_integer(list_id)}
    {visibility, get_replied_to_visibility(in_reply_to)}
minibikini's avatar
minibikini committed
181
182
  end

lain's avatar
lain committed
183
184
185
  def get_visibility(_, in_reply_to) when not is_nil(in_reply_to) do
    visibility = get_replied_to_visibility(in_reply_to)
    {visibility, visibility}
186
  end
lain's avatar
lain committed
187

lain's avatar
lain committed
188
  def get_visibility(_, in_reply_to), do: {"public", get_replied_to_visibility(in_reply_to)}
189

190
  def get_replied_to_visibility(nil), do: nil
191

192
193
194
  def get_replied_to_visibility(activity) do
    with %Object{} = object <- Object.normalize(activity) do
      Pleroma.Web.ActivityPub.Visibility.get_visibility(object)
195
    end
196
  end
lain's avatar
lain committed
197

198
  def post(user, %{"status" => status} = data) do
href's avatar
href committed
199
    limit = Pleroma.Config.get([:instance, :limit])
lain's avatar
lain committed
200

201
    with status <- String.trim(status),
202
         attachments <- attachments_from_ids(data),
203
         in_reply_to <- get_replied_to_activity(data["in_reply_to_status_id"]),
lain's avatar
lain committed
204
         {visibility, in_reply_to_visibility} <- get_visibility(data, in_reply_to),
205
206
         {_, false} <-
           {:private_to_public, in_reply_to_visibility == "direct" && visibility != "direct"},
minibikini's avatar
minibikini committed
207
         {content_html, mentions, tags} <-
208
209
210
           make_content_html(
             status,
             attachments,
lain's avatar
lain committed
211
212
             data,
             visibility
213
           ),
lain's avatar
lain committed
214
215
         mentioned_users <- for({_, mentioned_user} <- mentions, do: mentioned_user.ap_id),
         addressed_users <- get_addressed_users(mentioned_users, data["to"]),
216
         {poll, poll_emoji} <- make_poll_data(data),
lain's avatar
lain committed
217
         {to, cc} <- get_to_and_cc(user, addressed_users, in_reply_to, visibility),
218
         context <- make_context(in_reply_to),
Haelwenn's avatar
Haelwenn committed
219
         cw <- data["spoiler_text"] || "",
220
         sensitive <- data["sensitive"] || Enum.member?(tags, {"#nsfw", "nsfw"}),
Haelwenn's avatar
Haelwenn committed
221
         full_payload <- String.trim(status <> cw),
222
         :ok <- validate_character_limit(full_payload, attachments, limit),
lain's avatar
lain committed
223
224
225
226
227
228
229
         object <-
           make_note_data(
             user.ap_id,
             to,
             context,
             content_html,
             attachments,
230
             in_reply_to,
lain's avatar
lain committed
231
232
             tags,
             cw,
233
             cc,
234
             sensitive,
235
             poll
lain's avatar
lain committed
236
237
238
239
240
           ),
         object <-
           Map.put(
             object,
             "emoji",
241
             Map.merge(Formatter.get_emoji_map(full_payload), poll_emoji)
lain's avatar
lain committed
242
           ) do
minibikini's avatar
minibikini committed
243
244
245
      preview? = Pleroma.Web.ControllerHelper.truthy_param?(data["preview"]) || false
      direct? = visibility == "direct"

246
      %{
minibikini's avatar
minibikini committed
247
248
249
250
        to: to,
        actor: user,
        context: context,
        object: object,
251
        additional: %{"cc" => cc, "directMessage" => direct?}
minibikini's avatar
minibikini committed
252
      }
253
254
      |> maybe_add_list_data(user, visibility)
      |> ActivityPub.create(preview?)
255
    else
256
257
258
259
260
261
262
263
      {:private_to_public, true} ->
        {:error, dgettext("errors", "The message visibility must be direct")}

      {:error, _} = e ->
        e

      e ->
        {:error, e}
lain's avatar
lain committed
264
265
    end
  end
lain's avatar
lain committed
266

lain's avatar
lain committed
267
  # Updates the emojis for a user based on their profile
lain's avatar
lain committed
268
  def update(user) do
269
270
    user =
      with emoji <- emoji_from_profile(user),
lain's avatar
lain committed
271
           source_data <- (user.info.source_data || %{}) |> Map.put("tag", emoji),
minibikini's avatar
minibikini committed
272
           info_cng <- User.Info.set_source_data(user.info, source_data),
lain's avatar
lain committed
273
           change <- Ecto.Changeset.change(user) |> Ecto.Changeset.put_embed(:info, info_cng),
274
275
276
277
278
279
280
           {:ok, user} <- User.update_and_set_cache(change) do
        user
      else
        _e ->
          user
      end

lain's avatar
lain committed
281
282
283
284
285
286
287
    ActivityPub.update(%{
      local: true,
      to: [user.follower_address],
      cc: [],
      actor: user.ap_id,
      object: Pleroma.Web.ActivityPub.UserView.render("user.json", %{user: user})
    })
lain's avatar
lain committed
288
  end
minibikini's avatar
minibikini committed
289

290
291
292
293
  def pin(id_or_ap_id, %{ap_id: user_ap_id} = user) do
    with %Activity{
           actor: ^user_ap_id,
           data: %{
294
295
296
297
             "type" => "Create"
           },
           object: %Object{
             data: %{
298
299
300
301
               "type" => "Note"
             }
           }
         } = activity <- get_by_id_or_ap_id(id_or_ap_id),
302
         true <- Visibility.is_public?(activity),
303
         %{valid?: true} = info_changeset <- User.Info.add_pinnned_activity(user.info, activity),
minibikini's avatar
minibikini committed
304
305
306
307
308
309
310
311
312
         changeset <-
           Ecto.Changeset.change(user) |> Ecto.Changeset.put_embed(:info, info_changeset),
         {:ok, _user} <- User.update_and_set_cache(changeset) do
      {:ok, activity}
    else
      %{errors: [pinned_activities: {err, _}]} ->
        {:error, err}

      _ ->
313
        {:error, dgettext("errors", "Could not pin")}
minibikini's avatar
minibikini committed
314
315
316
317
318
319
    end
  end

  def unpin(id_or_ap_id, user) do
    with %Activity{} = activity <- get_by_id_or_ap_id(id_or_ap_id),
         %{valid?: true} = info_changeset <-
minibikini's avatar
minibikini committed
320
           User.Info.remove_pinnned_activity(user.info, activity),
minibikini's avatar
minibikini committed
321
322
323
324
325
326
327
328
329
         changeset <-
           Ecto.Changeset.change(user) |> Ecto.Changeset.put_embed(:info, info_changeset),
         {:ok, _user} <- User.update_and_set_cache(changeset) do
      {:ok, activity}
    else
      %{errors: [pinned_activities: {err, _}]} ->
        {:error, err}

      _ ->
330
        {:error, dgettext("errors", "Could not unpin")}
minibikini's avatar
minibikini committed
331
332
    end
  end
333
334
335
336
337

  def add_mute(user, activity) do
    with {:ok, _} <- ThreadMute.add_mute(user.id, activity.data["context"]) do
      {:ok, activity}
    else
338
      {:error, _} -> {:error, dgettext("errors", "conversation is already muted")}
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
    end
  end

  def remove_mute(user, activity) do
    ThreadMute.remove_mute(user.id, activity.data["context"])
    {:ok, activity}
  end

  def thread_muted?(%{id: nil} = _user, _activity), do: false

  def thread_muted?(user, activity) do
    with [] <- ThreadMute.check_muted(user.id, activity.data["context"]) do
      false
    else
      _ -> true
    end
  end
minibikini's avatar
Reports    
minibikini committed
356
357
358

  def report(user, data) do
    with {:account_id, %{"account_id" => account_id}} <- {:account_id, data},
minibikini's avatar
minibikini committed
359
         {:account, %User{} = account} <- {:account, User.get_cached_by_id(account_id)},
minibikini's avatar
minibikini committed
360
         {:ok, {content_html, _, _}} <- make_report_content_html(data["comment"]),
minibikini's avatar
Reports    
minibikini committed
361
362
363
364
365
366
367
         {:ok, statuses} <- get_report_statuses(account, data),
         {:ok, activity} <-
           ActivityPub.flag(%{
             context: Utils.generate_context_id(),
             actor: user,
             account: account,
             statuses: statuses,
368
369
             content: content_html,
             forward: data["forward"] || false
minibikini's avatar
Reports    
minibikini committed
370
371
372
373
           }) do
      {:ok, activity}
    else
      {:error, err} -> {:error, err}
374
375
      {:account_id, %{}} -> {:error, dgettext("errors", "Valid `account_id` required")}
      {:account, nil} -> {:error, dgettext("errors", "Account not found")}
minibikini's avatar
Reports    
minibikini committed
376
377
    end
  end
378

Sergey Suprunenko's avatar
Sergey Suprunenko committed
379
380
381
382
383
  def update_report_state(activity_id, state) do
    with %Activity{} = activity <- Activity.get_by_id(activity_id),
         {:ok, activity} <- Utils.update_report_state(activity, state) do
      {:ok, activity}
    else
384
385
386
      nil -> {:error, :not_found}
      {:error, reason} -> {:error, reason}
      _ -> {:error, dgettext("errors", "Could not update state")}
Sergey Suprunenko's avatar
Sergey Suprunenko committed
387
388
389
390
391
392
393
394
395
    end
  end

  def update_activity_scope(activity_id, opts \\ %{}) do
    with %Activity{} = activity <- Activity.get_by_id_with_object(activity_id),
         {:ok, activity} <- toggle_sensitive(activity, opts),
         {:ok, activity} <- set_visibility(activity, opts) do
      {:ok, activity}
    else
396
397
      nil -> {:error, :not_found}
      {:error, reason} -> {:error, reason}
Sergey Suprunenko's avatar
Sergey Suprunenko committed
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
    end
  end

  defp toggle_sensitive(activity, %{"sensitive" => sensitive}) when sensitive in ~w(true false) do
    toggle_sensitive(activity, %{"sensitive" => String.to_existing_atom(sensitive)})
  end

  defp toggle_sensitive(%Activity{object: object} = activity, %{"sensitive" => sensitive})
       when is_boolean(sensitive) do
    new_data = Map.put(object.data, "sensitive", sensitive)

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

    {:ok, Map.put(activity, :object, object)}
  end

  defp toggle_sensitive(activity, _), do: {:ok, activity}

  defp set_visibility(activity, %{"visibility" => visibility}) do
    Utils.update_activity_visibility(activity, visibility)
  end

  defp set_visibility(activity, _), do: {:ok, activity}

425
426
427
428
429
  def hide_reblogs(user, muted) do
    ap_id = muted.ap_id

    if ap_id not in user.info.muted_reblogs do
      info_changeset = User.Info.add_reblog_mute(user.info, ap_id)
430
431
432
433
434
      changeset = Ecto.Changeset.change(user) |> Ecto.Changeset.put_embed(:info, info_changeset)
      User.update_and_set_cache(changeset)
    end
  end

435
436
437
438
439
  def show_reblogs(user, muted) do
    ap_id = muted.ap_id

    if ap_id in user.info.muted_reblogs do
      info_changeset = User.Info.remove_reblog_mute(user.info, ap_id)
440
441
442
443
      changeset = Ecto.Changeset.change(user) |> Ecto.Changeset.put_embed(:info, info_changeset)
      User.update_and_set_cache(changeset)
    end
  end
lain's avatar
lain committed
444
end