Improve episode-level compatability with media center apps (#86)

* Add media profile presets (#85)

* Added presets for output templates

* Added presets for the entire media profile form

* Append `-thumb` to thumbnails when downloading (#87)

* Appended -thumb to thumbnails when downloading

* Added code to compensate for yt-dlp bug

* Squash all the commits from the other branch bc I broke things (#88)
This commit is contained in:
Kieran
2024-03-14 12:30:08 -07:00
committed by GitHub
parent 25eb772896
commit 0f3329e97d
28 changed files with 710 additions and 179 deletions
+1 -1
View File
@@ -2,7 +2,7 @@ defmodule Pinchflat.Boot.DataBackfillWorker do
@moduledoc false
use Oban.Worker,
queue: :media_local_metadata,
queue: :local_metadata,
unique: [period: :infinity, states: [:available, :scheduled, :retryable]],
tags: ["media_item", "media_metadata", "local_metadata", "data_backfill"]
@@ -18,7 +18,7 @@ defmodule Pinchflat.Downloading.DownloadOptionBuilder do
built_options =
default_options() ++
subtitle_options(media_profile) ++
thumbnail_options(media_profile) ++
thumbnail_options(media_item_with_preloads) ++
metadata_options(media_profile) ++
quality_options(media_profile) ++
output_options(media_item_with_preloads)
@@ -57,13 +57,16 @@ defmodule Pinchflat.Downloading.DownloadOptionBuilder do
end)
end
defp thumbnail_options(media_profile) do
defp thumbnail_options(media_item_with_preloads) do
media_profile = media_item_with_preloads.source.media_profile
mapped_struct = Map.from_struct(media_profile)
Enum.reduce(mapped_struct, [], fn attr, acc ->
case attr do
{:download_thumbnail, true} ->
acc ++ [:write_thumbnail, convert_thumbnail: "jpg"]
thumbnail_save_location = determine_thumbnail_location(media_item_with_preloads)
acc ++ [:write_thumbnail, convert_thumbnail: "jpg", output: "thumbnail:#{thumbnail_save_location}"]
{:embed_thumbnail, true} ->
acc ++ [:embed_thumbnail, convert_thumbnail: "jpg"]
@@ -102,15 +105,20 @@ defmodule Pinchflat.Downloading.DownloadOptionBuilder do
end
defp output_options(media_item_with_preloads) do
media_profile = media_item_with_preloads.source.media_profile
additional_options_map = output_options_map(media_item_with_preloads)
{:ok, output_path} = OutputPathBuilder.build(media_profile.output_path_template, additional_options_map)
output_path_template = media_item_with_preloads.source.media_profile.output_path_template
[
output: Path.join(base_directory(), output_path)
output: build_output_path(output_path_template, media_item_with_preloads)
]
end
defp build_output_path(string, media_item_with_preloads) do
additional_options_map = output_options_map(media_item_with_preloads)
{:ok, output_path} = OutputPathBuilder.build(string, additional_options_map)
Path.join(base_directory(), output_path)
end
defp output_options_map(media_item_with_preloads) do
source = media_item_with_preloads.source
@@ -120,6 +128,19 @@ defmodule Pinchflat.Downloading.DownloadOptionBuilder do
}
end
# I don't love the string manipulation here, but what can ya' do.
# It's dependent on the output_path_template being a string ending `.{{ ext }}`
# (or equivalent), but that's validated by the MediaProfile schema.
defp determine_thumbnail_location(media_item_with_preloads) do
output_path_template = media_item_with_preloads.source.media_profile.output_path_template
output_path_template
|> String.split(~r{\.}, include_captures: true)
|> List.insert_at(-3, "-thumb")
|> Enum.join()
|> build_output_path(media_item_with_preloads)
end
defp base_directory do
Application.get_env(:pinchflat, :media_directory)
end
@@ -40,7 +40,9 @@ defmodule Pinchflat.Downloading.OutputPathBuilder do
"upload_year" => "%(upload_date>%Y)S",
"upload_month" => "%(upload_date>%m)S",
"upload_day" => "%(upload_date>%d)S",
"upload_yyyy_mm_dd" => "%(upload_date>%Y-%m-%d)S"
"upload_yyyy_mm_dd" => "%(upload_date>%Y-%m-%d)S",
"season_from_date" => "%(upload_date>%Y)S",
"season_episode_from_date" => "s%(upload_date>%Y)Se%(upload_date>%m%d)S"
}
end
end
@@ -2,7 +2,7 @@ defmodule Pinchflat.Filesystem.FilesystemDataWorker do
@moduledoc false
use Oban.Worker,
queue: :media_local_metadata,
queue: :local_metadata,
tags: ["media_item", "media_metadata", "local_metadata"],
max_attempts: 1
@@ -13,6 +13,10 @@ defmodule Pinchflat.Filesystem.FilesystemDataWorker do
@doc """
For a given media item, compute and save metadata about the file on-disk.
IDEA: does this have to be a standalone job? I originally split it out
so a failure here wouldn't cause a downloader job retry, but I can match
for failures so it doesn't retry.
Returns :ok
"""
def perform(%Oban.Job{args: %{"id" => media_item_id}}) do
+6
View File
@@ -144,6 +144,8 @@ defmodule Pinchflat.Media do
@doc """
Produces a flat list of the filesystem paths for a media_item's downloaded files
NOTE: this can almost certainly be made private
Returns [binary()]
"""
def media_filepaths(media_item) do
@@ -162,6 +164,8 @@ defmodule Pinchflat.Media do
Produces a flat list of the filesystem paths for a media_item's metadata files.
Returns an empty list if the media_item has no metadata.
NOTE: this can almost certainly be made private
Returns [binary()] | []
"""
def metadata_filepaths(media_item) do
@@ -227,6 +231,7 @@ defmodule Pinchflat.Media do
def delete_media_item(%MediaItem{} = media_item, opts \\ []) do
delete_files = Keyword.get(opts, :delete_files, false)
# NOTE: this should delete metadata no matter what
if delete_files do
{:ok, _} = delete_all_attachments(media_item)
end
@@ -242,6 +247,7 @@ defmodule Pinchflat.Media do
MediaItem.changeset(media_item, attrs)
end
# NOTE: refactor this
defp delete_all_attachments(media_item) do
media_item = Repo.preload(media_item, :metadata)
+16 -3
View File
@@ -54,9 +54,22 @@ defmodule Pinchflat.Metadata.MetadataParser do
|> Enum.reverse()
|> Enum.find_value(fn attrs -> attrs["filepath"] end)
%{
thumbnail_filepath: thumbnail_filepath
}
if thumbnail_filepath do
# NOTE: whole ordeal needed due to a bug I found in yt-dlp
# https://github.com/yt-dlp/yt-dlp/issues/9445
# Can be reverted to remove this entire conditional once fixed
%{
thumbnail_filepath:
thumbnail_filepath
|> String.split(~r{\.}, include_captures: true)
|> List.insert_at(-3, "-thumb")
|> Enum.join()
}
else
%{
thumbnail_filepath: thumbnail_filepath
}
end
end
defp parse_infojson_metadata(metadata) do
+36
View File
@@ -0,0 +1,36 @@
defmodule Pinchflat.Metadata.SourceMetadata do
@moduledoc """
The SourceMetadata schema.
Look. Don't @ me about Metadata vs. Metadatum. I'm very sensitive.
"""
use Ecto.Schema
import Ecto.Changeset
alias Pinchflat.Sources.Source
@allowed_fields ~w(metadata_filepath)a
@required_fields ~w(metadata_filepath)a
schema "source_metadata" do
field :metadata_filepath, :string
belongs_to :source, Source
timestamps(type: :utc_datetime)
end
@doc false
def changeset(source_metadata, attrs) do
source_metadata
|> cast(attrs, @allowed_fields)
|> validate_required(@required_fields)
|> unique_constraint([:source_id])
end
@doc false
def filepath_attributes do
~w(metadata_filepath)a
end
end
@@ -0,0 +1,48 @@
defmodule Pinchflat.Metadata.SourceMetadataStorageWorker do
@moduledoc false
use Oban.Worker,
queue: :remote_metadata,
tags: ["media_source", "source_metadata", "remote_metadata"],
max_attempts: 1
alias __MODULE__
alias Pinchflat.Repo
alias Pinchflat.Tasks
alias Pinchflat.Sources
alias Pinchflat.YtDlp.MediaCollection
alias Pinchflat.Metadata.MetadataFileHelpers
@doc """
Starts the source metadata storage worker and creates a task for the source.
IDEA: testing out this method of handling job kickoff. I think I like it, so
I may use it in other places. Just testing it for now
Returns {:ok, %Task{}} | {:error, :duplicate_job} | {:error, %Ecto.Changeset{}}
"""
def kickoff_with_task(source) do
%{id: source.id}
|> SourceMetadataStorageWorker.new()
|> Tasks.create_job_with_task(source)
end
@impl Oban.Worker
@doc """
Fetches and stores metadata for a source in the secret metadata location.
Returns :ok
"""
def perform(%Oban.Job{args: %{"id" => source_id}}) do
source = Repo.preload(Sources.get_source!(source_id), :metadata)
{:ok, metadata} = MediaCollection.get_source_metadata(source.original_url)
Sources.update_source(source, %{
metadata: %{
metadata_filepath: MetadataFileHelpers.compress_and_store_metadata_for(source, metadata)
}
})
:ok
end
end
+9 -3
View File
@@ -35,14 +35,14 @@ defmodule Pinchflat.Profiles.MediaProfile do
field :download_subs, :boolean, default: false
field :download_auto_subs, :boolean, default: false
field :embed_subs, :boolean, default: true
field :embed_subs, :boolean, default: false
field :sub_langs, :string, default: "en"
field :download_thumbnail, :boolean, default: false
field :embed_thumbnail, :boolean, default: true
field :embed_thumbnail, :boolean, default: false
field :download_metadata, :boolean, default: false
field :embed_metadata, :boolean, default: true
field :embed_metadata, :boolean, default: false
field :download_nfo, :boolean, default: false
# NOTE: these do NOT speed up indexing - the indexer still has to go
@@ -67,6 +67,12 @@ defmodule Pinchflat.Profiles.MediaProfile do
media_profile
|> cast(attrs, @allowed_fields)
|> validate_required(@required_fields)
# Ensures it ends with `.{{ ext }}` or `.%(ext)s` or similar (with a little wiggle room)
|> validate_format(:output_path_template, ext_regex(), message: "must end with .{{ ext }}")
|> unique_constraint(:name)
end
defp ext_regex do
~r/\.({{ ?ext ?}}|%\( ?ext ?\)[sS])$/
end
end
+6 -1
View File
@@ -10,6 +10,7 @@ defmodule Pinchflat.Sources.Source do
alias Pinchflat.Tasks.Task
alias Pinchflat.Media.MediaItem
alias Pinchflat.Profiles.MediaProfile
alias Pinchflat.Metadata.SourceMetadata
@allowed_fields ~w(
collection_name
@@ -28,7 +29,8 @@ defmodule Pinchflat.Sources.Source do
# Expensive API calls are made when a source is inserted/updated so
# we want to ensure that the source is valid before making the call.
# This way, we check that the other attributes are valid before ensuring
# that all fields are valid.
# that all fields are valid. This is still only one DB insert but it's
# a two-stage validation process to fail fast before the API call.
@initially_required_fields ~w(
index_frequency_minutes
fast_index
@@ -60,6 +62,8 @@ defmodule Pinchflat.Sources.Source do
belongs_to :media_profile, MediaProfile
has_one :metadata, SourceMetadata, on_replace: :update
has_many :tasks, Task
has_many :media_items, MediaItem, foreign_key: :source_id
@@ -80,6 +84,7 @@ defmodule Pinchflat.Sources.Source do
|> cast(attrs, @allowed_fields)
|> dynamic_default(:custom_name, fn cs -> get_field(cs, :collection_name) end)
|> validate_required(required_fields)
|> cast_assoc(:metadata, with: &SourceMetadata.changeset/2, required: false)
|> unique_constraint([:collection_id, :media_profile_id])
end
+27 -10
View File
@@ -11,9 +11,11 @@ defmodule Pinchflat.Sources do
alias Pinchflat.Sources.Source
alias Pinchflat.Profiles.MediaProfile
alias Pinchflat.YtDlp.MediaCollection
alias Pinchflat.Metadata.SourceMetadata
alias Pinchflat.Downloading.DownloadingHelpers
alias Pinchflat.FastIndexing.FastIndexingHelpers
alias Pinchflat.SlowIndexing.SlowIndexingHelpers
alias Pinchflat.Metadata.SourceMetadataStorageWorker
@doc """
Returns the list of sources. Returns [%Source{}, ...]
@@ -54,7 +56,7 @@ defmodule Pinchflat.Sources do
case change_source(%Source{}, attrs, :initial) do
%Ecto.Changeset{valid?: true} ->
%Source{}
|> change_source_from_url(attrs)
|> maybe_change_source_from_url(attrs)
|> maybe_change_indexing_frequency()
|> commit_and_handle_tasks()
@@ -82,7 +84,7 @@ defmodule Pinchflat.Sources do
case change_source(source, attrs, :initial) do
%Ecto.Changeset{valid?: true} ->
source
|> change_source_from_url(attrs)
|> maybe_change_source_from_url(attrs)
|> maybe_change_indexing_frequency()
|> commit_and_handle_tasks()
@@ -107,6 +109,7 @@ defmodule Pinchflat.Sources do
end)
Tasks.delete_tasks_for(source)
delete_source_metadata_files(source)
Repo.delete(source)
end
@@ -122,14 +125,12 @@ defmodule Pinchflat.Sources do
fetches source details from the original_url (if provided). If the source
details cannot be fetched, an error is added to the changeset.
Note that this fetches source details as long as the `original_url` is present.
This means that it'll go for it even if a changeset is otherwise invalid. This
is pretty easy to change, but for MVP I'm not concerned.
NOTE: When operating in the ideal path, this effectively adds an API call
to the source creation/update process. Should be used only when needed.
NOTE: this can almost certainly be made private now
"""
def change_source_from_url(%Source{} = source, attrs) do
def maybe_change_source_from_url(%Source{} = source, attrs) do
case change_source(source, attrs) do
%Ecto.Changeset{changes: %{original_url: _}} = changeset ->
add_source_details_to_changeset(source, changeset)
@@ -139,6 +140,18 @@ defmodule Pinchflat.Sources do
end
end
defp delete_source_metadata_files(source) do
metadata = Repo.preload(source, :metadata).metadata || %SourceMetadata{}
mapped_struct = Map.from_struct(metadata)
filepaths =
SourceMetadata.filepath_attributes()
|> Enum.map(fn field -> mapped_struct[field] end)
|> Enum.filter(&is_binary/1)
Enum.each(filepaths, &File.rm/1)
end
defp add_source_details_to_changeset(source, changeset) do
%Ecto.Changeset{changes: changes} = changeset
@@ -196,6 +209,9 @@ defmodule Pinchflat.Sources do
{:ok, %Source{} = source} ->
maybe_handle_media_tasks(changeset, source)
maybe_run_indexing_task(changeset, source)
run_metadata_storage_task(source)
{:ok, source}
err ->
err
@@ -215,8 +231,6 @@ defmodule Pinchflat.Sources do
_ ->
:ok
end
{:ok, source}
end
defp maybe_run_indexing_task(changeset, source) do
@@ -231,8 +245,11 @@ defmodule Pinchflat.Sources do
maybe_update_slow_indexing_task(changeset, source)
maybe_update_fast_indexing_task(changeset, source)
end
end
{:ok, source}
# This runs every time to pick up any changes to the metadata
defp run_metadata_storage_task(source) do
SourceMetadataStorageWorker.kickoff_with_task(source)
end
defp maybe_update_slow_indexing_task(changeset, source) do
+2
View File
@@ -20,6 +20,8 @@ defmodule Pinchflat.Tasks do
Returns the list of tasks for a given record type and ID. Optionally allows you to specify
which worker or job states to include.
IDEA: this should be updated to take a struct instead of a record type and ID
Returns [%Task{}, ...]
"""
def list_tasks_for(attached_record_type, attached_record_id, worker_name \\ nil, job_states \\ Oban.Job.states()) do
+30 -2
View File
@@ -50,8 +50,8 @@ defmodule Pinchflat.YtDlp.MediaCollection do
@doc """
Gets a source's ID and name from its URL.
yt-dlp does not _really_ have source-specific functions, so
instead we're fetching just the first video (using playlist_end: 1)
yt-dlp does not _really_ have source-specific functions that return what
we need, so instead we're fetching just the first video (using playlist_end: 1)
and parsing the source ID and name from _its_ metadata
Returns {:ok, map()} | {:error, any, ...}.
@@ -71,7 +71,35 @@ defmodule Pinchflat.YtDlp.MediaCollection do
end
end
@doc """
Gets a source's metadata from its URL.
This is mostly for things like getting the source's avatar and banner image
(if applicable). However, this yt-dlp call doesn't have enough overlap with
`get_source_details/1` to allow combining them - this one has _almost_ everything
we need, but it doesn't contain enough information to tell 100% if the url is a channel
or a playlist.
The main purpose of this (past using as a fetcher for _other_ metadata) is to live
as a compressed blob for possible future use. That's why it's not getting formatted like
`get_source_details/1`
Returns {:ok, map()} | {:error, any, ...}.
"""
def get_source_metadata(source_url) do
opts = [playlist_items: 0]
output_template = "playlist:%()j"
with {:ok, output} <- backend_runner().run(source_url, opts, output_template),
{:ok, parsed_json} <- Phoenix.json_library().decode(output) do
{:ok, parsed_json}
else
err -> err
end
end
defp format_source_details(response) do
# NOTE: I should probably make this a struct some day
%{
channel_id: response["channel_id"],
channel_name: response["channel"],