1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.MastodonAPI.SearchController do
6 use Pleroma.Web, :controller
9 alias Pleroma.Plugs.RateLimiter
12 alias Pleroma.Web.ControllerHelper
13 alias Pleroma.Web.MastodonAPI.AccountView
14 alias Pleroma.Web.MastodonAPI.StatusView
17 plug(RateLimiter, :search when action in [:search, :search2, :account_search])
19 def search2(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
20 accounts = with_fallback(fn -> User.search(query, search_options(params, user)) end, [])
21 statuses = with_fallback(fn -> Activity.search(user, query) end, [])
23 tags_path = Web.base_url() <> "/tag/"
28 |> Enum.map(fn tag -> %{name: tag, url: tags_path <> tag} end)
31 "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
33 StatusView.render("index.json", activities: statuses, for: user, as: :activity),
40 def search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
41 accounts = with_fallback(fn -> User.search(query, search_options(params, user)) end)
42 statuses = with_fallback(fn -> Activity.search(user, query) end)
44 tags = prepare_tags(query)
47 "accounts" => AccountView.render("accounts.json", users: accounts, for: user, as: :user),
49 StatusView.render("index.json", activities: statuses, for: user, as: :activity),
56 def account_search(%{assigns: %{user: user}} = conn, %{"q" => query} = params) do
57 accounts = User.search(query, search_options(params, user))
58 res = AccountView.render("accounts.json", users: accounts, for: user, as: :user)
63 defp prepare_tags(query) do
67 |> Enum.filter(fn tag -> String.starts_with?(tag, "#") end)
68 |> Enum.map(fn tag -> String.slice(tag, 1..-1) end)
71 defp search_options(params, user) do
73 resolve: params["resolve"] == "true",
74 following: params["following"] == "true",
75 limit: ControllerHelper.fetch_integer_param(params, "limit"),
76 offset: ControllerHelper.fetch_integer_param(params, "offset"),
81 defp with_fallback(f, fallback \\ []) do
86 Logger.error("#{__MODULE__} search error: #{inspect(error)}")