Merge branch 'exclude-reblogs-from-admin-api-by-default' into 'develop'
[akkoma] / lib / pleroma / web / web.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web do
6 @moduledoc """
7 A module that keeps using definitions for controllers,
8 views and so on.
9
10 This can be used in your application as:
11
12 use Pleroma.Web, :controller
13 use Pleroma.Web, :view
14
15 The definitions below will be executed for every view,
16 controller, etc, so keep them short and clean, focused
17 on imports, uses and aliases.
18
19 Do NOT define functions inside the quoted expressions
20 below.
21 """
22
23 def controller do
24 quote do
25 use Phoenix.Controller, namespace: Pleroma.Web
26
27 import Plug.Conn
28 import Pleroma.Web.Gettext
29 import Pleroma.Web.Router.Helpers
30 import Pleroma.Web.TranslationHelpers
31
32 plug(:set_put_layout)
33
34 defp set_put_layout(conn, _) do
35 put_layout(conn, Pleroma.Config.get(:app_layout, "app.html"))
36 end
37 end
38 end
39
40 def view do
41 quote do
42 use Phoenix.View,
43 root: "lib/pleroma/web/templates",
44 namespace: Pleroma.Web
45
46 # Import convenience functions from controllers
47 import Phoenix.Controller, only: [get_csrf_token: 0, get_flash: 2, view_module: 1]
48
49 import Pleroma.Web.ErrorHelpers
50 import Pleroma.Web.Gettext
51 import Pleroma.Web.Router.Helpers
52
53 require Logger
54
55 @doc "Same as `render/3` but wrapped in a rescue block"
56 def safe_render(view, template, assigns \\ %{}) do
57 Phoenix.View.render(view, template, assigns)
58 rescue
59 error ->
60 Logger.error(
61 "#{__MODULE__} failed to render #{inspect({view, template})}\n" <>
62 Exception.format(:error, error, __STACKTRACE__)
63 )
64
65 nil
66 end
67
68 @doc """
69 Same as `render_many/4` but wrapped in rescue block.
70 """
71 def safe_render_many(collection, view, template, assigns \\ %{}) do
72 Enum.map(collection, fn resource ->
73 as = Map.get(assigns, :as) || view.__resource__
74 assigns = Map.put(assigns, as, resource)
75 safe_render(view, template, assigns)
76 end)
77 |> Enum.filter(& &1)
78 end
79 end
80 end
81
82 def router do
83 quote do
84 use Phoenix.Router
85 # credo:disable-for-next-line Credo.Check.Consistency.MultiAliasImportRequireUse
86 import Plug.Conn
87 import Phoenix.Controller
88 end
89 end
90
91 def channel do
92 quote do
93 # credo:disable-for-next-line Credo.Check.Consistency.MultiAliasImportRequireUse
94 use Phoenix.Channel
95 import Pleroma.Web.Gettext
96 end
97 end
98
99 @doc """
100 When used, dispatch to the appropriate controller/view/etc.
101 """
102 defmacro __using__(which) when is_atom(which) do
103 apply(__MODULE__, which, [])
104 end
105
106 def base_url do
107 Pleroma.Web.Endpoint.url()
108 end
109 end