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.
10 @tmp_base "/tmp/pleroma-media_preview-pipe"
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() do
18 args = List.flatten([fifo_path, args])
19 run_fifo(fifo_path, env, executable, args)
21 nil -> {:error, {:convert, :command_not_found}}
22 {:error, _} = error -> error
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, ">"])
43 defp prepare_image_resize_args(_), do: {:error, :missing_options}
45 def video_framegrab(url) do
46 with executable when is_binary(executable) <- System.find_executable("ffmpeg"),
47 url = Pleroma.Web.MediaProxy.url(url),
48 {:ok, env} <- Pleroma.HTTP.get(url),
49 {:ok, fifo_path} <- mkfifo(),
62 run_fifo(fifo_path, env, executable, args)
64 nil -> {:error, {:ffmpeg, :command_not_found}}
65 {:error, _} = error -> error
69 defp run_fifo(fifo_path, env, executable, args) do
71 Port.open({:spawn_executable, executable}, [
79 fifo = Port.open(to_charlist(fifo_path), [:eof, :binary, :stream, :out])
80 fix = Pleroma.Helpers.QtFastStart.fix(env.body)
81 true = Port.command(fifo, fix)
82 :erlang.port_close(fifo)
89 path = "#{@tmp_base}#{to_charlist(:erlang.phash2(self()))}"
91 case System.cmd("mkfifo", [path]) do
93 spawn(fifo_guard(path))
97 {:error, {:fifo_failed, err}}
101 defp fifo_guard(path) do
105 ref = Process.monitor(pid)
108 {:DOWN, ^ref, :process, ^pid, _} ->
114 defp loop_recv(pid) do
118 defp loop_recv(pid, acc) do
120 {^pid, {:data, data}} ->
121 loop_recv(pid, acc <> data)
123 {^pid, {:exit_status, 0}} ->
126 {^pid, {:exit_status, status}} ->
130 :erlang.port_close(pid)