total rebase
[anni] / lib / pleroma / upload / filter / exiftool / read_description.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Upload.Filter.Exiftool.ReadDescription do
6   @moduledoc """
7   Gets a valid description from the related EXIF tags and provides them in the response if no description is provided yet.
8   It will first check ImageDescription, when that doesn't probide a valid description, it will check iptc:Caption-Abstract.
9   A valid description means the fields are filled in and not too long (see `:instance, :description_limit`).
10   """
11   @behaviour Pleroma.Upload.Filter
12
13   def filter(%Pleroma.Upload{description: description})
14       when is_binary(description),
15       do: {:ok, :noop}
16
17   def filter(%Pleroma.Upload{tempfile: file} = upload),
18     do: {:ok, :filtered, upload |> Map.put(:description, read_description_from_exif_data(file))}
19
20   def filter(_, _), do: {:ok, :noop}
21
22   defp read_description_from_exif_data(file) do
23     nil
24     |> read_when_empty(file, "-ImageDescription")
25     |> read_when_empty(file, "-iptc:Caption-Abstract")
26   end
27
28   defp read_when_empty(current_description, _, _) when is_binary(current_description),
29     do: current_description
30
31   defp read_when_empty(_, file, tag) do
32     try do
33       {tag_content, 0} =
34         System.cmd("exiftool", ["-b", "-s3", tag, file],
35           stderr_to_stdout: false,
36           parallelism: true
37         )
38
39       tag_content = String.trim(tag_content)
40
41       if tag_content != "" and
42            String.length(tag_content) <=
43              Pleroma.Config.get([:instance, :description_limit]),
44          do: tag_content,
45          else: nil
46     rescue
47       _ in ErlangError -> nil
48     end
49   end
50 end