Extract suggestions actions from `MastodonAPIController` to `SuggestionController`
authorEgor Kislitsyn <egor@kislitsyn.com>
Tue, 1 Oct 2019 07:45:04 +0000 (14:45 +0700)
committerEgor Kislitsyn <egor@kislitsyn.com>
Tue, 1 Oct 2019 08:07:49 +0000 (15:07 +0700)
lib/pleroma/web/mastodon_api/controllers/mastodon_api_controller.ex
lib/pleroma/web/mastodon_api/controllers/suggestion_controller.ex [new file with mode: 0644]
lib/pleroma/web/router.ex
test/web/mastodon_api/controllers/suggestion_controller_test.exs [new file with mode: 0644]
test/web/mastodon_api/mastodon_api_controller_test.exs

index f466ecbfff47b59e050a7ac373a2610090a1d6d4..ff6de425f3fe16811e07368cee8ae15c32e88470 100644 (file)
@@ -9,7 +9,6 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do
 
   alias Pleroma.Bookmark
   alias Pleroma.Config
-  alias Pleroma.HTTP
   alias Pleroma.Pagination
   alias Pleroma.Plugs.RateLimiter
   alias Pleroma.Repo
@@ -22,7 +21,6 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do
   alias Pleroma.Web.MastodonAPI.AppView
   alias Pleroma.Web.MastodonAPI.MastodonView
   alias Pleroma.Web.MastodonAPI.StatusView
-  alias Pleroma.Web.MediaProxy
   alias Pleroma.Web.OAuth.App
   alias Pleroma.Web.OAuth.Authorization
   alias Pleroma.Web.OAuth.Scopes
@@ -362,53 +360,6 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIController do
     json(conn, %{})
   end
 
-  def suggestions(%{assigns: %{user: user}} = conn, _) do
-    suggestions = Config.get(:suggestions)
-
-    if Keyword.get(suggestions, :enabled, false) do
-      api = Keyword.get(suggestions, :third_party_engine, "")
-      timeout = Keyword.get(suggestions, :timeout, 5000)
-      limit = Keyword.get(suggestions, :limit, 23)
-
-      host = Config.get([Pleroma.Web.Endpoint, :url, :host])
-
-      user = user.nickname
-
-      url =
-        api
-        |> String.replace("{{host}}", host)
-        |> String.replace("{{user}}", user)
-
-      with {:ok, %{status: 200, body: body}} <-
-             HTTP.get(url, [], adapter: [recv_timeout: timeout, pool: :default]),
-           {:ok, data} <- Jason.decode(body) do
-        data =
-          data
-          |> Enum.slice(0, limit)
-          |> Enum.map(fn x ->
-            x
-            |> Map.put("id", fetch_suggestion_id(x))
-            |> Map.put("avatar", MediaProxy.url(x["avatar"]))
-            |> Map.put("avatar_static", MediaProxy.url(x["avatar_static"]))
-          end)
-
-        json(conn, data)
-      else
-        e ->
-          Logger.error("Could not retrieve suggestions at fetch #{url}, #{inspect(e)}")
-      end
-    else
-      json(conn, [])
-    end
-  end
-
-  defp fetch_suggestion_id(attrs) do
-    case User.get_or_fetch(attrs["acct"]) do
-      {:ok, %User{id: id}} -> id
-      _ -> 0
-    end
-  end
-
   def password_reset(conn, params) do
     nickname_or_email = params["email"] || params["nickname"]
 
diff --git a/lib/pleroma/web/mastodon_api/controllers/suggestion_controller.ex b/lib/pleroma/web/mastodon_api/controllers/suggestion_controller.ex
new file mode 100644 (file)
index 0000000..9076bb8
--- /dev/null
@@ -0,0 +1,63 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.MastodonAPI.SuggestionController do
+  use Pleroma.Web, :controller
+
+  require Logger
+
+  alias Pleroma.Config
+  alias Pleroma.User
+  alias Pleroma.Web.MediaProxy
+
+  action_fallback(Pleroma.Web.MastodonAPI.FallbackController)
+
+  @doc "GET /api/v1/suggestions"
+  def index(%{assigns: %{user: user}} = conn, _) do
+    if Config.get([:suggestions, :enabled], false) do
+      with {:ok, data} <- fetch_suggestions(user) do
+        limit = Config.get([:suggestions, :limit], 23)
+
+        data =
+          data
+          |> Enum.slice(0, limit)
+          |> Enum.map(fn x ->
+            x
+            |> Map.put("id", fetch_suggestion_id(x))
+            |> Map.put("avatar", MediaProxy.url(x["avatar"]))
+            |> Map.put("avatar_static", MediaProxy.url(x["avatar_static"]))
+          end)
+
+        json(conn, data)
+      end
+    else
+      json(conn, [])
+    end
+  end
+
+  defp fetch_suggestions(user) do
+    api = Config.get([:suggestions, :third_party_engine], "")
+    timeout = Config.get([:suggestions, :timeout], 5000)
+    host = Config.get([Pleroma.Web.Endpoint, :url, :host])
+
+    url =
+      api
+      |> String.replace("{{host}}", host)
+      |> String.replace("{{user}}", user.nickname)
+
+    with {:ok, %{status: 200, body: body}} <-
+           Pleroma.HTTP.get(url, [], adapter: [recv_timeout: timeout, pool: :default]) do
+      Jason.decode(body)
+    else
+      e -> Logger.error("Could not retrieve suggestions at fetch #{url}, #{inspect(e)}")
+    end
+  end
+
+  defp fetch_suggestion_id(attrs) do
+    case User.get_or_fetch(attrs["acct"]) do
+      {:ok, %User{id: id}} -> id
+      _ -> 0
+    end
+  end
+end
index 8b482528b0871a84bc2878c6390803870c01fc2f..bb8e7bd721651038654b3f53356e0344101eb945 100644 (file)
@@ -373,7 +373,7 @@ defmodule Pleroma.Web.Router do
 
       get("/filters", FilterController, :index)
 
-      get("/suggestions", MastodonAPIController, :suggestions)
+      get("/suggestions", SuggestionController, :index)
 
       get("/conversations", ConversationController, :index)
       post("/conversations/:id/read", ConversationController, :read)
diff --git a/test/web/mastodon_api/controllers/suggestion_controller_test.exs b/test/web/mastodon_api/controllers/suggestion_controller_test.exs
new file mode 100644 (file)
index 0000000..78620a8
--- /dev/null
@@ -0,0 +1,92 @@
+# Pleroma: A lightweight social networking server
+# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
+# SPDX-License-Identifier: AGPL-3.0-only
+
+defmodule Pleroma.Web.MastodonAPI.SuggestionControllerTest do
+  use Pleroma.Web.ConnCase
+
+  alias Pleroma.Config
+
+  import ExUnit.CaptureLog
+  import Pleroma.Factory
+  import Tesla.Mock
+
+  setup do
+    user = insert(:user)
+    other_user = insert(:user)
+    host = Config.get([Pleroma.Web.Endpoint, :url, :host])
+    url500 = "http://test500?#{host}&#{user.nickname}"
+    url200 = "http://test200?#{host}&#{user.nickname}"
+
+    mock(fn
+      %{method: :get, url: ^url500} ->
+        %Tesla.Env{status: 500, body: "bad request"}
+
+      %{method: :get, url: ^url200} ->
+        %Tesla.Env{
+          status: 200,
+          body:
+            ~s([{"acct":"yj455","avatar":"https://social.heldscal.la/avatar/201.jpeg","avatar_static":"https://social.heldscal.la/avatar/s/201.jpeg"}, {"acct":"#{
+              other_user.ap_id
+            }","avatar":"https://social.heldscal.la/avatar/202.jpeg","avatar_static":"https://social.heldscal.la/avatar/s/202.jpeg"}])
+        }
+    end)
+
+    [user: user, other_user: other_user]
+  end
+
+  clear_config(:suggestions)
+
+  test "returns empty result when suggestions disabled", %{conn: conn, user: user} do
+    Config.put([:suggestions, :enabled], false)
+
+    res =
+      conn
+      |> assign(:user, user)
+      |> get("/api/v1/suggestions")
+      |> json_response(200)
+
+    assert res == []
+  end
+
+  test "returns error", %{conn: conn, user: user} do
+    Config.put([:suggestions, :enabled], true)
+    Config.put([:suggestions, :third_party_engine], "http://test500?{{host}}&{{user}}")
+
+    assert capture_log(fn ->
+             res =
+               conn
+               |> assign(:user, user)
+               |> get("/api/v1/suggestions")
+               |> json_response(500)
+
+             assert res == "Something went wrong"
+           end) =~ "Could not retrieve suggestions"
+  end
+
+  test "returns suggestions", %{conn: conn, user: user, other_user: other_user} do
+    Config.put([:suggestions, :enabled], true)
+    Config.put([:suggestions, :third_party_engine], "http://test200?{{host}}&{{user}}")
+
+    res =
+      conn
+      |> assign(:user, user)
+      |> get("/api/v1/suggestions")
+      |> json_response(200)
+
+    assert res == [
+             %{
+               "acct" => "yj455",
+               "avatar" => "https://social.heldscal.la/avatar/201.jpeg",
+               "avatar_static" => "https://social.heldscal.la/avatar/s/201.jpeg",
+               "id" => 0
+             },
+             %{
+               "acct" => other_user.ap_id,
+               "avatar" => "https://social.heldscal.la/avatar/202.jpeg",
+               "avatar_static" => "https://social.heldscal.la/avatar/s/202.jpeg",
+               "id" => other_user.id
+             }
+           ]
+  end
+end
index da56061652f9e7b21cfeddf879eecd32e1f2c8e4..47357863c852ee012fae77462496db1bf223a7f4 100644 (file)
@@ -8,7 +8,6 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do
   alias Ecto.Changeset
   alias Pleroma.Config
   alias Pleroma.Notification
-  alias Pleroma.Object
   alias Pleroma.Repo
   alias Pleroma.Tests.ObanHelpers
   alias Pleroma.User
@@ -16,7 +15,6 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do
   alias Pleroma.Web.OAuth.App
   alias Pleroma.Web.Push
 
-  import ExUnit.CaptureLog
   import Pleroma.Factory
   import Swoosh.TestAssertions
   import Tesla.Mock
@@ -431,87 +429,6 @@ defmodule Pleroma.Web.MastodonAPI.MastodonAPIControllerTest do
     end
   end
 
-  describe "GET /api/v1/suggestions" do
-    setup do
-      user = insert(:user)
-      other_user = insert(:user)
-      host = Config.get([Pleroma.Web.Endpoint, :url, :host])
-      url500 = "http://test500?#{host}&#{user.nickname}"
-      url200 = "http://test200?#{host}&#{user.nickname}"
-
-      mock(fn
-        %{method: :get, url: ^url500} ->
-          %Tesla.Env{status: 500, body: "bad request"}
-
-        %{method: :get, url: ^url200} ->
-          %Tesla.Env{
-            status: 200,
-            body:
-              ~s([{"acct":"yj455","avatar":"https://social.heldscal.la/avatar/201.jpeg","avatar_static":"https://social.heldscal.la/avatar/s/201.jpeg"}, {"acct":"#{
-                other_user.ap_id
-              }","avatar":"https://social.heldscal.la/avatar/202.jpeg","avatar_static":"https://social.heldscal.la/avatar/s/202.jpeg"}])
-          }
-      end)
-
-      [user: user, other_user: other_user]
-    end
-
-    clear_config(:suggestions)
-
-    test "returns empty result when suggestions disabled", %{conn: conn, user: user} do
-      Config.put([:suggestions, :enabled], false)
-
-      res =
-        conn
-        |> assign(:user, user)
-        |> get("/api/v1/suggestions")
-        |> json_response(200)
-
-      assert res == []
-    end
-
-    test "returns error", %{conn: conn, user: user} do
-      Config.put([:suggestions, :enabled], true)
-      Config.put([:suggestions, :third_party_engine], "http://test500?{{host}}&{{user}}")
-
-      assert capture_log(fn ->
-               res =
-                 conn
-                 |> assign(:user, user)
-                 |> get("/api/v1/suggestions")
-                 |> json_response(500)
-
-               assert res == "Something went wrong"
-             end) =~ "Could not retrieve suggestions"
-    end
-
-    test "returns suggestions", %{conn: conn, user: user, other_user: other_user} do
-      Config.put([:suggestions, :enabled], true)
-      Config.put([:suggestions, :third_party_engine], "http://test200?{{host}}&{{user}}")
-
-      res =
-        conn
-        |> assign(:user, user)
-        |> get("/api/v1/suggestions")
-        |> json_response(200)
-
-      assert res == [
-               %{
-                 "acct" => "yj455",
-                 "avatar" => "https://social.heldscal.la/avatar/201.jpeg",
-                 "avatar_static" => "https://social.heldscal.la/avatar/s/201.jpeg",
-                 "id" => 0
-               },
-               %{
-                 "acct" => other_user.ap_id,
-                 "avatar" => "https://social.heldscal.la/avatar/202.jpeg",
-                 "avatar_static" => "https://social.heldscal.la/avatar/s/202.jpeg",
-                 "id" => other_user.id
-               }
-             ]
-    end
-  end
-
   describe "DELETE /auth/sign_out" do
     test "redirect to root page", %{conn: conn} do
       user = insert(:user)