util_controller.ex 10.4 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

dtluna's avatar
dtluna committed
5
6
defmodule Pleroma.Web.TwitterAPI.UtilController do
  use Pleroma.Web, :controller
7

eal's avatar
eal committed
8
  require Logger
9

10
  alias Pleroma.Activity
Haelwenn's avatar
Haelwenn committed
11
  alias Pleroma.Emoji
12
  alias Pleroma.Notification
13
  alias Pleroma.Plugs.AuthenticationPlug
14
  alias Pleroma.User
15
  alias Pleroma.Web
16
  alias Pleroma.Web.ActivityPub.ActivityPub
Haelwenn's avatar
Haelwenn committed
17
18
19
  alias Pleroma.Web.CommonAPI
  alias Pleroma.Web.OStatus
  alias Pleroma.Web.WebFinger
Roger Braun's avatar
Roger Braun committed
20

dtluna's avatar
dtluna committed
21
22
23
24
  def help_test(conn, _params) do
    json(conn, "ok")
  end

eal's avatar
eal committed
25
  def remote_subscribe(conn, %{"nickname" => nick, "profile" => _}) do
lain's avatar
lain committed
26
    with %User{} = user <- User.get_cached_by_nickname(nick), avatar = User.avatar_url(user) do
eal's avatar
eal committed
27
28
29
      conn
      |> render("subscribe.html", %{nickname: nick, avatar: avatar, error: false})
    else
lain's avatar
lain committed
30
31
32
33
34
35
      _e ->
        render(conn, "subscribe.html", %{
          nickname: nick,
          avatar: nil,
          error: "Could not find user"
        })
eal's avatar
eal committed
36
37
    end
  end
lain's avatar
lain committed
38

eal's avatar
eal committed
39
40
41
42
43
44
45
  def remote_subscribe(conn, %{"user" => %{"nickname" => nick, "profile" => profile}}) do
    with {:ok, %{"subscribe_address" => template}} <- WebFinger.finger(profile),
         %User{ap_id: ap_id} <- User.get_cached_by_nickname(nick) do
      conn
      |> Phoenix.Controller.redirect(external: String.replace(template, "{uri}", ap_id))
    else
      _e ->
lain's avatar
lain committed
46
47
48
49
50
        render(conn, "subscribe.html", %{
          nickname: nick,
          avatar: nil,
          error: "Something went wrong."
        })
eal's avatar
eal committed
51
52
53
    end
  end

54
  def remote_follow(%{assigns: %{user: user}} = conn, %{"acct" => acct}) do
55
    if is_status?(acct) do
56
      {:ok, object} = Pleroma.Object.Fetcher.fetch_object_from_id(acct)
57
58
      %Activity{id: activity_id} = Activity.get_create_by_object_ap_id(object.data["id"])
      redirect(conn, to: "/notice/#{activity_id}")
59
    else
60
61
62
63
      {err, followee} = OStatus.find_or_make_user(acct)
      avatar = User.avatar_url(followee)
      name = followee.nickname
      id = followee.id
64

65
66
67
68
69
70
71
72
73
74
75
76
77
      if !!user do
        conn
        |> render("follow.html", %{error: err, acct: acct, avatar: avatar, name: name, id: id})
      else
        conn
        |> render("follow_login.html", %{
          error: false,
          acct: acct,
          avatar: avatar,
          name: name,
          id: id
        })
      end
78
79
80
    end
  end

81
  defp is_status?(acct) do
82
    case Pleroma.Object.Fetcher.fetch_and_contain_remote_object_from_id(acct) do
83
84
85
86
87
      {:ok, %{"type" => type}} when type in ["Article", "Note", "Video", "Page", "Question"] ->
        true

      _ ->
        false
88
89
90
    end
  end

lain's avatar
lain committed
91
92
93
  def do_remote_follow(conn, %{
        "authorization" => %{"name" => username, "password" => password, "id" => id}
      }) do
minibikini's avatar
minibikini committed
94
    followee = User.get_cached_by_id(id)
95
96
    avatar = User.avatar_url(followee)
    name = followee.nickname
lain's avatar
lain committed
97

98
    with %User{} = user <- User.get_cached_by_nickname(username),
99
         true <- AuthenticationPlug.checkpw(password, user.password_hash),
minibikini's avatar
minibikini committed
100
         %User{} = _followed <- User.get_cached_by_id(id),
101
102
103
104
105
         {:ok, follower} <- User.follow(user, followee),
         {:ok, _activity} <- ActivityPub.follow(follower, followee) do
      conn
      |> render("followed.html", %{error: false})
    else
106
107
108
109
      # Was already following user
      {:error, "Could not follow user:" <> _rest} ->
        render(conn, "followed.html", %{error: false})

110
111
      _e ->
        conn
lain's avatar
lain committed
112
113
114
115
116
117
        |> render("follow_login.html", %{
          error: "Wrong username or password",
          id: id,
          name: name,
          avatar: avatar
        })
118
119
    end
  end
lain's avatar
lain committed
120

121
  def do_remote_follow(%{assigns: %{user: user}} = conn, %{"user" => %{"id" => id}}) do
minibikini's avatar
minibikini committed
122
    with %User{} = followee <- User.get_cached_by_id(id),
123
124
125
126
127
         {:ok, follower} <- User.follow(user, followee),
         {:ok, _activity} <- ActivityPub.follow(follower, followee) do
      conn
      |> render("followed.html", %{error: false})
    else
128
129
130
131
132
      # Was already following user
      {:error, "Could not follow user:" <> _rest} ->
        conn
        |> render("followed.html", %{error: false})

133
      e ->
lain's avatar
lain committed
134
135
136
137
        Logger.debug("Remote follow failed with error #{inspect(e)}")

        conn
        |> render("followed.html", %{error: inspect(e)})
138
139
140
    end
  end

141
142
143
144
145
146
147
148
149
150
151
  def notifications_read(%{assigns: %{user: user}} = conn, %{"id" => notification_id}) do
    with {:ok, _} <- Notification.read_one(user, notification_id) do
      json(conn, %{status: "success"})
    else
      {:error, message} ->
        conn
        |> put_resp_content_type("application/json")
        |> send_resp(403, Jason.encode!(%{"error" => message}))
    end
  end

dtluna's avatar
dtluna committed
152
  def config(conn, _params) do
href's avatar
href committed
153
154
    instance = Pleroma.Config.get(:instance)

lain's avatar
lain committed
155
156
157
158
159
    case get_format(conn) do
      "xml" ->
        response = """
        <config>
          <site>
href's avatar
href committed
160
            <name>#{Keyword.get(instance, :name)}</name>
lain's avatar
lain committed
161
            <site>#{Web.base_url()}</site>
href's avatar
href committed
162
163
            <textlimit>#{Keyword.get(instance, :limit)}</textlimit>
            <closed>#{!Keyword.get(instance, :registrations_open)}</closed>
lain's avatar
lain committed
164
165
166
          </site>
        </config>
        """
lain's avatar
lain committed
167

lain's avatar
lain committed
168
169
170
        conn
        |> put_resp_content_type("application/xml")
        |> send_resp(200, response)
lain's avatar
lain committed
171

lain's avatar
lain committed
172
      _ ->
173
        vapid_public_key = Keyword.get(Pleroma.Web.Push.vapid_config(), :public_key)
minibikini's avatar
minibikini committed
174

175
176
177
178
179
180
181
        uploadlimit = %{
          uploadlimit: to_string(Keyword.get(instance, :upload_limit)),
          avatarlimit: to_string(Keyword.get(instance, :avatar_upload_limit)),
          backgroundlimit: to_string(Keyword.get(instance, :background_upload_limit)),
          bannerlimit: to_string(Keyword.get(instance, :banner_upload_limit))
        }

182
        data = %{
href's avatar
href committed
183
184
          name: Keyword.get(instance, :name),
          description: Keyword.get(instance, :description),
185
          server: Web.base_url(),
href's avatar
href committed
186
          textlimit: to_string(Keyword.get(instance, :limit)),
187
          uploadlimit: uploadlimit,
href's avatar
href committed
188
          closed: if(Keyword.get(instance, :registrations_open), do: "0", else: "1"),
189
          private: if(Keyword.get(instance, :public, true), do: "0", else: "1"),
190
          vapidPublicKey: vapid_public_key,
191
192
          accountActivationRequired:
            if(Keyword.get(instance, :account_activation_required, false), do: "1", else: "0"),
193
194
195
          invitesEnabled: if(Keyword.get(instance, :invites_enabled, false), do: "1", else: "0"),
          safeDMMentionsEnabled:
            if(Pleroma.Config.get([:instance, :safe_dm_mentions]), do: "1", else: "0")
196
197
        }

198
        pleroma_fe = Pleroma.Config.get([:frontend_configurations, :pleroma_fe])
199

href's avatar
href committed
200
        managed_config = Keyword.get(instance, :managed_config)
kaniini's avatar
kaniini committed
201

202
203
204
205
206
207
208
209
        data =
          if managed_config do
            data |> Map.put("pleromafe", pleroma_fe)
          else
            data
          end

        json(conn, %{site: data})
lain's avatar
lain committed
210
211
212
    end
  end

lain's avatar
lain committed
213
214
215
216
217
218
219
220
  def frontend_configurations(conn, _params) do
    config =
      Pleroma.Config.get(:frontend_configurations, %{})
      |> Enum.into(%{})

    json(conn, config)
  end

lain's avatar
lain committed
221
  def version(conn, _params) do
href's avatar
href committed
222
    version = Pleroma.Application.named_version()
lain's avatar
lain committed
223

lain's avatar
lain committed
224
225
    case get_format(conn) do
      "xml" ->
226
        response = "<version>#{version}</version>"
lain's avatar
lain committed
227

lain's avatar
lain committed
228
229
230
        conn
        |> put_resp_content_type("application/xml")
        |> send_resp(200, response)
lain's avatar
lain committed
231
232
233

      _ ->
        json(conn, version)
lain's avatar
lain committed
234
    end
dtluna's avatar
dtluna committed
235
  end
eal's avatar
eal committed
236
237

  def emoji(conn, _params) do
238
239
240
    emoji =
      Emoji.get_all()
      |> Enum.map(fn {short_code, path, tags} ->
241
        {short_code, %{image_url: path, tags: tags}}
242
      end)
243
      |> Enum.into(%{})
244
245

    json(conn, emoji)
eal's avatar
eal committed
246
  end
eal's avatar
eal committed
247

248
249
250
251
  def update_notificaton_settings(%{assigns: %{user: user}} = conn, params) do
    with {:ok, _} <- User.update_notification_settings(user, params) do
      json(conn, %{status: "success"})
    end
eal's avatar
eal committed
252
  end
eal's avatar
eal committed
253

254
255
256
  def follow_import(conn, %{"list" => %Plug.Upload{} = listfile}) do
    follow_import(conn, %{"list" => File.read!(listfile.path)})
  end
lain's avatar
lain committed
257

258
  def follow_import(%{assigns: %{user: follower}} = conn, %{"list" => list}) do
259
260
261
262
263
    with lines <- String.split(list, "\n"),
         followed_identifiers <-
           Enum.map(lines, fn line ->
             String.split(line, ",") |> List.first()
           end)
264
265
266
267
268
269
270
           |> List.delete("Account address") do
      PleromaJobQueue.enqueue(:background, User, [
        :follow_import,
        follower,
        followed_identifiers
      ])

271
272
      json(conn, "job started")
    end
eal's avatar
eal committed
273
  end
274

275
276
277
278
  def blocks_import(conn, %{"list" => %Plug.Upload{} = listfile}) do
    blocks_import(conn, %{"list" => File.read!(listfile.path)})
  end

279
  def blocks_import(%{assigns: %{user: blocker}} = conn, %{"list" => list}) do
280
281
282
283
284
285
286
    with blocked_identifiers <- String.split(list) do
      PleromaJobQueue.enqueue(:background, User, [
        :blocks_import,
        blocker,
        blocked_identifiers
      ])

287
288
      json(conn, "job started")
    end
289
290
  end

291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
  def change_password(%{assigns: %{user: user}} = conn, params) do
    case CommonAPI.Utils.confirm_current_password(user, params["password"]) do
      {:ok, user} ->
        with {:ok, _user} <-
               User.reset_password(user, %{
                 password: params["new_password"],
                 password_confirmation: params["new_password_confirmation"]
               }) do
          json(conn, %{status: "success"})
        else
          {:error, changeset} ->
            {_, {error, _}} = Enum.at(changeset.errors, 0)
            json(conn, %{error: "New password #{error}."})

          _ ->
            json(conn, %{error: "Unable to change password."})
        end

      {:error, msg} ->
        json(conn, %{error: msg})
    end
  end

314
  def delete_account(%{assigns: %{user: user}} = conn, params) do
315
    case CommonAPI.Utils.confirm_current_password(user, params["password"]) do
316
      {:ok, user} ->
317
        User.delete(user)
318
        json(conn, %{status: "success"})
319
320
321
322
323

      {:error, msg} ->
        json(conn, %{error: msg})
    end
  end
324

325
326
327
  def disable_account(%{assigns: %{user: user}} = conn, params) do
    case CommonAPI.Utils.confirm_current_password(user, params["password"]) do
      {:ok, user} ->
328
        User.deactivate_async(user)
329
330
331
332
333
334
335
        json(conn, %{status: "success"})

      {:error, msg} ->
        json(conn, %{error: msg})
    end
  end

336
337
338
  def captcha(conn, _params) do
    json(conn, Pleroma.Captcha.new())
  end
339
340

  def healthcheck(conn, _params) do
341
342
343
344
345
346
    info =
      if Pleroma.Config.get([:instance, :healthcheck]) do
        Pleroma.Healthcheck.system_info()
      else
        %{}
      end
347
348

    conn =
349
      if info[:healthy] do
350
351
352
353
354
355
356
        conn
      else
        Plug.Conn.put_status(conn, :service_unavailable)
      end

    json(conn, info)
  end
dtluna's avatar
dtluna committed
357
end