pinchflat/lib/pinchflat/metadata/metadata_file_helpers.ex
Kieran 25eb772896
Add support for episode NFO files (#84)
* Added nfo builder for 'episodes'

* Added NFO download fields; hooked up NFO generation to downloading pipeline

* Added NFO option to media profile
2024-03-13 11:31:53 -07:00

84 lines
2.5 KiB
Elixir

defmodule Pinchflat.Metadata.MetadataFileHelpers do
@moduledoc """
Provides methods for creating/downloading/storing related metadata
out-of-band of the normal yt-dlp backend process.
The idea is that I don't want to craft a complicated yt-dlp command,
instead focusing on downloading the media as the user wants it then
I can use the result of that here to grab the additional information
needed
"""
alias Pinchflat.Filesystem.FilesystemHelpers
@doc """
Compresses and stores metadata for a media item, returning the filepath.
Returns binary()
"""
def compress_and_store_metadata_for(database_record, metadata_map) do
filepath = generate_filepath_for(database_record, "metadata.json.gz")
{:ok, json} = Phoenix.json_library().encode(metadata_map)
:ok = FilesystemHelpers.write_p!(filepath, json, [:compressed])
filepath
end
@doc """
Reads and decodes compressed metadata from a filepath.
Returns {:ok, map()} | {:error, any}
"""
def read_compressed_metadata(filepath) do
{:ok, json} = File.open(filepath, [:read, :compressed], &IO.read(&1, :all))
Phoenix.json_library().decode(json)
end
@doc """
Downloads and stores a thumbnail for a media item, returning the filepath.
Returns binary()
"""
def download_and_store_thumbnail_for(database_record, metadata_map) do
thumbnail_url = metadata_map["thumbnail"]
filepath = generate_filepath_for(database_record, Path.basename(thumbnail_url))
thumbnail_blob = fetch_thumbnail_from_url(thumbnail_url)
:ok = FilesystemHelpers.write_p!(filepath, thumbnail_blob)
filepath
end
@doc """
Parses an upload date from the YYYYMMDD string returned in yt-dlp metadata
and returns a Date struct.
Returns Date.t()
"""
def parse_upload_date(upload_date) do
<<year::binary-size(4)>> <> <<month::binary-size(2)>> <> <<day::binary-size(2)>> = upload_date
Date.from_iso8601!("#{year}-#{month}-#{day}")
end
defp fetch_thumbnail_from_url(url) do
http_client = Application.get_env(:pinchflat, :http_client, Pinchflat.HTTP.HTTPClient)
{:ok, body} = http_client.get(url, [], body_format: :binary)
body
end
defp generate_filepath_for(database_record, filename) do
metadata_directory = Application.get_env(:pinchflat, :metadata_directory)
record_table_name = database_record.__meta__.source
Path.join([
metadata_directory,
record_table_name,
to_string(database_record.id),
filename
])
end
end