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