Move arg for images to the list so we can reuse these fifo functions for videos
[akkoma] / lib / pleroma / helpers / media_helper.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.Helpers.MediaHelper do
6 @moduledoc """
7 Handles common media-related operations.
8 """
9
10 @tmp_base "/tmp/pleroma-media_preview-pipe"
11
12 def image_resize(url, options) do
13 with executable when is_binary(executable) <- System.find_executable("convert"),
14 {:ok, args} <- prepare_image_resize_args(options),
15 url = Pleroma.Web.MediaProxy.url(url),
16 {:ok, env} <- Pleroma.HTTP.get(url),
17 {:ok, fifo_path} <- mkfifo()
18 do
19 run_fifo(fifo_path, env, executable, args)
20 else
21 nil -> {:error, {:convert, :command_not_found}}
22 {:error, _} = error -> error
23 end
24 end
25
26 defp prepare_image_resize_args(%{max_width: max_width, max_height: max_height} = options) do
27 quality = options[:quality] || 85
28 resize = Enum.join([max_width, "x", max_height, ">"])
29 args = [
30 "-interlace", "Plane",
31 "-resize", resize,
32 "-quality", to_string(quality),
33 "jpg:-"
34 ]
35 {:ok, args}
36 end
37
38 defp prepare_image_resize_args(_), do: {:error, :missing_options}
39
40 defp run_fifo(fifo_path, env, executable, args) do
41 args = List.flatten([fifo_path, args])
42 pid = Port.open({:spawn_executable, executable}, [:use_stdio, :stream, :exit_status, :binary, args: args])
43 fifo = Port.open(to_charlist(fifo_path), [:eof, :binary, :stream, :out])
44 true = Port.command(fifo, env.body)
45 :erlang.port_close(fifo)
46 loop_recv(pid)
47 after
48 File.rm(fifo_path)
49 end
50
51 defp mkfifo() do
52 path = "#{@tmp_base}#{to_charlist(:erlang.phash2(self()))}"
53 case System.cmd("mkfifo", [path]) do
54 {_, 0} ->
55 spawn(fifo_guard(path))
56 {:ok, path}
57 {_, err} ->
58 {:error, {:fifo_failed, err}}
59 end
60 end
61
62 defp fifo_guard(path) do
63 pid = self()
64 fn() ->
65 ref = Process.monitor(pid)
66 receive do
67 {:DOWN, ^ref, :process, ^pid, _} ->
68 File.rm(path)
69 end
70 end
71 end
72
73 defp loop_recv(pid) do
74 loop_recv(pid, <<>>)
75 end
76
77 defp loop_recv(pid, acc) do
78 receive do
79 {^pid, {:data, data}} ->
80 loop_recv(pid, acc <> data)
81 {^pid, {:exit_status, 0}} ->
82 {:ok, acc}
83 {^pid, {:exit_status, status}} ->
84 {:error, status}
85 after
86 5000 ->
87 :erlang.port_close(pid)
88 {:error, :timeout}
89 end
90 end
91 end