1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Helpers.MediaHelper do
7 Handles common media-related operations.
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 {:ok, env} <- HTTP.get(url, [], pool: :media),
16 {:ok, fifo_path} <- mkfifo() do
17 args = List.flatten([fifo_path, args])
18 run_fifo(fifo_path, env, executable, args)
20 nil -> {:error, {:convert, :command_not_found}}
21 {:error, _} = error -> error
25 defp prepare_image_resize_args(
26 %{max_width: max_width, max_height: max_height, format: "png"} = options
28 quality = options[:quality] || 85
29 resize = Enum.join([max_width, "x", max_height, ">"])
42 defp prepare_image_resize_args(%{max_width: max_width, max_height: max_height} = options) do
43 quality = options[:quality] || 85
44 resize = Enum.join([max_width, "x", max_height, ">"])
59 defp prepare_image_resize_args(_), do: {:error, :missing_options}
61 # Note: video thumbnail is intentionally not resized (always has original dimensions)
62 def video_framegrab(url) do
63 with executable when is_binary(executable) <- System.find_executable("ffmpeg"),
64 {:ok, env} <- HTTP.get(url, [], pool: :media),
65 {:ok, fifo_path} <- mkfifo(),
78 run_fifo(fifo_path, env, executable, args)
80 nil -> {:error, {:ffmpeg, :command_not_found}}
81 {:error, _} = error -> error
85 defp run_fifo(fifo_path, env, executable, args) do
87 Port.open({:spawn_executable, executable}, [
95 fifo = Port.open(to_charlist(fifo_path), [:eof, :binary, :stream, :out])
96 fix = Pleroma.Helpers.QtFastStart.fix(env.body)
97 true = Port.command(fifo, fix)
98 :erlang.port_close(fifo)
105 path = Path.join(System.tmp_dir!(), "pleroma-media-preview-pipe-#{Ecto.UUID.generate()}")
107 case System.cmd("mkfifo", [path]) do
109 spawn(fifo_guard(path))
113 {:error, {:fifo_failed, err}}
117 defp fifo_guard(path) do
121 ref = Process.monitor(pid)
124 {:DOWN, ^ref, :process, ^pid, _} ->
130 defp loop_recv(pid) do
134 defp loop_recv(pid, acc) do
136 {^pid, {:data, data}} ->
137 loop_recv(pid, acc <> data)
139 {^pid, {:exit_status, 0}} ->
142 {^pid, {:exit_status, status}} ->
146 :erlang.port_close(pid)