4f618743df776535231bd4ddd633c952d67606e5
[akkoma] / lib / pleroma / web / web.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 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 import Plug.Conn
27 import Pleroma.Web.Gettext
28 import Pleroma.Web.Router.Helpers
29
30 plug(:put_layout, Application.get_env(:pleroma, :app_template, "app.html"))
31 end
32 end
33
34 def view do
35 quote do
36 use Phoenix.View,
37 root: "lib/pleroma/web/templates",
38 namespace: Pleroma.Web
39
40 # Import convenience functions from controllers
41 import Phoenix.Controller, only: [get_csrf_token: 0, get_flash: 2, view_module: 1]
42
43 import Pleroma.Web.ErrorHelpers
44 import Pleroma.Web.Gettext
45 import Pleroma.Web.Router.Helpers
46
47 require Logger
48
49 @doc "Same as `render/3` but wrapped in a rescue block"
50 def safe_render(view, template, assigns \\ %{}) do
51 Phoenix.View.render(view, template, assigns)
52 rescue
53 error ->
54 Logger.error(
55 "#{__MODULE__} failed to render #{inspect({view, template})}: #{inspect(error)}"
56 )
57
58 Logger.error(inspect(__STACKTRACE__))
59 nil
60 end
61
62 @doc """
63 Same as `render_many/4` but wrapped in rescue block.
64 """
65 def safe_render_many(collection, view, template, assigns \\ %{}) do
66 Enum.map(collection, fn resource ->
67 as = Map.get(assigns, :as) || view.__resource__
68 assigns = Map.put(assigns, as, resource)
69 safe_render(view, template, assigns)
70 end)
71 |> Enum.filter(& &1)
72 end
73 end
74 end
75
76 def router do
77 quote do
78 use Phoenix.Router
79 # credo:disable-for-next-line Credo.Check.Consistency.MultiAliasImportRequireUse
80 import Plug.Conn
81 import Phoenix.Controller
82 end
83 end
84
85 def channel do
86 quote do
87 # credo:disable-for-next-line Credo.Check.Consistency.MultiAliasImportRequireUse
88 use Phoenix.Channel
89 import Pleroma.Web.Gettext
90 end
91 end
92
93 @doc """
94 When used, dispatch to the appropriate controller/view/etc.
95 """
96 defmacro __using__(which) when is_atom(which) do
97 apply(__MODULE__, which, [])
98 end
99
100 def base_url do
101 Pleroma.Web.Endpoint.url()
102 end
103 end