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 {:ok, env} <- Pleroma.HTTP.get(url, [], [adapter: [pool: :preview]]),
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 def video_framegrab(url) do
62 with executable when is_binary(executable) <- System.find_executable("ffmpeg"),
63 {:ok, env} <- Pleroma.HTTP.get(url, [], [adapter: [pool: :preview]]),
64 {:ok, fifo_path} <- mkfifo(),
77 run_fifo(fifo_path, env, executable, args)
79 nil -> {:error, {:ffmpeg, :command_not_found}}
80 {:error, _} = error -> error
84 defp run_fifo(fifo_path, env, executable, args) do
86 Port.open({:spawn_executable, executable}, [
94 fifo = Port.open(to_charlist(fifo_path), [:eof, :binary, :stream, :out])
95 fix = Pleroma.Helpers.QtFastStart.fix(env.body)
96 true = Port.command(fifo, fix)
97 :erlang.port_close(fifo)
104 path = "#{@tmp_base}#{to_charlist(:erlang.phash2(self()))}"
106 case System.cmd("mkfifo", [path]) do
108 spawn(fifo_guard(path))
112 {:error, {:fifo_failed, err}}
116 defp fifo_guard(path) do
120 ref = Process.monitor(pid)
123 {:DOWN, ^ref, :process, ^pid, _} ->
129 defp loop_recv(pid) do
133 defp loop_recv(pid, acc) do
135 {^pid, {:data, data}} ->
136 loop_recv(pid, acc <> data)
138 {^pid, {:exit_status, 0}} ->
141 {^pid, {:exit_status, status}} ->
145 :erlang.port_close(pid)