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