2020-01-22 22:40:40 +01:00
|
|
|
defmodule Mobilizon.Federation.ActivityStream.Converter.Picture do
|
2019-09-22 18:29:13 +02:00
|
|
|
@moduledoc """
|
|
|
|
Picture converter.
|
|
|
|
|
|
|
|
This module allows to convert events from ActivityStream format to our own
|
|
|
|
internal one, and back.
|
|
|
|
"""
|
|
|
|
|
2020-01-28 19:18:33 +01:00
|
|
|
alias Mobilizon.Media
|
2019-09-22 18:29:13 +02:00
|
|
|
alias Mobilizon.Media.Picture, as: PictureModel
|
|
|
|
|
2020-01-28 19:18:33 +01:00
|
|
|
alias Mobilizon.Web.Upload
|
|
|
|
|
2020-02-18 08:57:00 +01:00
|
|
|
@http_options [
|
|
|
|
ssl: [{:versions, [:"tlsv1.2"]}]
|
|
|
|
]
|
|
|
|
|
2019-09-22 18:29:13 +02:00
|
|
|
@doc """
|
|
|
|
Convert a picture struct to an ActivityStream representation.
|
|
|
|
"""
|
|
|
|
@spec model_to_as(PictureModel.t()) :: map
|
|
|
|
def model_to_as(%PictureModel{file: file}) do
|
|
|
|
%{
|
|
|
|
"type" => "Document",
|
2019-12-03 11:29:51 +01:00
|
|
|
"mediaType" => file.content_type,
|
|
|
|
"url" => file.url,
|
2019-09-22 18:29:13 +02:00
|
|
|
"name" => file.name
|
|
|
|
}
|
|
|
|
end
|
2019-12-03 11:29:51 +01:00
|
|
|
|
|
|
|
@doc """
|
|
|
|
Save picture data from raw data and return AS Link data.
|
|
|
|
"""
|
|
|
|
def find_or_create_picture(%{"type" => "Link", "href" => url}, actor_id),
|
|
|
|
do: find_or_create_picture(url, actor_id)
|
|
|
|
|
|
|
|
def find_or_create_picture(
|
|
|
|
%{"type" => "Document", "url" => picture_url, "name" => name},
|
|
|
|
actor_id
|
|
|
|
)
|
|
|
|
when is_bitstring(picture_url) do
|
2020-07-09 17:24:28 +02:00
|
|
|
with {:ok, %{body: body}} <- Tesla.get(picture_url, opts: @http_options),
|
2020-01-22 22:40:40 +01:00
|
|
|
{:ok, %{name: name, url: url, content_type: content_type, size: size}} <-
|
2020-01-28 19:18:33 +01:00
|
|
|
Upload.store(%{body: body, name: name}),
|
|
|
|
{:picture_exists, nil} <- {:picture_exists, Media.get_picture_by_url(url)} do
|
|
|
|
Media.create_picture(%{
|
2019-12-03 11:29:51 +01:00
|
|
|
"file" => %{
|
|
|
|
"url" => url,
|
|
|
|
"name" => name,
|
|
|
|
"content_type" => content_type,
|
|
|
|
"size" => size
|
|
|
|
},
|
|
|
|
"actor_id" => actor_id
|
|
|
|
})
|
|
|
|
else
|
|
|
|
{:picture_exists, %PictureModel{file: _file} = picture} ->
|
|
|
|
{:ok, picture}
|
|
|
|
|
|
|
|
err ->
|
|
|
|
err
|
|
|
|
end
|
|
|
|
end
|
2019-09-22 18:29:13 +02:00
|
|
|
end
|