Compare commits

..

21 Commits

Author SHA1 Message Date
Kieran Eglin 75fb1a6ab9 Bumped version 2024-11-27 10:43:07 -08:00
Kieran 652fcccb4a [Enhancement] Add audio track language selection to Media Profile (#487)
* Moved quality options to their own module

* Added language and format selection to quality option builder

* [WIP] migrating tests

* Added audio_lang to media_profile table

* Renamed column; added format options and tests

* Adds UI for audio_track to the media profile form

* Adds a version string to in-app streams to help with cache busting
2024-11-27 10:39:29 -08:00
Kieran bfb27427ce [Bugfix] Ensure livestreams aren't downloaded until they're finished processing (#485)
* Added logic to ignore downloads that aren't in the right live state

* Added tests for get_downloadable_status method

* Added tests for media downloader module

* Added tests to download worker modeule
2024-11-26 11:56:33 -08:00
Kieran d9c48370df [Enhancement] Adds ability to enable/disable sources (#481)
* [Unrelated] updated module name for existing liveview module

* Updated toggle component and moved MP index table to a liveview

* [WIP] reverted MP index table; added source count to MP index

* Moved new live table to sources index

* Added 'enabled' boolean to sources

* Got 'enabled' logic working re: downloading pending media

* Updated sources context to do the right thing when a source is updated

* Docs and tests

* Updated slow indexing to maintain its old schedule if re-enabled

* Hooked up the enabled toggle to the sources page

* [Unrelated] added direct links to various tabs on the sources table

* More tests

* Removed unneeded guard in

* Removed outdated comment
2024-11-21 14:38:37 -08:00
Duong Nguyen 4c8c0461be [Enhancement] Add option to use existing Media Profile as template for new profile (#466)
* Add option to use existing Media Profile as template for new profile

* Forgot to commit the edit form too

* Reset deletion mark on Source controller

* Add test for new preload profile feature

* mix check
2024-11-20 10:25:53 -08:00
Kieran a02f71f304 [Enhancement] Add support for yt-dlp plugins + add lifecycle script event for app boot (#465)
* Added new script type to pre-job startup tasks

* Updated Dockerfile to create the needful directories

* added tests
2024-11-08 15:38:00 -08:00
Kieran 83c10b2b00 [Enhancement] Track the predicted final filepath for indexed media items (#461)
* Added ability to pass additional yt-dlp options to indexing step

* Added predicted_filename to media struct

* WIP added ability to predict filepath to source indexing

* renamed predicted_filepath

* Added the ability to predict filepath when fast indexing

* Add predicted_media_filepath to media items table

* Addressed TODOs
2024-11-08 09:42:59 -08:00
Kieran Eglin 8c0dd0bb6b Bumped version 2024-10-30 14:13:08 -07:00
Kieran Eglin 7a374f1162 Updated README 2024-10-30 14:12:29 -07:00
Kieran a5afcf168b Went back to using original_url over webpage_url to improve short detection (#447) 2024-10-30 14:09:28 -07:00
Kieran Eglin 2f83fe03d2 Updated default tzdata location to prevent needless pulls every time I push a new version 2024-10-30 10:18:03 -07:00
Kieran Eglin 3c10d78e78 Updated timezone logic to prevent boot crash 2024-10-30 10:14:04 -07:00
Kieran 8c0df65c0c Took the easy way out and removed playlist index explicitly from the update method (#442) 2024-10-28 10:26:31 -07:00
Kieran 47bb1cb98d Updated timezone logic to not prevent booting (#441) 2024-10-28 09:15:45 -07:00
Kieran Eglin 20547e60e4 Bump version 2024-10-25 11:42:16 -07:00
Kieran 0fd3106cb8 Removed root pw workaround (#437) 2024-10-25 11:17:16 -07:00
Kieran 108a141c65 Improve error messages when adding a non-valid source URL (#436) 2024-10-25 11:01:46 -07:00
Kieran 6a1b7b0160 [Enhancement] Misc. UI updates (#434)
* Format 'Scheduled At' in task table according to user's TZ

* Changed video preview layout to 1 column on all displays

* Made links in descriptions clickable

* Updated Copy JSON button to properly escape newline characters
2024-10-24 12:47:48 -07:00
Kieran 3c8d99196a [Bugfix] Fix off-by-1 error for retention date logic (#432)
* Added a sanity check test to the media context

* Improves logic for handing media item culling dates
2024-10-24 10:26:30 -07:00
Jonas Bergler cae86953a0 document that BASE_ROUTE_PATH requires the prefix to be stripped (#413) 2024-10-22 12:24:34 -07:00
FibreTTP f661747a0c Flip settings submenu chevron (#405) 2024-10-10 14:19:03 -07:00
69 changed files with 1359 additions and 330 deletions
+5 -8
View File
@@ -53,7 +53,7 @@ If it doesn't work for your use case, please make a feature request! You can als
- Self-contained - just one Docker container with no external dependencies - Self-contained - just one Docker container with no external dependencies
- Powerful naming system so content is stored where and how you want it - Powerful naming system so content is stored where and how you want it
- Easy-to-use web interface with presets to get you started right away - Easy-to-use web interface with presets to get you started right away
- First-class support for media center apps like Plex, Jellyfin, and Kodi - First-class support for media center apps like Plex, Jellyfin, and Kodi ([docs](https://github.com/kieraneglin/pinchflat/wiki/Frequently-Asked-Questions#how-do-i-get-media-into-plexjellyfinkodi))
- Supports serving RSS feeds to your favourite podcast app ([docs](https://github.com/kieraneglin/pinchflat/wiki/Podcast-RSS-Feeds)) - Supports serving RSS feeds to your favourite podcast app ([docs](https://github.com/kieraneglin/pinchflat/wiki/Podcast-RSS-Feeds))
- Automatically downloads new content from channels and playlists - Automatically downloads new content from channels and playlists
- Uses a novel approach to download new content more quickly than other apps - Uses a novel approach to download new content more quickly than other apps
@@ -63,7 +63,7 @@ If it doesn't work for your use case, please make a feature request! You can als
- Allows automatically redownloading new media after a set period - Allows automatically redownloading new media after a set period
- This can help improve the download quality of new content or improve SponsorBlock tags - This can help improve the download quality of new content or improve SponsorBlock tags
- Optionally automatically delete old content ([docs](https://github.com/kieraneglin/pinchflat/wiki/Automatically-Delete-Media)) - Optionally automatically delete old content ([docs](https://github.com/kieraneglin/pinchflat/wiki/Automatically-Delete-Media))
- Advanced options like setting cutoff dates and filtering by title - Advanced options like setting cutoff dates and filtering by title ([docs](https://github.com/kieraneglin/pinchflat/wiki/Frequently-Asked-Questions#i-only-want-certain-videos-from-a-source---how-can-i-only-download-those))
- Reliable hands-off operation - Reliable hands-off operation
- Can pass cookies to YouTube to download your private playlists ([docs](https://github.com/kieraneglin/pinchflat/wiki/YouTube-Cookies)) - Can pass cookies to YouTube to download your private playlists ([docs](https://github.com/kieraneglin/pinchflat/wiki/YouTube-Cookies))
- Sponsorblock integration - Sponsorblock integration
@@ -131,9 +131,6 @@ You _must_ ensure the host directories you've mounted are writable by the user r
> [!IMPORTANT] > [!IMPORTANT]
> It's not recommended to run the container as root. Doing so can create permission issues if other apps need to work with the downloaded media. > It's not recommended to run the container as root. Doing so can create permission issues if other apps need to work with the downloaded media.
> [!TIP]
> If you need to run any command as root, you can run `su` from the container's shell as there is no password set for the root user.
### ADVANCED: Storing Pinchflat config directory on a network share ### ADVANCED: Storing Pinchflat config directory on a network share
As pointed out in [#137](https://github.com/kieraneglin/pinchflat/issues/137), SQLite doesn't like being run in WAL mode on network shares. If you're running Pinchflat on a network share, you can disable WAL mode by setting the `JOURNAL_MODE` environment variable to `delete`. This will make Pinchflat run in rollback journal mode which is less performant but should work on network shares. As pointed out in [#137](https://github.com/kieraneglin/pinchflat/issues/137), SQLite doesn't like being run in WAL mode on network shares. If you're running Pinchflat on a network share, you can disable WAL mode by setting the `JOURNAL_MODE` environment variable to `delete`. This will make Pinchflat run in rollback journal mode which is less performant but should work on network shares.
@@ -155,7 +152,7 @@ If you change this setting and it works well for you, please leave a comment on
| `ENABLE_IPV6` | No | `false` | Setting to _any_ non-blank value will enable IPv6 | | `ENABLE_IPV6` | No | `false` | Setting to _any_ non-blank value will enable IPv6 |
| `JOURNAL_MODE` | No | `wal` | Set to `delete` if your config directory is stored on a network share (not recommended) | | `JOURNAL_MODE` | No | `wal` | Set to `delete` if your config directory is stored on a network share (not recommended) |
| `TZ_DATA_DIR` | No | `/etc/elixir_tzdata_data` | The container path where the timezone database is stored | | `TZ_DATA_DIR` | No | `/etc/elixir_tzdata_data` | The container path where the timezone database is stored |
| `BASE_ROUTE_PATH` | No | `/` | The base path for route generation. Useful when running behind certain reverse proxies | | `BASE_ROUTE_PATH` | No | `/` | The base path for route generation. Useful when running behind certain reverse proxies, but prefix must be stripped. |
| `YT_DLP_WORKER_CONCURRENCY` | No | `2` | The number of concurrent workers that use `yt-dlp` _per queue_. Set to 1 if you're getting IP limited, otherwise don't touch it | | `YT_DLP_WORKER_CONCURRENCY` | No | `2` | The number of concurrent workers that use `yt-dlp` _per queue_. Set to 1 if you're getting IP limited, otherwise don't touch it |
## EFF donations ## EFF donations
@@ -164,9 +161,9 @@ Prior to 2024-05-10, a portion of all donations were given to the [Electronic Fr
The EFF defends your online liberties and [backed](https://github.com/github/dmca/blob/9a85e0f021f7967af80e186b890776a50443f06c/2020/11/2020-11-16-RIAA-reversal-effletter.pdf) `youtube-dl` when Google took them down. The EFF defends your online liberties and [backed](https://github.com/github/dmca/blob/9a85e0f021f7967af80e186b890776a50443f06c/2020/11/2020-11-16-RIAA-reversal-effletter.pdf) `youtube-dl` when Google took them down.
## Pre-release disclaimer ## Stability disclaimer
This is pre-release software and anything can break at any time. I make not guarantees about the stability of this software, forward-compatibility of updates, or integrity (both related to and independent of Pinchflat). Essentially, use at your own risk and expect there will be rough edges for now. This software is in active development and anything can break at any time. I make no guarantees about the stability of this software, forward-compatibility of updates, or integrity (both related to and independent of Pinchflat).
## License ## License
+7
View File
@@ -35,3 +35,10 @@ window.markVersionAsSeen = (versionString) => {
window.isVersionSeen = (versionString) => { window.isVersionSeen = (versionString) => {
return localStorage.getItem('seenVersion') === versionString return localStorage.getItem('seenVersion') === versionString
} }
window.dispatchFor = (elementOrId, eventName, detail = {}) => {
const element =
typeof elementOrId === 'string' ? document.getElementById(elementOrId) : elementOrId
element.dispatchEvent(new CustomEvent(eventName, { detail }))
}
+24 -1
View File
@@ -39,7 +39,7 @@ let liveSocket = new LiveSocket(document.body.dataset.socketPath, Socket, {
} }
}, },
hooks: { hooks: {
supressEnterSubmission: { 'supress-enter-submission': {
mounted() { mounted() {
this.el.addEventListener('keypress', (event) => { this.el.addEventListener('keypress', (event) => {
if (event.key === 'Enter') { if (event.key === 'Enter') {
@@ -47,6 +47,29 @@ let liveSocket = new LiveSocket(document.body.dataset.socketPath, Socket, {
} }
}) })
} }
},
'formless-input': {
mounted() {
const subscribedEvents = this.el.dataset.subscribe.split(' ')
const eventName = this.el.dataset.eventName || ''
const identifier = this.el.dataset.identifier || ''
subscribedEvents.forEach((domEvent) => {
this.el.addEventListener(domEvent, () => {
// This ensures that the event is pushed to the server after the input value has been updated
// so that the server has the most up-to-date value
setTimeout(() => {
this.pushEvent('formless-input', {
value: this.el.value,
id: identifier,
event: eventName,
dom_id: this.el.id,
dom_event: domEvent
})
}, 0)
})
})
}
} }
} }
}) })
+3 -2
View File
@@ -79,11 +79,12 @@ if config_env() == :prod do
tmpfile_directory: Path.join([System.tmp_dir!(), "pinchflat", "data"]), tmpfile_directory: Path.join([System.tmp_dir!(), "pinchflat", "data"]),
dns_cluster_query: System.get_env("DNS_CLUSTER_QUERY"), dns_cluster_query: System.get_env("DNS_CLUSTER_QUERY"),
expose_feed_endpoints: expose_feed_endpoints, expose_feed_endpoints: expose_feed_endpoints,
timezone: System.get_env("TIMEZONE") || System.get_env("TZ") || "UTC", # This is configured in application.ex
timezone: "UTC",
log_path: log_path, log_path: log_path,
base_route_path: base_route_path base_route_path: base_route_path
config :tzdata, :data_dir, System.get_env("TZ_DATA_DIR", "/etc/elixir_tzdata_data") config :tzdata, :data_dir, System.get_env("TZ_DATA_DIR", "/config/extras/elixir_tz_data")
config :pinchflat, Pinchflat.Repo, config :pinchflat, Pinchflat.Repo,
database: db_path, database: db_path,
+3 -12
View File
@@ -88,6 +88,7 @@ RUN apt-get update -y && \
ca-certificates \ ca-certificates \
python3-mutagen \ python3-mutagen \
curl \ curl \
zip \
openssh-client \ openssh-client \
nano \ nano \
python3 \ python3 \
@@ -116,7 +117,8 @@ ENV LC_ALL en_US.UTF-8
WORKDIR "/app" WORKDIR "/app"
# Set up data volumes # Set up data volumes
RUN mkdir /config /downloads /etc/elixir_tzdata_data && chmod ugo+rw /etc/elixir_tzdata_data RUN mkdir -p /config /downloads /etc/elixir_tzdata_data /etc/yt-dlp/plugins && \
chmod ugo+rw /etc/elixir_tzdata_data /etc/yt-dlp /etc/yt-dlp/plugins
# set runner ENV # set runner ENV
ENV MIX_ENV="prod" ENV MIX_ENV="prod"
@@ -127,17 +129,6 @@ EXPOSE ${PORT}
# Only copy the final release from the build stage # Only copy the final release from the build stage
COPY --from=builder /app/_build/${MIX_ENV}/rel/pinchflat ./ COPY --from=builder /app/_build/${MIX_ENV}/rel/pinchflat ./
# NEVER do this if you're running in an environment where you don't trust the user
# (ie: most environments). This is only acceptable in a self-hosted environment.
# The user could just run the whole container as root and bypass this anyway so
# it's not a huge deal.
# This removes the root password to allow users to assume root if needed. This is
# preferrable to running the whole container as root so that the files/directories
# created by the app aren't owned by root and are therefore easier for other users
# and processes to interact with. If you want to just run the whole container as
# root, use --user 0:0 or something.
RUN passwd -d root
HEALTHCHECK --interval=120s --start-period=10s \ HEALTHCHECK --interval=120s --start-period=10s \
CMD curl --fail http://localhost:${PORT}/healthcheck || exit 1 CMD curl --fail http://localhost:${PORT}/healthcheck || exit 1
+19
View File
@@ -4,9 +4,12 @@ defmodule Pinchflat.Application do
@moduledoc false @moduledoc false
use Application use Application
require Logger
@impl true @impl true
def start(_type, _args) do def start(_type, _args) do
check_and_update_timezone()
children = [ children = [
PinchflatWeb.Telemetry, PinchflatWeb.Telemetry,
Pinchflat.Repo, Pinchflat.Repo,
@@ -47,4 +50,20 @@ defmodule Pinchflat.Application do
:ok = Oban.Telemetry.attach_default_logger() :ok = Oban.Telemetry.attach_default_logger()
:telemetry.attach_many("job-telemetry-broadcast", events, &PinchflatWeb.Telemetry.job_state_change_broadcast/4, []) :telemetry.attach_many("job-telemetry-broadcast", events, &PinchflatWeb.Telemetry.job_state_change_broadcast/4, [])
end end
# This has to be here (rather than runtime.exs) since the `tzdata` application
# has to be started before we can check the timezone
defp check_and_update_timezone do
attempted_timezone = System.get_env("TIMEZONE") || System.get_env("TZ") || "UTC"
valid_timezone =
if Tzdata.zone_exists?(attempted_timezone) do
attempted_timezone
else
Logger.warning("Invalid timezone #{attempted_timezone}, defaulting to UTC")
"UTC"
end
Application.put_env(:pinchflat, :timezone, valid_timezone)
end
end end
@@ -16,6 +16,8 @@ defmodule Pinchflat.Boot.PreJobStartupTasks do
alias Pinchflat.Settings alias Pinchflat.Settings
alias Pinchflat.Utils.FilesystemUtils alias Pinchflat.Utils.FilesystemUtils
alias Pinchflat.Lifecycle.UserScripts.CommandRunner, as: UserScriptRunner
def start_link(opts \\ []) do def start_link(opts \\ []) do
GenServer.start_link(__MODULE__, %{}, opts) GenServer.start_link(__MODULE__, %{}, opts)
end end
@@ -36,6 +38,7 @@ defmodule Pinchflat.Boot.PreJobStartupTasks do
create_blank_yt_dlp_files() create_blank_yt_dlp_files()
create_blank_user_script_file() create_blank_user_script_file()
apply_default_settings() apply_default_settings()
run_app_init_script()
{:ok, state} {:ok, state}
end end
@@ -95,6 +98,12 @@ defmodule Pinchflat.Boot.PreJobStartupTasks do
Settings.set(apprise_version: apprise_version) Settings.set(apprise_version: apprise_version)
end end
defp run_app_init_script do
runner = Application.get_env(:pinchflat, :user_script_runner, UserScriptRunner)
runner.run(:app_init, %{})
end
defp yt_dlp_runner do defp yt_dlp_runner do
Application.get_env(:pinchflat, :yt_dlp_runner) Application.get_env(:pinchflat, :yt_dlp_runner)
end end
@@ -4,10 +4,10 @@ defmodule Pinchflat.Downloading.DownloadOptionBuilder do
""" """
alias Pinchflat.Sources alias Pinchflat.Sources
alias Pinchflat.Settings
alias Pinchflat.Sources.Source alias Pinchflat.Sources.Source
alias Pinchflat.Media.MediaItem alias Pinchflat.Media.MediaItem
alias Pinchflat.Downloading.OutputPathBuilder alias Pinchflat.Downloading.OutputPathBuilder
alias Pinchflat.Downloading.QualityOptionBuilder
alias Pinchflat.Utils.FilesystemUtils, as: FSUtils alias Pinchflat.Utils.FilesystemUtils, as: FSUtils
@@ -34,21 +34,38 @@ defmodule Pinchflat.Downloading.DownloadOptionBuilder do
@doc """ @doc """
Builds the output path for yt-dlp to download media based on the given source's Builds the output path for yt-dlp to download media based on the given source's
media profile. Uses the source's override output path template if it exists. or media_item's media profile. Uses the source's override output path template if it exists.
Accepts a %MediaItem{} or %Source{} struct. If a %Source{} struct is passed, it Accepts a %MediaItem{} or %Source{} struct. If a %Source{} struct is passed, it
will use a default %MediaItem{} struct with the given source. will use a default %MediaItem{} struct with the given source.
Returns binary() Returns binary()
""" """
def build_output_path_for(%Source{} = source_with_preloads) do
build_output_path_for(%MediaItem{source: source_with_preloads})
end
def build_output_path_for(%MediaItem{} = media_item_with_preloads) do def build_output_path_for(%MediaItem{} = media_item_with_preloads) do
output_path_template = Sources.output_path_template(media_item_with_preloads.source) output_path_template = Sources.output_path_template(media_item_with_preloads.source)
build_output_path(output_path_template, media_item_with_preloads) build_output_path(output_path_template, media_item_with_preloads)
end end
def build_output_path_for(%Source{} = source_with_preloads) do @doc """
build_output_path_for(%MediaItem{source: source_with_preloads}) Builds the quality options for yt-dlp to download media based on the given source's
or media_item's media profile. Useful for helping predict final filepath of downloaded
media.
returns [Keyword.t()]
"""
def build_quality_options_for(%Source{} = source_with_preloads) do
build_quality_options_for(%MediaItem{source: source_with_preloads})
end
def build_quality_options_for(%MediaItem{} = media_item_with_preloads) do
media_profile = media_item_with_preloads.source.media_profile
quality_options(media_profile)
end end
defp default_options(override_opts) do defp default_options(override_opts) do
@@ -125,27 +142,7 @@ defmodule Pinchflat.Downloading.DownloadOptionBuilder do
end end
defp quality_options(media_profile) do defp quality_options(media_profile) do
vcodec = Settings.get!(:video_codec_preference) QualityOptionBuilder.build(media_profile)
acodec = Settings.get!(:audio_codec_preference)
container = media_profile.media_container
case media_profile.preferred_resolution do
# Also be aware that :audio disabled all embedding options for subtitles
:audio ->
[:extract_audio, format_sort: "+acodec:#{acodec}", audio_format: container || "best"]
resolution_atom ->
{resolution_string, _} =
resolution_atom
|> Atom.to_string()
|> Integer.parse()
[
# Since Plex doesn't support reading metadata from MKV
remux_video: container || "mp4",
format_sort: "res:#{resolution_string},+codec:#{vcodec}:#{acodec}"
]
end
end end
defp sponsorblock_options(media_profile) do defp sponsorblock_options(media_profile) do
@@ -94,6 +94,9 @@ defmodule Pinchflat.Downloading.MediaDownloadWorker do
{:recovered, _} -> {:recovered, _} ->
{:error, :retry} {:error, :retry}
{:error, :unsuitable_for_download} ->
{:ok, :non_retry}
{:error, message} -> {:error, message} ->
action_on_error(message) action_on_error(message)
end end
+12 -1
View File
@@ -37,6 +37,13 @@ defmodule Pinchflat.Downloading.MediaDownloader do
{:ok, parsed_json} -> {:ok, parsed_json} ->
update_media_item_from_parsed_json(media_with_preloads, parsed_json) update_media_item_from_parsed_json(media_with_preloads, parsed_json)
{:error, :unsuitable_for_download} ->
Logger.warning(
"Media item ##{media_with_preloads.id} isn't suitable for download yet. May be an active or processing live stream"
)
{:error, :unsuitable_for_download}
{:error, message, _exit_code} -> {:error, message, _exit_code} ->
Logger.error("yt-dlp download error for media item ##{media_with_preloads.id}: #{inspect(message)}") Logger.error("yt-dlp download error for media item ##{media_with_preloads.id}: #{inspect(message)}")
@@ -108,7 +115,11 @@ defmodule Pinchflat.Downloading.MediaDownloader do
{:ok, options} = DownloadOptionBuilder.build(item_with_preloads, override_opts) {:ok, options} = DownloadOptionBuilder.build(item_with_preloads, override_opts)
runner_opts = [output_filepath: output_filepath, use_cookies: item_with_preloads.source.use_cookies] runner_opts = [output_filepath: output_filepath, use_cookies: item_with_preloads.source.use_cookies]
YtDlpMedia.download(url, options, runner_opts) case YtDlpMedia.get_downloadable_status(url) do
{:ok, :downloadable} -> YtDlpMedia.download(url, options, runner_opts)
{:ok, :ignorable} -> {:error, :unsuitable_for_download}
err -> err
end
end end
defp recoverable_errors do defp recoverable_errors do
@@ -49,6 +49,8 @@ defmodule Pinchflat.Downloading.MediaRetentionWorker do
end) end)
end end
# NOTE: Since this is a date and not a datetime, we can't add logic to have to-the-minute
# comparison like we can with retention periods. We can only compare to the day.
defp delete_media_items_from_before_cutoff do defp delete_media_items_from_before_cutoff do
deletable_media = deletable_media =
MediaQuery.new() MediaQuery.new()
@@ -0,0 +1,66 @@
defmodule Pinchflat.Downloading.QualityOptionBuilder do
@moduledoc """
A standalone builder module for building quality-related options for yt-dlp to download media.
Currently exclusively used in DownloadOptionBuilder since this logic is too complex to just
place in the main module.
"""
alias Pinchflat.Settings
alias Pinchflat.Profiles.MediaProfile
@doc """
Builds the quality-related options for yt-dlp to download media based on the given media profile
Includes things like container, preferred format/codec, and audio track options.
"""
def build(%MediaProfile{preferred_resolution: :audio, media_container: container} = media_profile) do
acodec = Settings.get!(:audio_codec_preference)
[
:extract_audio,
format_sort: "+acodec:#{acodec}",
audio_format: container || "best",
format: build_format_string(media_profile)
]
end
def build(%MediaProfile{preferred_resolution: resolution_atom, media_container: container} = media_profile) do
vcodec = Settings.get!(:video_codec_preference)
acodec = Settings.get!(:audio_codec_preference)
{resolution_string, _} = resolution_atom |> Atom.to_string() |> Integer.parse()
[
# Since Plex doesn't support reading metadata from MKV
remux_video: container || "mp4",
format_sort: "res:#{resolution_string},+codec:#{vcodec}:#{acodec}",
format: build_format_string(media_profile)
]
end
defp build_format_string(%MediaProfile{preferred_resolution: :audio, audio_track: audio_track}) do
if audio_track do
"bestaudio[#{build_format_modifier(audio_track)}]/bestaudio/best"
else
"bestaudio/best"
end
end
defp build_format_string(%MediaProfile{audio_track: audio_track}) do
if audio_track do
"bestvideo+bestaudio[#{build_format_modifier(audio_track)}]/bestvideo*+bestaudio/best"
else
"bestvideo*+bestaudio/best"
end
end
# Reminder to self: this conflicts with `--extractor-args "youtube:lang=<LANG>"`
# since that will translate the format_notes as well, which means they may not match.
# At least that's what happens now - worth a re-check if I have to come back to this
defp build_format_modifier("original"), do: "format_note*=original"
defp build_format_modifier("default"), do: "format_note*='(default)'"
# This uses the carat to anchor the language to the beginning of the string
# since that's what's needed to match `en` to `en-US` and `en-GB`, etc. The user
# can always specify the full language code if they want.
defp build_format_modifier(language_code), do: "language^=#{language_code}"
end
@@ -11,13 +11,27 @@ defmodule Pinchflat.FastIndexing.FastIndexingHelpers do
alias Pinchflat.Repo alias Pinchflat.Repo
alias Pinchflat.Media alias Pinchflat.Media
alias Pinchflat.Tasks
alias Pinchflat.Sources.Source alias Pinchflat.Sources.Source
alias Pinchflat.FastIndexing.YoutubeRss alias Pinchflat.FastIndexing.YoutubeRss
alias Pinchflat.FastIndexing.YoutubeApi alias Pinchflat.FastIndexing.YoutubeApi
alias Pinchflat.Downloading.DownloadingHelpers alias Pinchflat.Downloading.DownloadingHelpers
alias Pinchflat.FastIndexing.FastIndexingWorker
alias Pinchflat.Downloading.DownloadOptionBuilder
alias Pinchflat.YtDlp.Media, as: YtDlpMedia alias Pinchflat.YtDlp.Media, as: YtDlpMedia
@doc """
Kicks off a new fast indexing task for a source. This will delete any existing fast indexing
tasks for the source before starting a new one.
Returns {:ok, %Task{}}
"""
def kickoff_indexing_task(%Source{} = source) do
Tasks.delete_pending_tasks_for(source, "FastIndexingWorker", include_executing: true)
FastIndexingWorker.kickoff_with_task(source)
end
@doc """ @doc """
Fetches new media IDs for a source from YT's API or RSS, indexes them, and kicks off downloading Fetches new media IDs for a source from YT's API or RSS, indexes them, and kicks off downloading
tasks for any pending media items. See comments in `FastIndexingWorker` for more info on the tasks for any pending media items. See comments in `FastIndexingWorker` for more info on the
@@ -27,6 +41,10 @@ defmodule Pinchflat.FastIndexing.FastIndexingHelpers do
downloaded_. downloaded_.
""" """
def kickoff_download_tasks_from_youtube_rss_feed(%Source{} = source) do def kickoff_download_tasks_from_youtube_rss_feed(%Source{} = source) do
# The media_profile is needed to determine the quality options to _then_ determine a more
# accurate predicted filepath
source = Repo.preload(source, [:media_profile])
{:ok, media_ids} = get_recent_media_ids(source) {:ok, media_ids} = get_recent_media_ids(source)
existing_media_items = list_media_items_by_media_id_for(source, media_ids) existing_media_items = list_media_items_by_media_id_for(source, media_ids)
new_media_ids = media_ids -- Enum.map(existing_media_items, & &1.media_id) new_media_ids = media_ids -- Enum.map(existing_media_items, & &1.media_id)
@@ -68,7 +86,11 @@ defmodule Pinchflat.FastIndexing.FastIndexingHelpers do
defp create_media_item_from_media_id(source, media_id) do defp create_media_item_from_media_id(source, media_id) do
url = "https://www.youtube.com/watch?v=#{media_id}" url = "https://www.youtube.com/watch?v=#{media_id}"
case YtDlpMedia.get_media_attributes(url, use_cookies: source.use_cookies) do command_opts =
[output: DownloadOptionBuilder.build_output_path_for(source)] ++
DownloadOptionBuilder.build_quality_options_for(source)
case YtDlpMedia.get_media_attributes(url, command_opts, use_cookies: source.use_cookies) do
{:ok, media_attrs} -> {:ok, media_attrs} ->
Media.create_media_item_from_backend_attrs(source, media_attrs) Media.create_media_item_from_backend_attrs(source, media_attrs)
@@ -12,6 +12,7 @@ defmodule Pinchflat.Lifecycle.UserScripts.CommandRunner do
@behaviour UserScriptCommandRunner @behaviour UserScriptCommandRunner
@event_types [ @event_types [
:app_init,
:media_pre_download, :media_pre_download,
:media_downloaded, :media_downloaded,
:media_deleted :media_deleted
+7 -4
View File
@@ -15,6 +15,9 @@ defmodule Pinchflat.Media do
alias Pinchflat.Lifecycle.UserScripts.CommandRunner, as: UserScriptRunner alias Pinchflat.Lifecycle.UserScripts.CommandRunner, as: UserScriptRunner
# Some fields should only be set on insert and not on update.
@fields_to_drop_on_update [:playlist_index]
@doc """ @doc """
Returns the list of media_items. Returns the list of media_items.
@@ -131,8 +134,6 @@ defmodule Pinchflat.Media do
""" """
def create_media_item_from_backend_attrs(source, media_attrs_struct) do def create_media_item_from_backend_attrs(source, media_attrs_struct) do
attrs = Map.merge(%{source_id: source.id}, Map.from_struct(media_attrs_struct)) attrs = Map.merge(%{source_id: source.id}, Map.from_struct(media_attrs_struct))
# Some fields should only be set on insert and not on update.
fields_to_drop_on_update = [:playlist_index]
%MediaItem{} %MediaItem{}
|> MediaItem.changeset(attrs) |> MediaItem.changeset(attrs)
@@ -140,7 +141,7 @@ defmodule Pinchflat.Media do
on_conflict: [ on_conflict: [
set: set:
attrs attrs
|> Map.drop(fields_to_drop_on_update) |> Map.drop(@fields_to_drop_on_update)
|> Map.to_list() |> Map.to_list()
], ],
conflict_target: [:source_id, :media_id] conflict_target: [:source_id, :media_id]
@@ -153,8 +154,10 @@ defmodule Pinchflat.Media do
Returns {:ok, %MediaItem{}} | {:error, %Ecto.Changeset{}} Returns {:ok, %MediaItem{}} | {:error, %Ecto.Changeset{}}
""" """
def update_media_item(%MediaItem{} = media_item, attrs) do def update_media_item(%MediaItem{} = media_item, attrs) do
update_attrs = Map.drop(attrs, @fields_to_drop_on_update)
media_item media_item
|> MediaItem.changeset(attrs) |> MediaItem.changeset(update_attrs)
|> Repo.update() |> Repo.update()
end end
+2
View File
@@ -31,6 +31,7 @@ defmodule Pinchflat.Media.MediaItem do
:uploaded_at, :uploaded_at,
:upload_date_index, :upload_date_index,
:duration_seconds, :duration_seconds,
:predicted_media_filepath,
# these fields are captured only on download # these fields are captured only on download
:media_downloaded_at, :media_downloaded_at,
:media_filepath, :media_filepath,
@@ -76,6 +77,7 @@ defmodule Pinchflat.Media.MediaItem do
field :duration_seconds, :integer field :duration_seconds, :integer
field :playlist_index, :integer, default: 0 field :playlist_index, :integer, default: 0
field :predicted_media_filepath, :string
field :media_filepath, :string field :media_filepath, :string
field :media_size_bytes, :integer field :media_size_bytes, :integer
field :thumbnail_filepath, :string field :thumbnail_filepath, :string
+3 -3
View File
@@ -88,7 +88,7 @@ defmodule Pinchflat.Media.MediaQuery do
[mi, source], [mi, source],
fragment(""" fragment("""
IFNULL(retention_period_days, 0) > 0 AND IFNULL(retention_period_days, 0) > 0 AND
DATETIME('now', '-' || retention_period_days || ' day') > media_downloaded_at DATETIME(media_downloaded_at, '+' || retention_period_days || ' day') < DATETIME('now')
""") """)
) )
end end
@@ -100,8 +100,8 @@ defmodule Pinchflat.Media.MediaQuery do
# downloaded_at minus the redownload_delay_days is before the upload date # downloaded_at minus the redownload_delay_days is before the upload date
fragment(""" fragment("""
IFNULL(redownload_delay_days, 0) > 0 AND IFNULL(redownload_delay_days, 0) > 0 AND
DATETIME('now', '-' || redownload_delay_days || ' day') > uploaded_at AND DATE('now', '-' || redownload_delay_days || ' day') > DATE(uploaded_at) AND
DATETIME(media_downloaded_at, '-' || redownload_delay_days || ' day') < uploaded_at DATE(media_downloaded_at, '-' || redownload_delay_days || ' day') < DATE(uploaded_at)
""") """)
) )
end end
+2
View File
@@ -26,6 +26,7 @@ defmodule Pinchflat.Profiles.MediaProfile do
sponsorblock_categories sponsorblock_categories
shorts_behaviour shorts_behaviour
livestream_behaviour livestream_behaviour
audio_track
preferred_resolution preferred_resolution
media_container media_container
redownload_delay_days redownload_delay_days
@@ -65,6 +66,7 @@ defmodule Pinchflat.Profiles.MediaProfile do
# See `build_format_clauses` in the Media context for more. # See `build_format_clauses` in the Media context for more.
field :shorts_behaviour, Ecto.Enum, values: ~w(include exclude only)a, default: :include field :shorts_behaviour, Ecto.Enum, values: ~w(include exclude only)a, default: :include
field :livestream_behaviour, Ecto.Enum, values: ~w(include exclude only)a, default: :include field :livestream_behaviour, Ecto.Enum, values: ~w(include exclude only)a, default: :include
field :audio_track, :string
field :preferred_resolution, Ecto.Enum, values: ~w(4320p 2160p 1080p 720p 480p 360p audio)a, default: :"1080p" field :preferred_resolution, Ecto.Enum, values: ~w(4320p 2160p 1080p 720p 480p 360p audio)a, default: :"1080p"
field :media_container, :string, default: nil field :media_container, :string, default: nil
+29
View File
@@ -0,0 +1,29 @@
defmodule Pinchflat.Profiles.ProfilesQuery do
@moduledoc """
Query helpers for the Profiles context.
These methods are made to be one-ish liners used
to compose queries. Each method should strive to do
_one_ thing. These don't need to be tested as
they are just building blocks for other functionality
which, itself, will be tested.
"""
import Ecto.Query, warn: false
alias Pinchflat.Profiles.MediaProfile
# This allows the module to be aliased and query methods to be used
# all in one go
# usage: use Pinchflat.Profiles.ProfilesQuery
defmacro __using__(_opts) do
quote do
import Ecto.Query, warn: false
alias unquote(__MODULE__)
end
end
def new do
MediaProfile
end
end
+2
View File
@@ -29,6 +29,8 @@ defmodule Pinchflat.Release do
[ [
"/config", "/config",
"/downloads", "/downloads",
"/etc/yt-dlp",
"/etc/yt-dlp/plugins",
Application.get_env(:pinchflat, :media_directory), Application.get_env(:pinchflat, :media_directory),
Application.get_env(:pinchflat, :tmpfile_directory), Application.get_env(:pinchflat, :tmpfile_directory),
Application.get_env(:pinchflat, :extras_directory), Application.get_env(:pinchflat, :extras_directory),
@@ -16,6 +16,7 @@ defmodule Pinchflat.SlowIndexing.SlowIndexingHelpers do
alias Pinchflat.YtDlp.MediaCollection alias Pinchflat.YtDlp.MediaCollection
alias Pinchflat.Downloading.DownloadingHelpers alias Pinchflat.Downloading.DownloadingHelpers
alias Pinchflat.SlowIndexing.FileFollowerServer alias Pinchflat.SlowIndexing.FileFollowerServer
alias Pinchflat.Downloading.DownloadOptionBuilder
alias Pinchflat.SlowIndexing.MediaCollectionIndexingWorker alias Pinchflat.SlowIndexing.MediaCollectionIndexingWorker
alias Pinchflat.YtDlp.Media, as: YtDlpMedia alias Pinchflat.YtDlp.Media, as: YtDlpMedia
@@ -24,13 +25,28 @@ defmodule Pinchflat.SlowIndexing.SlowIndexingHelpers do
Starts tasks for indexing a source's media regardless of the source's indexing Starts tasks for indexing a source's media regardless of the source's indexing
frequency. It's assumed the caller will check for indexing frequency. frequency. It's assumed the caller will check for indexing frequency.
Returns {:ok, %Task{}}. Returns {:ok, %Task{}}
""" """
def kickoff_indexing_task(%Source{} = source, job_args \\ %{}, job_opts \\ []) do def kickoff_indexing_task(%Source{} = source, job_args \\ %{}, job_opts \\ []) do
job_offset_seconds = calculate_job_offset_seconds(source)
Tasks.delete_pending_tasks_for(source, "FastIndexingWorker") Tasks.delete_pending_tasks_for(source, "FastIndexingWorker")
Tasks.delete_pending_tasks_for(source, "MediaCollectionIndexingWorker", include_executing: true) Tasks.delete_pending_tasks_for(source, "MediaCollectionIndexingWorker", include_executing: true)
MediaCollectionIndexingWorker.kickoff_with_task(source, job_args, job_opts) MediaCollectionIndexingWorker.kickoff_with_task(source, job_args, job_opts ++ [schedule_in: job_offset_seconds])
end
@doc """
A helper method to delete all indexing-related tasks for a source.
Optionally, you can include executing tasks in the deletion process.
Returns :ok
"""
def delete_indexing_tasks(%Source{} = source, opts \\ []) do
include_executing = Keyword.get(opts, :include_executing, false)
Tasks.delete_pending_tasks_for(source, "FastIndexingWorker", include_executing: include_executing)
Tasks.delete_pending_tasks_for(source, "MediaCollectionIndexingWorker", include_executing: include_executing)
end end
@doc """ @doc """
@@ -56,6 +72,9 @@ defmodule Pinchflat.SlowIndexing.SlowIndexingHelpers do
Returns [%MediaItem{} | %Ecto.Changeset{}] Returns [%MediaItem{} | %Ecto.Changeset{}]
""" """
def index_and_enqueue_download_for_media_items(%Source{} = source) do def index_and_enqueue_download_for_media_items(%Source{} = source) do
# The media_profile is needed to determine the quality options to _then_ determine a more
# accurate predicted filepath
source = Repo.preload(source, [:media_profile])
# See the method definition below for more info on how file watchers work # See the method definition below for more info on how file watchers work
# (important reading if you're not familiar with it) # (important reading if you're not familiar with it)
{:ok, media_attributes} = setup_file_watcher_and_kickoff_indexing(source) {:ok, media_attributes} = setup_file_watcher_and_kickoff_indexing(source)
@@ -94,8 +113,13 @@ defmodule Pinchflat.SlowIndexing.SlowIndexingHelpers do
{:ok, pid} = FileFollowerServer.start_link() {:ok, pid} = FileFollowerServer.start_link()
handler = fn filepath -> setup_file_follower_watcher(pid, filepath, source) end handler = fn filepath -> setup_file_follower_watcher(pid, filepath, source) end
command_opts =
[output: DownloadOptionBuilder.build_output_path_for(source)] ++
DownloadOptionBuilder.build_quality_options_for(source)
runner_opts = [file_listener_handler: handler, use_cookies: source.use_cookies] runner_opts = [file_listener_handler: handler, use_cookies: source.use_cookies]
result = MediaCollection.get_media_attributes_for_collection(source.original_url, runner_opts) result = MediaCollection.get_media_attributes_for_collection(source.original_url, command_opts, runner_opts)
FileFollowerServer.stop(pid) FileFollowerServer.stop(pid)
@@ -132,4 +156,14 @@ defmodule Pinchflat.SlowIndexing.SlowIndexingHelpers do
changeset changeset
end end
end end
# Find the difference between the current time and the last time the source was indexed
defp calculate_job_offset_seconds(%Source{last_indexed_at: nil}), do: 0
defp calculate_job_offset_seconds(source) do
offset_seconds = DateTime.diff(DateTime.utc_now(), source.last_indexed_at, :second)
index_frequency_seconds = source.index_frequency_minutes * 60
max(0, index_frequency_seconds - offset_seconds)
end
end end
+2
View File
@@ -15,6 +15,7 @@ defmodule Pinchflat.Sources.Source do
alias Pinchflat.Metadata.SourceMetadata alias Pinchflat.Metadata.SourceMetadata
@allowed_fields ~w( @allowed_fields ~w(
enabled
collection_name collection_name
collection_id collection_id
collection_type collection_type
@@ -64,6 +65,7 @@ defmodule Pinchflat.Sources.Source do
)a )a
schema "sources" do schema "sources" do
field :enabled, :boolean, default: true
# This is _not_ used as the primary key or internally in the database # This is _not_ used as the primary key or internally in the database
# relations. This is only used to prevent an enumeration attack on the streaming # relations. This is only used to prevent an enumeration attack on the streaming
# and RSS feed endpoints since those _must_ be public (ie: no basic auth) # and RSS feed endpoints since those _must_ be public (ie: no basic auth)
+66 -18
View File
@@ -15,8 +15,8 @@ defmodule Pinchflat.Sources do
alias Pinchflat.Metadata.SourceMetadata alias Pinchflat.Metadata.SourceMetadata
alias Pinchflat.Utils.FilesystemUtils alias Pinchflat.Utils.FilesystemUtils
alias Pinchflat.Downloading.DownloadingHelpers alias Pinchflat.Downloading.DownloadingHelpers
alias Pinchflat.FastIndexing.FastIndexingWorker
alias Pinchflat.SlowIndexing.SlowIndexingHelpers alias Pinchflat.SlowIndexing.SlowIndexingHelpers
alias Pinchflat.FastIndexing.FastIndexingHelpers
alias Pinchflat.Metadata.SourceMetadataStorageWorker alias Pinchflat.Metadata.SourceMetadataStorageWorker
@doc """ @doc """
@@ -186,7 +186,13 @@ defmodule Pinchflat.Sources do
{:ok, source_details} -> {:ok, source_details} ->
add_source_details_by_collection_type(source, changeset, source_details) add_source_details_by_collection_type(source, changeset, source_details)
{:error, runner_error, _status_code} -> err ->
runner_error =
case err do
{:error, error_msg, _status_code} -> error_msg
{:error, error_msg} -> error_msg
end
Ecto.Changeset.add_error( Ecto.Changeset.add_error(
changeset, changeset,
:original_url, :original_url,
@@ -249,19 +255,40 @@ defmodule Pinchflat.Sources do
end end
end end
# If the source is NOT new (ie: updated) and the download_media flag has changed, # If the source is new (ie: not persisted), do nothing
defp maybe_handle_media_tasks(%{data: %{__meta__: %{state: state}}}, _source) when state != :loaded do
:ok
end
# If the source is NOT new (ie: updated),
# enqueue or dequeue media download tasks as necessary. # enqueue or dequeue media download tasks as necessary.
defp maybe_handle_media_tasks(changeset, source) do defp maybe_handle_media_tasks(changeset, source) do
case {changeset.data, changeset.changes} do current_changes = changeset.changes
{%{__meta__: %{state: :loaded}}, %{download_media: true}} -> applied_changes = Ecto.Changeset.apply_changes(changeset)
# We need both current_changes and applied_changes to determine
# the course of action to take. For example, we only care if a source is supposed
# to be `enabled` or not - we don't care if that information comes from the
# current changes or if that's how it already was in the database.
# Rephrased, we're essentially using it in place of `get_field/2`
case {current_changes, applied_changes} do
{%{download_media: true}, %{enabled: true}} ->
DownloadingHelpers.enqueue_pending_download_tasks(source) DownloadingHelpers.enqueue_pending_download_tasks(source)
{%{__meta__: %{state: :loaded}}, %{download_media: false}} -> {%{enabled: true}, %{download_media: true}} ->
DownloadingHelpers.enqueue_pending_download_tasks(source)
{%{download_media: false}, _} ->
DownloadingHelpers.dequeue_pending_download_tasks(source)
{%{enabled: false}, _} ->
DownloadingHelpers.dequeue_pending_download_tasks(source) DownloadingHelpers.dequeue_pending_download_tasks(source)
_ -> _ ->
:ok nil
end end
:ok
end end
defp maybe_run_indexing_task(changeset, source) do defp maybe_run_indexing_task(changeset, source) do
@@ -295,13 +322,22 @@ defmodule Pinchflat.Sources do
end end
defp maybe_update_slow_indexing_task(changeset, source) do defp maybe_update_slow_indexing_task(changeset, source) do
case changeset.changes do # See comment in `maybe_handle_media_tasks` as to why we need these
%{index_frequency_minutes: mins} when mins > 0 -> current_changes = changeset.changes
applied_changes = Ecto.Changeset.apply_changes(changeset)
case {current_changes, applied_changes} do
{%{index_frequency_minutes: mins}, %{enabled: true}} when mins > 0 ->
SlowIndexingHelpers.kickoff_indexing_task(source) SlowIndexingHelpers.kickoff_indexing_task(source)
%{index_frequency_minutes: _} -> {%{enabled: true}, %{index_frequency_minutes: mins}} when mins > 0 ->
Tasks.delete_pending_tasks_for(source, "FastIndexingWorker") SlowIndexingHelpers.kickoff_indexing_task(source)
Tasks.delete_pending_tasks_for(source, "MediaCollectionIndexingWorker")
{%{index_frequency_minutes: _}, _} ->
SlowIndexingHelpers.delete_indexing_tasks(source, include_executing: true)
{%{enabled: false}, _} ->
SlowIndexingHelpers.delete_indexing_tasks(source, include_executing: true)
_ -> _ ->
:ok :ok
@@ -309,13 +345,25 @@ defmodule Pinchflat.Sources do
end end
defp maybe_update_fast_indexing_task(changeset, source) do defp maybe_update_fast_indexing_task(changeset, source) do
case changeset.changes do # See comment in `maybe_handle_media_tasks` as to why we need these
%{fast_index: true} -> current_changes = changeset.changes
Tasks.delete_pending_tasks_for(source, "FastIndexingWorker") applied_changes = Ecto.Changeset.apply_changes(changeset)
FastIndexingWorker.kickoff_with_task(source)
%{fast_index: false} -> # This technically could be simplified since `maybe_update_slow_indexing_task`
Tasks.delete_pending_tasks_for(source, "FastIndexingWorker") # has some overlap re: deleting pending tasks, but I'm keeping it separate
# for clarity and explicitness.
case {current_changes, applied_changes} do
{%{fast_index: true}, %{enabled: true}} ->
FastIndexingHelpers.kickoff_indexing_task(source)
{%{enabled: true}, %{fast_index: true}} ->
FastIndexingHelpers.kickoff_indexing_task(source)
{%{fast_index: false}, _} ->
Tasks.delete_pending_tasks_for(source, "FastIndexingWorker", include_executing: true)
{%{enabled: false}, _} ->
Tasks.delete_pending_tasks_for(source, "FastIndexingWorker", include_executing: true)
_ -> _ ->
:ok :ok
+45 -11
View File
@@ -11,7 +11,8 @@ defmodule Pinchflat.YtDlp.Media do
:livestream, :livestream,
:short_form_content, :short_form_content,
:uploaded_at, :uploaded_at,
:duration_seconds :duration_seconds,
:predicted_media_filepath
] ]
defstruct [ defstruct [
@@ -23,7 +24,8 @@ defmodule Pinchflat.YtDlp.Media do
:short_form_content, :short_form_content,
:uploaded_at, :uploaded_at,
:duration_seconds, :duration_seconds,
:playlist_index :playlist_index,
:predicted_media_filepath
] ]
alias __MODULE__ alias __MODULE__
@@ -47,6 +49,24 @@ defmodule Pinchflat.YtDlp.Media do
end end
end end
@doc """
Determines if the media at the given URL is ready to be downloaded.
Common examples of non-downloadable media are upcoming or in-progress live streams.
Returns {:ok, :downloadable | :ignorable} | {:error, any}
"""
def get_downloadable_status(url) do
case backend_runner().run(url, [:simulate, :skip_download], "%(.{live_status})j") do
{:ok, output} ->
output
|> Phoenix.json_library().decode!()
|> parse_downloadable_status()
err ->
err
end
end
@doc """ @doc """
Downloads a thumbnail for a single piece of media. Usually used for Downloads a thumbnail for a single piece of media. Usually used for
downloading thumbnails for internal use downloading thumbnails for internal use
@@ -63,15 +83,16 @@ defmodule Pinchflat.YtDlp.Media do
@doc """ @doc """
Returns a map representing the media at the given URL. Returns a map representing the media at the given URL.
Optionally takes a list of additional command options to pass to yt-dlp
or configuration-related options to pass to the runner.
Returns {:ok, %Media{}} | {:error, any, ...}. Returns {:ok, %Media{}} | {:error, any, ...}.
""" """
def get_media_attributes(url, addl_opts \\ []) do def get_media_attributes(url, command_opts \\ [], addl_opts \\ []) do
runner = Application.get_env(:pinchflat, :yt_dlp_runner) all_command_opts = [:simulate, :skip_download] ++ command_opts
command_opts = [:simulate, :skip_download]
output_template = indexing_output_template() output_template = indexing_output_template()
case runner.run(url, command_opts, output_template, addl_opts) do case backend_runner().run(url, all_command_opts, output_template, addl_opts) do
{:ok, output} -> {:ok, output} ->
output output
|> Phoenix.json_library().decode!() |> Phoenix.json_library().decode!()
@@ -87,9 +108,11 @@ defmodule Pinchflat.YtDlp.Media do
Returns the output template for yt-dlp's indexing command. Returns the output template for yt-dlp's indexing command.
NOTE: playlist_index is really only useful for playlists that will never change their order. NOTE: playlist_index is really only useful for playlists that will never change their order.
NOTE: I've switched back to `original_url` (from `webpage_url`) since it's started indicating
if something is a short via the URL again
""" """
def indexing_output_template do def indexing_output_template do
"%(.{id,title,live_status,webpage_url,description,aspect_ratio,duration,upload_date,timestamp,playlist_index})j" "%(.{id,title,live_status,original_url,description,aspect_ratio,duration,upload_date,timestamp,playlist_index,filename})j"
end end
@doc """ @doc """
@@ -103,17 +126,18 @@ defmodule Pinchflat.YtDlp.Media do
media_id: response["id"], media_id: response["id"],
title: response["title"], title: response["title"],
description: response["description"], description: response["description"],
original_url: response["webpage_url"], original_url: response["original_url"],
livestream: !!response["live_status"] && response["live_status"] != "not_live", livestream: !!response["live_status"] && response["live_status"] != "not_live",
duration_seconds: response["duration"] && round(response["duration"]), duration_seconds: response["duration"] && round(response["duration"]),
short_form_content: response["webpage_url"] && short_form_content?(response), short_form_content: response["original_url"] && short_form_content?(response),
uploaded_at: response["upload_date"] && parse_uploaded_at(response), uploaded_at: response["upload_date"] && parse_uploaded_at(response),
playlist_index: response["playlist_index"] || 0 playlist_index: response["playlist_index"] || 0,
predicted_media_filepath: response["filename"]
} }
end end
defp short_form_content?(response) do defp short_form_content?(response) do
if String.contains?(response["webpage_url"], "/shorts/") do if String.contains?(response["original_url"], "/shorts/") do
true true
else else
# Sometimes shorts are returned without /shorts/ in the URL, # Sometimes shorts are returned without /shorts/ in the URL,
@@ -140,6 +164,16 @@ defmodule Pinchflat.YtDlp.Media do
defp parse_uploaded_at(%{"upload_date" => nil}), do: nil defp parse_uploaded_at(%{"upload_date" => nil}), do: nil
defp parse_uploaded_at(response), do: MetadataFileHelpers.parse_upload_date(response["upload_date"]) defp parse_uploaded_at(response), do: MetadataFileHelpers.parse_upload_date(response["upload_date"])
defp parse_downloadable_status(response) do
case response["live_status"] do
status when status in ["is_live", "is_upcoming", "post_live"] -> {:ok, :ignorable}
status when status in ["was_live", "not_live"] -> {:ok, :downloadable}
# This preserves my tenuous support for non-youtube sources.
nil -> {:ok, :downloadable}
_ -> {:error, "Unknown live status: #{response["live_status"]}"}
end
end
defp backend_runner do defp backend_runner do
# This approach lets us mock the command for testing # This approach lets us mock the command for testing
Application.get_env(:pinchflat, :yt_dlp_runner) Application.get_env(:pinchflat, :yt_dlp_runner)
+8 -4
View File
@@ -11,20 +11,23 @@ defmodule Pinchflat.YtDlp.MediaCollection do
@doc """ @doc """
Returns a list of maps representing the media in the collection. Returns a list of maps representing the media in the collection.
Optionally takes a list of additional command options to pass to yt-dlp
or configuration-related options to pass to the runner.
Options: Runner Options:
- :file_listener_handler - a function that will be called with the path to the - :file_listener_handler - a function that will be called with the path to the
file that will be written to when yt-dlp is done. This is useful for file that will be written to when yt-dlp is done. This is useful for
setting up a file watcher to know when the file is ready to be read. setting up a file watcher to know when the file is ready to be read.
- :use_cookies - whether or not to use user-provided cookies when fetching the media details
Returns {:ok, [map()]} | {:error, any, ...}. Returns {:ok, [map()]} | {:error, any, ...}.
""" """
def get_media_attributes_for_collection(url, addl_opts \\ []) do def get_media_attributes_for_collection(url, command_opts \\ [], addl_opts \\ []) do
runner = Application.get_env(:pinchflat, :yt_dlp_runner) runner = Application.get_env(:pinchflat, :yt_dlp_runner)
# `ignore_no_formats_error` is necessary because yt-dlp will error out if # `ignore_no_formats_error` is necessary because yt-dlp will error out if
# the first video has not released yet (ie: is a premier). We don't care about # the first video has not released yet (ie: is a premier). We don't care about
# available formats since we're just getting the media details # available formats since we're just getting the media details
command_opts = [:simulate, :skip_download, :ignore_no_formats_error, :no_warnings] all_command_opts = [:simulate, :skip_download, :ignore_no_formats_error, :no_warnings] ++ command_opts
use_cookies = Keyword.get(addl_opts, :use_cookies, false) use_cookies = Keyword.get(addl_opts, :use_cookies, false)
output_template = YtDlpMedia.indexing_output_template() output_template = YtDlpMedia.indexing_output_template()
output_filepath = FilesystemUtils.generate_metadata_tmpfile(:json) output_filepath = FilesystemUtils.generate_metadata_tmpfile(:json)
@@ -35,7 +38,7 @@ defmodule Pinchflat.YtDlp.MediaCollection do
file_listener_handler.(output_filepath) file_listener_handler.(output_filepath)
end end
case runner.run(url, command_opts, output_template, runner_opts) do case runner.run(url, all_command_opts, output_template, runner_opts) do
{:ok, output} -> {:ok, output} ->
parsed_lines = parsed_lines =
output output
@@ -84,6 +87,7 @@ defmodule Pinchflat.YtDlp.MediaCollection do
{:ok, parsed_json} <- Phoenix.json_library().decode(output) do {:ok, parsed_json} <- Phoenix.json_library().decode(output) do
{:ok, format_source_details(parsed_json)} {:ok, format_source_details(parsed_json)}
else else
{:error, %Jason.DecodeError{}} -> {:error, "Error decoding JSON response"}
err -> err err -> err
end end
end end
@@ -340,14 +340,15 @@ defmodule PinchflatWeb.CoreComponents do
end) end)
~H""" ~H"""
<div x-data={"{ enabled: #{@checked}}"}> <div x-data={"{ enabled: #{@checked} }"} class="" phx-update="ignore" id={"#{@id}-wrapper"}>
<.label for={@id}> <.label :if={@label} for={@id}>
<%= @label %> <%= @label %>
<span :if={@label_suffix} class="text-xs text-bodydark"><%= @label_suffix %></span> <span :if={@label_suffix} class="text-xs text-bodydark"><%= @label_suffix %></span>
</.label> </.label>
<div class="relative"> <div class="relative flex flex-col">
<input type="hidden" id={@id} name={@name} x-bind:value="enabled" {@rest} /> <input type="hidden" id={@id} name={@name} x-bind:value="enabled" {@rest} />
<div class="inline-block cursor-pointer" @click="enabled = !enabled"> <%!-- This triggers a `change` event on the hidden input when the toggle is clicked --%>
<div class="inline-block cursor-pointer" @click={"enabled = !enabled; dispatchFor('#{@id}', 'change')"}>
<div x-bind:class="enabled && '!bg-primary'" class="block h-8 w-14 rounded-full bg-black"></div> <div x-bind:class="enabled && '!bg-primary'" class="block h-8 w-14 rounded-full bg-black"></div>
<div <div
x-bind:class="enabled && '!right-1 !translate-x-full'" x-bind:class="enabled && '!right-1 !translate-x-full'"
@@ -62,17 +62,24 @@ defmodule PinchflatWeb.CustomComponents.TextComponents do
end end
@doc """ @doc """
Renders a block of text with each line broken into a separate span. Renders a block of text with each line broken into a separate span and links highlighted.
""" """
attr :text, :string, required: true attr :text, :string, required: true
def break_on_newline(assigns) do def render_description(assigns) do
broken_text = formatted_text =
assigns.text Regex.split(~r{https?://\S+}, assigns.text, include_captures: true)
|> Enum.map(fn
"http" <> _ = url ->
Phoenix.HTML.Tag.content_tag(:a, url, class: "text-blue-500 hover:text-blue-300", href: url, target: "_blank")
text ->
text
|> String.split("\n", trim: false) |> String.split("\n", trim: false)
|> Enum.intersperse(Phoenix.HTML.Tag.tag(:span, class: "inline-block mt-2")) |> Enum.intersperse(Phoenix.HTML.Tag.tag(:span, class: "inline-block mt-2"))
end)
assigns = Map.put(assigns, :text, broken_text) assigns = Map.put(assigns, :text, formatted_text)
~H""" ~H"""
<span><%= @text %></span> <span><%= @text %></span>
+1 -1
View File
@@ -64,7 +64,7 @@ defmodule PinchflatWeb.Layouts do
<.icon name={@icon} /> <%= @text %> <.icon name={@icon} /> <%= @text %>
</span> </span>
<span class="text-bodydark2"> <span class="text-bodydark2">
<.icon name="hero-chevron-up" x-bind:class="{ 'rotate-180': selected }" /> <.icon name="hero-chevron-down" x-bind:class="{ 'rotate-180': selected }" />
</span> </span>
</span> </span>
@@ -3,7 +3,7 @@ defmodule Pinchflat.UpgradeButtonLive do
def render(assigns) do def render(assigns) do
~H""" ~H"""
<form id="upgradeForm" phx-change="check_matching_text" phx-hook="supressEnterSubmission"> <form id="upgradeForm" phx-change="check_matching_text" phx-hook="supress-enter-submission">
<.input type="text" name="unlock-pro-textbox" value="" /> <.input type="text" name="unlock-pro-textbox" value="" />
</form> </form>
@@ -2,7 +2,7 @@
<:option> <:option>
<span x-data="{ copied: false }" x-on:click={~s" <span x-data="{ copied: false }" x-on:click={~s"
copyWithCallbacks( copyWithCallbacks(
`#{Jason.Formatter.pretty_print(Phoenix.json_library().encode!(@media_item))}`, String.raw`#{Jason.Formatter.pretty_print(Phoenix.json_library().encode!(@media_item))}`,
() => copied = true, () => copied = true,
() => copied = false () => copied = false
) )
@@ -1,13 +1,13 @@
<%= if media_type(@media_item) == :video do %> <%= if media_type(@media_item) == :video do %>
<video controls class="max-h-96 w-full"> <video controls class="max-h-128 w-full">
<source src={~p"/media/#{@media_item.uuid}/stream"} type="video/mp4" /> <source src={~p"/media/#{@media_item.uuid}/stream?v=#{DateTime.to_unix(@media_item.updated_at)}"} type="video/mp4" />
Your browser does not support the video element. Your browser does not support the video element.
</video> </video>
<% end %> <% end %>
<%= if media_type(@media_item) == :audio do %> <%= if media_type(@media_item) == :audio do %>
<audio controls class="w-full"> <audio controls class="w-full">
<source src={~p"/media/#{@media_item.uuid}/stream"} type="audio/mpeg" /> <source src={~p"/media/#{@media_item.uuid}/stream?v=#{DateTime.to_unix(@media_item.updated_at)}"} type="audio/mpeg" />
Your browser does not support the audio element. Your browser does not support the audio element.
</audio> </audio>
<% end %> <% end %>
@@ -26,11 +26,12 @@
<:tab title="Media" id="media"> <:tab title="Media" id="media">
<div class="flex flex-col gap-10 dark:text-white"> <div class="flex flex-col gap-10 dark:text-white">
<%= if media_file_exists?(@media_item) do %> <%= if media_file_exists?(@media_item) do %>
<section class="grid grid-cols-1 xl:grid-cols-2 xl:gap-6 mt-6"> <section class="grid grid-cols-1 xl:gap-6 mt-6">
<div> <div>
<.media_preview media_item={@media_item} /> <.media_preview media_item={@media_item} />
</div> </div>
<aside class="mt-4 xl:mt-0"> <aside class="mt-4">
<h2 class="text-xl mb-2"><%= @media_item.title %></h2>
<div>Uploaded: <%= DateTime.to_date(@media_item.uploaded_at) %></div> <div>Uploaded: <%= DateTime.to_date(@media_item.uploaded_at) %></div>
<div> <div>
<span :if={URI.parse(@media_item.original_url).scheme =~ "http"}> <span :if={URI.parse(@media_item.original_url).scheme =~ "http"}>
@@ -38,13 +39,16 @@
<span class="mx-2">or</span> <span class="mx-2">or</span>
</span> </span>
<span> <span>
<.subtle_link href={~p"/media/#{@media_item.uuid}/stream"} target="_blank"> <.subtle_link
href={~p"/media/#{@media_item.uuid}/stream?v=#{DateTime.to_unix(@media_item.updated_at)}"}
target="_blank"
>
Open Local Stream Open Local Stream
</.subtle_link> </.subtle_link>
</span> </span>
</div> </div>
<div :if={@media_item.description} class="mt-4 text-bodydark"> <div :if={@media_item.description} class="mt-4 text-bodydark">
<.break_on_newline text={@media_item.description} /> <.render_description text={@media_item.description} />
</div> </div>
</aside> </aside>
</section> </section>
@@ -70,7 +74,7 @@
<%= task.job.state %> <%= task.job.state %>
</:col> </:col>
<:col :let={task} label="Scheduled At"> <:col :let={task} label="Scheduled At">
<%= Calendar.strftime(task.job.scheduled_at, "%y-%m-%d %I:%M:%S %p %Z") %> <.datetime_in_zone datetime={task.job.scheduled_at} />
</:col> </:col>
</.table> </.table>
<% else %> <% else %>
@@ -1,26 +1,51 @@
defmodule PinchflatWeb.MediaProfiles.MediaProfileController do defmodule PinchflatWeb.MediaProfiles.MediaProfileController do
use PinchflatWeb, :controller use PinchflatWeb, :controller
use Pinchflat.Sources.SourcesQuery use Pinchflat.Sources.SourcesQuery
use Pinchflat.Profiles.ProfilesQuery
alias Pinchflat.Repo alias Pinchflat.Repo
alias Pinchflat.Profiles alias Pinchflat.Profiles
alias Pinchflat.Sources.Source
alias Pinchflat.Profiles.MediaProfile alias Pinchflat.Profiles.MediaProfile
alias Pinchflat.Profiles.MediaProfileDeletionWorker alias Pinchflat.Profiles.MediaProfileDeletionWorker
def index(conn, _params) do def index(conn, _params) do
media_profiles = media_profiles_query =
MediaProfile from mp in MediaProfile,
|> where([mp], is_nil(mp.marked_for_deletion_at)) as: :media_profile,
|> order_by(asc: :name) where: is_nil(mp.marked_for_deletion_at),
|> Repo.all() order_by: [asc: mp.name],
select: map(mp, ^MediaProfile.__schema__(:fields)),
select_merge: %{
source_count:
subquery(
from s in Source,
where: s.media_profile_id == parent_as(:media_profile).id,
select: count(s.id)
)
}
render(conn, :index, media_profiles: media_profiles) render(conn, :index, media_profiles: Repo.all(media_profiles_query))
end end
def new(conn, _params) do def new(conn, params) do
changeset = Profiles.change_media_profile(%MediaProfile{}) # Preload an existing media profile for faster creation
cs_struct =
case to_string(params["template_id"]) do
"" -> %MediaProfile{}
template_id -> Repo.get(MediaProfile, template_id) || %MediaProfile{}
end
render(conn, :new, changeset: changeset, layout: get_onboarding_layout()) render(conn, :new,
layout: get_onboarding_layout(),
changeset:
Profiles.change_media_profile(%MediaProfile{
cs_struct
| id: nil,
name: nil,
marked_for_deletion_at: nil
})
)
end end
def create(conn, %{"media_profile" => media_profile_params}) do def create(conn, %{"media_profile" => media_profile_params}) do
@@ -10,6 +10,7 @@ defmodule PinchflatWeb.MediaProfiles.MediaProfileHTML do
""" """
attr :changeset, Ecto.Changeset, required: true attr :changeset, Ecto.Changeset, required: true
attr :action, :string, required: true attr :action, :string, required: true
attr :method, :string, required: true
def media_profile_form(assigns) def media_profile_form(assigns)
@@ -2,7 +2,7 @@
<:option> <:option>
<span x-data="{ copied: false }" x-on:click={~s" <span x-data="{ copied: false }" x-on:click={~s"
copyWithCallbacks( copyWithCallbacks(
`#{Jason.Formatter.pretty_print(Phoenix.json_library().encode!(@media_profile))}`, String.raw`#{Jason.Formatter.pretty_print(Phoenix.json_library().encode!(@media_profile))}`,
() => copied = true, () => copied = true,
() => copied = false () => copied = false
) )
@@ -11,6 +11,11 @@
<span x-show="copied" x-transition.duration.150ms><.icon name="hero-check" class="ml-2 h-4 w-4" /></span> <span x-show="copied" x-transition.duration.150ms><.icon name="hero-check" class="ml-2 h-4 w-4" /></span>
</span> </span>
</:option> </:option>
<:option>
<.link href={~p"/media_profiles/new?template_id=#{@media_profile}"} method="get">
Use as Template
</.link>
</:option>
<:option> <:option>
<div class="h-px w-full bg-bodydark2"></div> <div class="h-px w-full bg-bodydark2"></div>
</:option> </:option>
@@ -10,7 +10,7 @@
<div class="rounded-sm border border-stroke bg-white px-5 pb-2.5 pt-6 shadow-default dark:border-strokedark dark:bg-boxdark sm:px-7.5 xl:pb-1"> <div class="rounded-sm border border-stroke bg-white px-5 pb-2.5 pt-6 shadow-default dark:border-strokedark dark:bg-boxdark sm:px-7.5 xl:pb-1">
<div class="max-w-full"> <div class="max-w-full">
<div class="flex flex-col gap-10"> <div class="flex flex-col gap-10">
<.media_profile_form changeset={@changeset} action={~p"/media_profiles/#{@media_profile}"} /> <.media_profile_form changeset={@changeset} action={~p"/media_profiles/#{@media_profile}"} method="patch" />
</div> </div>
</div> </div>
</div> </div>
@@ -10,7 +10,6 @@
</.link> </.link>
</nav> </nav>
</div> </div>
<div class="rounded-sm border border-stroke bg-white shadow-default dark:border-strokedark dark:bg-boxdark"> <div class="rounded-sm border border-stroke bg-white shadow-default dark:border-strokedark dark:bg-boxdark">
<div class="max-w-full overflow-x-auto"> <div class="max-w-full overflow-x-auto">
<div class="flex flex-col gap-10 min-w-max"> <div class="flex flex-col gap-10 min-w-max">
@@ -23,6 +22,11 @@
<:col :let={media_profile} label="Preferred Resolution"> <:col :let={media_profile} label="Preferred Resolution">
<%= media_profile.preferred_resolution %> <%= media_profile.preferred_resolution %>
</:col> </:col>
<:col :let={media_profile} label="Sources">
<.subtle_link href={~p"/media_profiles/#{media_profile.id}/#tab-sources"}>
<.localized_number number={media_profile.source_count} />
</.subtle_link>
</:col>
<:col :let={media_profile} label="" class="flex justify-end"> <:col :let={media_profile} label="" class="flex justify-end">
<.icon_link href={~p"/media_profiles/#{media_profile.id}/edit"} icon="hero-pencil-square" class="mr-4" /> <.icon_link href={~p"/media_profiles/#{media_profile.id}/edit"} icon="hero-pencil-square" class="mr-4" />
</:col> </:col>
@@ -2,6 +2,7 @@
:let={f} :let={f}
for={@changeset} for={@changeset}
action={@action} action={@action}
method={@method}
x-data="{ advancedMode: !!JSON.parse(localStorage.getItem('advancedMode')) }" x-data="{ advancedMode: !!JSON.parse(localStorage.getItem('advancedMode')) }"
x-init="$watch('advancedMode', value => localStorage.setItem('advancedMode', JSON.stringify(value)))" x-init="$watch('advancedMode', value => localStorage.setItem('advancedMode', JSON.stringify(value)))"
> >
@@ -124,6 +125,16 @@
/> />
</section> </section>
<section x-show="advancedMode">
<.input
field={f[:audio_track]}
placeholder="de"
type="text"
label="Audio Track Language"
help="Only works if there are multiple audio tracks. Use either a language code, 'original' for the original audio track, or 'default' for YouTube's preference. Or just leave it blank"
/>
</section>
<h3 class="mt-10 text-2xl text-black dark:text-white"> <h3 class="mt-10 text-2xl text-black dark:text-white">
Thumbnail Options Thumbnail Options
</h3> </h3>
@@ -8,7 +8,7 @@
<div class="rounded-sm border border-stroke bg-white px-5 pb-2.5 pt-6 shadow-default dark:border-strokedark dark:bg-boxdark sm:px-7.5 xl:pb-1"> <div class="rounded-sm border border-stroke bg-white px-5 pb-2.5 pt-6 shadow-default dark:border-strokedark dark:bg-boxdark sm:px-7.5 xl:pb-1">
<div class="max-w-full"> <div class="max-w-full">
<div class="flex flex-col gap-10"> <div class="flex flex-col gap-10">
<.media_profile_form changeset={@changeset} action={~p"/media_profiles"} /> <.media_profile_form changeset={@changeset} action={~p"/media_profiles"} method="post" />
</div> </div>
</div> </div>
</div> </div>
@@ -1,12 +1,11 @@
defmodule PinchflatWeb.Sources.SourceController do defmodule PinchflatWeb.Sources.SourceController do
use PinchflatWeb, :controller use PinchflatWeb, :controller
use Pinchflat.Media.MediaQuery use Pinchflat.Sources.SourcesQuery
alias Pinchflat.Repo alias Pinchflat.Repo
alias Pinchflat.Tasks alias Pinchflat.Tasks
alias Pinchflat.Sources alias Pinchflat.Sources
alias Pinchflat.Sources.Source alias Pinchflat.Sources.Source
alias Pinchflat.Media.MediaItem
alias Pinchflat.Profiles.MediaProfile alias Pinchflat.Profiles.MediaProfile
alias Pinchflat.Media.FileSyncingWorker alias Pinchflat.Media.FileSyncingWorker
alias Pinchflat.Sources.SourceDeletionWorker alias Pinchflat.Sources.SourceDeletionWorker
@@ -15,33 +14,7 @@ defmodule PinchflatWeb.Sources.SourceController do
alias Pinchflat.Metadata.SourceMetadataStorageWorker alias Pinchflat.Metadata.SourceMetadataStorageWorker
def index(conn, _params) do def index(conn, _params) do
source_query = render(conn, :index)
from s in Source,
as: :source,
inner_join: mp in assoc(s, :media_profile),
where: is_nil(s.marked_for_deletion_at) and is_nil(mp.marked_for_deletion_at),
preload: [media_profile: mp],
order_by: [asc: s.custom_name],
select: map(s, ^Source.__schema__(:fields)),
select_merge: %{
downloaded_count:
subquery(
from m in MediaItem,
where: m.source_id == parent_as(:source).id,
where: ^MediaQuery.downloaded(),
select: count(m.id)
),
pending_count:
subquery(
from m in MediaItem,
join: s in assoc(m, :source),
where: m.source_id == parent_as(:source).id,
where: ^MediaQuery.pending(),
select: count(m.id)
)
}
render(conn, :index, sources: Repo.all(source_query))
end end
def new(conn, params) do def new(conn, params) do
@@ -67,7 +40,8 @@ defmodule PinchflatWeb.Sources.SourceController do
collection_name: nil, collection_name: nil,
collection_id: nil, collection_id: nil,
collection_type: nil, collection_type: nil,
original_url: nil original_url: nil,
marked_for_deletion_at: nil
}) })
) )
end end
@@ -17,7 +17,7 @@
<:option> <:option>
<span x-data="{ copied: false }" x-on:click={~s" <span x-data="{ copied: false }" x-on:click={~s"
copyWithCallbacks( copyWithCallbacks(
`#{Jason.Formatter.pretty_print(Phoenix.json_library().encode!(@source))}`, String.raw`#{Jason.Formatter.pretty_print(Phoenix.json_library().encode!(@source))}`,
() => copied = true, () => copied = true,
() => copied = false () => copied = false
) )
@@ -12,32 +12,7 @@
<div class="rounded-sm border border-stroke bg-white shadow-default dark:border-strokedark dark:bg-boxdark"> <div class="rounded-sm border border-stroke bg-white shadow-default dark:border-strokedark dark:bg-boxdark">
<div class="max-w-full overflow-x-auto"> <div class="max-w-full overflow-x-auto">
<div class="flex flex-col gap-10 min-w-max"> <div class="flex flex-col gap-10 min-w-max">
<.table rows={@sources} table_class="text-black dark:text-white"> <%= live_render(@conn, PinchflatWeb.Sources.IndexTableLive) %>
<:col :let={source} label="Name">
<.subtle_link href={~p"/sources/#{source.id}"}>
<%= StringUtils.truncate(source.custom_name || source.collection_name, 35) %>
</.subtle_link>
</:col>
<:col :let={source} label="Type"><%= source.collection_type %></:col>
<:col :let={source} label="Pending"><.localized_number number={source.pending_count} /></:col>
<:col :let={source} label="Downloaded"><.localized_number number={source.downloaded_count} /></:col>
<:col :let={source} label="Retention">
<%= if source.retention_period_days && source.retention_period_days > 0 do %>
<.localized_number number={source.retention_period_days} />
<.pluralize count={source.retention_period_days} word="day" />
<% else %>
<span class="text-lg">∞</span>
<% end %>
</:col>
<:col :let={source} label="Media Profile">
<.subtle_link href={~p"/media_profiles/#{source.media_profile_id}"}>
<%= source.media_profile.name %>
</.subtle_link>
</:col>
<:col :let={source} label="" class="flex place-content-evenly">
<.icon_link href={~p"/sources/#{source.id}/edit"} icon="hero-pencil-square" class="mx-1" />
</:col>
</.table>
</div> </div>
</div> </div>
</div> </div>
@@ -0,0 +1,103 @@
defmodule PinchflatWeb.Sources.IndexTableLive do
use PinchflatWeb, :live_view
use Pinchflat.Media.MediaQuery
use Pinchflat.Sources.SourcesQuery
alias Pinchflat.Repo
alias Pinchflat.Sources
alias Pinchflat.Sources.Source
alias Pinchflat.Media.MediaItem
def render(assigns) do
~H"""
<.table rows={@sources} table_class="text-white">
<:col :let={source} label="Name">
<.subtle_link href={~p"/sources/#{source.id}"}>
<%= StringUtils.truncate(source.custom_name || source.collection_name, 35) %>
</.subtle_link>
</:col>
<:col :let={source} label="Pending">
<.subtle_link href={~p"/sources/#{source.id}/#tab-pending"}>
<.localized_number number={source.pending_count} />
</.subtle_link>
</:col>
<:col :let={source} label="Downloaded">
<.subtle_link href={~p"/sources/#{source.id}/#tab-downloaded"}>
<.localized_number number={source.downloaded_count} />
</.subtle_link>
</:col>
<:col :let={source} label="Retention">
<%= if source.retention_period_days && source.retention_period_days > 0 do %>
<.localized_number number={source.retention_period_days} />
<.pluralize count={source.retention_period_days} word="day" />
<% else %>
<span class="text-lg">∞</span>
<% end %>
</:col>
<:col :let={source} label="Media Profile">
<.subtle_link href={~p"/media_profiles/#{source.media_profile_id}"}>
<%= source.media_profile.name %>
</.subtle_link>
</:col>
<:col :let={source} label="Enabled?">
<.input
name={"source[#{source.id}][enabled]"}
value={source.enabled}
id={"source_#{source.id}_enabled"}
phx-hook="formless-input"
data-subscribe="change"
data-event-name="toggle_enabled"
data-identifier={source.id}
type="toggle"
/>
</:col>
<:col :let={source} label="" class="flex place-content-evenly">
<.icon_link href={~p"/sources/#{source.id}/edit"} icon="hero-pencil-square" class="mx-1" />
</:col>
</.table>
"""
end
def mount(_params, _session, socket) do
{:ok, assign(socket, %{sources: get_sources()})}
end
def handle_event("formless-input", %{"event" => "toggle_enabled"} = params, socket) do
source = Sources.get_source!(params["id"])
should_enable = params["value"] == "true"
{:ok, _} = Sources.update_source(source, %{enabled: should_enable})
{:noreply, assign(socket, %{sources: get_sources()})}
end
defp get_sources do
query =
from s in Source,
as: :source,
inner_join: mp in assoc(s, :media_profile),
where: is_nil(s.marked_for_deletion_at) and is_nil(mp.marked_for_deletion_at),
preload: [media_profile: mp],
order_by: [asc: s.custom_name],
select: map(s, ^Source.__schema__(:fields)),
select_merge: %{
downloaded_count:
subquery(
from m in MediaItem,
where: m.source_id == parent_as(:source).id,
where: ^MediaQuery.downloaded(),
select: count(m.id)
),
pending_count:
subquery(
from m in MediaItem,
join: s in assoc(m, :source),
where: m.source_id == parent_as(:source).id,
where: ^MediaQuery.pending(),
select: count(m.id)
)
}
Repo.all(query)
end
end
@@ -1,4 +1,4 @@
defmodule Pinchflat.Sources.MediaItemTableLive do defmodule PinchflatWeb.Sources.MediaItemTableLive do
use PinchflatWeb, :live_view use PinchflatWeb, :live_view
use Pinchflat.Media.MediaQuery use Pinchflat.Media.MediaQuery
@@ -39,21 +39,21 @@
<:tab title="Pending" id="pending"> <:tab title="Pending" id="pending">
<%= live_render( <%= live_render(
@conn, @conn,
Pinchflat.Sources.MediaItemTableLive, PinchflatWeb.Sources.MediaItemTableLive,
session: %{"source_id" => @source.id, "media_state" => "pending"} session: %{"source_id" => @source.id, "media_state" => "pending"}
) %> ) %>
</:tab> </:tab>
<:tab title="Downloaded" id="downloaded"> <:tab title="Downloaded" id="downloaded">
<%= live_render( <%= live_render(
@conn, @conn,
Pinchflat.Sources.MediaItemTableLive, PinchflatWeb.Sources.MediaItemTableLive,
session: %{"source_id" => @source.id, "media_state" => "downloaded"} session: %{"source_id" => @source.id, "media_state" => "downloaded"}
) %> ) %>
</:tab> </:tab>
<:tab title="Other" id="other"> <:tab title="Other" id="other">
<%= live_render( <%= live_render(
@conn, @conn,
Pinchflat.Sources.MediaItemTableLive, PinchflatWeb.Sources.MediaItemTableLive,
session: %{"source_id" => @source.id, "media_state" => "other"} session: %{"source_id" => @source.id, "media_state" => "other"}
) %> ) %>
</:tab> </:tab>
@@ -67,7 +67,7 @@
<%= task.job.state %> <%= task.job.state %>
</:col> </:col>
<:col :let={task} label="Scheduled At"> <:col :let={task} label="Scheduled At">
<%= Calendar.strftime(task.job.scheduled_at, "%y-%m-%d %I:%M:%S %p %Z") %> <.datetime_in_zone datetime={task.job.scheduled_at} />
</:col> </:col>
</.table> </.table>
<% else %> <% else %>
+1 -1
View File
@@ -4,7 +4,7 @@ defmodule Pinchflat.MixProject do
def project do def project do
[ [
app: :pinchflat, app: :pinchflat,
version: "2024.10.2", version: "2024.11.27",
elixir: "~> 1.17", elixir: "~> 1.17",
elixirc_paths: elixirc_paths(Mix.env()), elixirc_paths: elixirc_paths(Mix.env()),
start_permanent: Mix.env() == :prod, start_permanent: Mix.env() == :prod,
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 433 KiB

After

Width:  |  Height:  |  Size: 438 KiB

@@ -0,0 +1,9 @@
defmodule Pinchflat.Repo.Migrations.AddPredictedMediaFilepathToMediaItems do
use Ecto.Migration
def change do
alter table(:media_items) do
add :predicted_media_filepath, :string
end
end
end
@@ -0,0 +1,9 @@
defmodule Pinchflat.Repo.Migrations.AddEnabledToSources do
use Ecto.Migration
def change do
alter table(:sources) do
add :enabled, :boolean, default: true, null: false
end
end
end
@@ -0,0 +1,9 @@
defmodule Pinchflat.Repo.Migrations.AddAudioLangToMediaProfiles do
use Ecto.Migration
def change do
alter table(:media_profiles) do
add :audio_track, :string
end
end
end
@@ -9,6 +9,7 @@ defmodule Pinchflat.Boot.PreJobStartupTasksTest do
setup do setup do
stub(YtDlpRunnerMock, :version, fn -> {:ok, "1"} end) stub(YtDlpRunnerMock, :version, fn -> {:ok, "1"} end)
stub(AppriseRunnerMock, :version, fn -> {:ok, "2"} end) stub(AppriseRunnerMock, :version, fn -> {:ok, "2"} end)
stub(UserScriptRunnerMock, :run, fn _event_type, _data -> {:ok, "3", 0} end)
:ok :ok
end end
@@ -112,4 +113,16 @@ defmodule Pinchflat.Boot.PreJobStartupTasksTest do
assert Settings.get!(:apprise_version) assert Settings.get!(:apprise_version)
end end
end end
describe "run_app_init_script" do
test "calls the app_init user script runner" do
expect(UserScriptRunnerMock, :run, fn :app_init, data ->
assert data == %{}
{:ok, "", 0}
end)
PreJobStartupTasks.init(%{})
end
end
end end
@@ -6,7 +6,6 @@ defmodule Pinchflat.Downloading.DownloadOptionBuilderTest do
alias Pinchflat.Sources alias Pinchflat.Sources
alias Pinchflat.Profiles alias Pinchflat.Profiles
alias Pinchflat.Settings
alias Pinchflat.Utils.FilesystemUtils alias Pinchflat.Utils.FilesystemUtils
alias Pinchflat.Downloading.DownloadOptionBuilder alias Pinchflat.Downloading.DownloadOptionBuilder
@@ -253,21 +252,14 @@ defmodule Pinchflat.Downloading.DownloadOptionBuilderTest do
end end
describe "build/1 when testing media quality and format options" do describe "build/1 when testing media quality and format options" do
test "includes quality options" do # There are more tests inside QualityOptionBuilderTest
resolutions = ["360", "480", "720", "1080", "2160", "4320"] # This is essenitally just testing that we implement that module correctly
Enum.each(resolutions, fn resolution ->
resolution_atom = String.to_existing_atom(resolution <> "p")
media_profile = media_profile_fixture(%{preferred_resolution: resolution_atom})
source = source_fixture(%{media_profile_id: media_profile.id})
media_item = Repo.preload(media_item_fixture(source_id: source.id), source: :media_profile)
test "includes video options for video profiles", %{media_item: media_item} do
assert {:ok, res} = DownloadOptionBuilder.build(media_item) assert {:ok, res} = DownloadOptionBuilder.build(media_item)
assert {:format_sort, "res:#{resolution},+codec:avc:m4a"} in res assert {:format_sort, "res:1080,+codec:avc:m4a"} in res
assert {:remux_video, "mp4"} in res assert {:remux_video, "mp4"} in res
end)
end end
test "includes quality options for audio only", %{media_item: media_item} do test "includes quality options for audio only", %{media_item: media_item} do
@@ -280,33 +272,6 @@ defmodule Pinchflat.Downloading.DownloadOptionBuilderTest do
refute {:remux_video, "mp4"} in res refute {:remux_video, "mp4"} in res
end end
test "includes custom quality options if specified", %{media_item: media_item} do
Settings.set(video_codec_preference: "av01")
Settings.set(audio_codec_preference: "aac")
media_item = update_media_profile_attribute(media_item, %{preferred_resolution: :"1080p"})
assert {:ok, res} = DownloadOptionBuilder.build(media_item)
assert {:format_sort, "res:1080,+codec:av01:aac"} in res
end
test "includes custom remux target for videos if specified", %{media_item: media_item} do
media_item = update_media_profile_attribute(media_item, %{media_container: "mkv"})
assert {:ok, res} = DownloadOptionBuilder.build(media_item)
assert {:remux_video, "mkv"} in res
end
test "includes custom format target for audio if specified", %{media_item: media_item} do
media_item = update_media_profile_attribute(media_item, %{media_container: "flac", preferred_resolution: :audio})
assert {:ok, res} = DownloadOptionBuilder.build(media_item)
assert {:audio_format, "flac"} in res
end
end end
describe "build/1 when testing sponsorblock options" do describe "build/1 when testing sponsorblock options" do
@@ -461,6 +426,22 @@ defmodule Pinchflat.Downloading.DownloadOptionBuilderTest do
end end
end end
describe "build_quality_options_for/1" do
test "builds quality options for a media item", %{media_item: media_item} do
options = DownloadOptionBuilder.build_quality_options_for(media_item)
assert {:format_sort, "res:1080,+codec:avc:m4a"} in options
assert {:remux_video, "mp4"} in options
end
test "builds quality options for a source", %{media_item: media_item} do
options = DownloadOptionBuilder.build_quality_options_for(media_item.source)
assert {:format_sort, "res:1080,+codec:avc:m4a"} in options
assert {:remux_video, "mp4"} in options
end
end
defp update_media_profile_attribute(media_item_with_preloads, attrs) do defp update_media_profile_attribute(media_item_with_preloads, attrs) do
media_item_with_preloads.source.media_profile media_item_with_preloads.source.media_profile
|> Profiles.change_media_profile(attrs) |> Profiles.change_media_profile(attrs)
@@ -9,6 +9,7 @@ defmodule Pinchflat.Downloading.MediaDownloadWorkerTest do
alias Pinchflat.Downloading.MediaDownloadWorker alias Pinchflat.Downloading.MediaDownloadWorker
setup do setup do
stub(YtDlpRunnerMock, :run, fn _url, _opts, _ot -> {:ok, "{}"} end)
stub(YtDlpRunnerMock, :run, fn _url, _opts, _ot, _addl -> {:ok, ""} end) stub(YtDlpRunnerMock, :run, fn _url, _opts, _ot, _addl -> {:ok, ""} end)
stub(UserScriptRunnerMock, :run, fn _event_type, _data -> {:ok, "", 0} end) stub(UserScriptRunnerMock, :run, fn _event_type, _data -> {:ok, "", 0} end)
stub(HTTPClientMock, :get, fn _url, _headers, _opts -> {:ok, ""} end) stub(HTTPClientMock, :get, fn _url, _headers, _opts -> {:ok, ""} end)
@@ -186,6 +187,20 @@ defmodule Pinchflat.Downloading.MediaDownloadWorkerTest do
end end
end end
describe "perform/1 when testing non-downloadable media" do
test "does not retry the job if the media is currently not downloadable", %{media_item: media_item} do
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot ->
{:ok, Phoenix.json_library().encode!(%{"live_status" => "is_live"})}
end)
Oban.Testing.with_testing_mode(:inline, fn ->
{:ok, job} = Oban.insert(MediaDownloadWorker.new(%{id: media_item.id}))
assert job.state == "completed"
end)
end
end
describe "perform/1 when testing forced downloads" do describe "perform/1 when testing forced downloads" do
test "ignores 'prevent_download' if forced", %{media_item: media_item} do test "ignores 'prevent_download' if forced", %{media_item: media_item} do
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot, _addl -> :ok end) expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot, _addl -> :ok end)
@@ -16,6 +16,7 @@ defmodule Pinchflat.Downloading.MediaDownloaderTest do
) )
stub(HTTPClientMock, :get, fn _url, _headers, _opts -> {:ok, ""} end) stub(HTTPClientMock, :get, fn _url, _headers, _opts -> {:ok, ""} end)
stub(YtDlpRunnerMock, :run, fn _url, _opts, _ot -> {:ok, "{}"} end)
stub(YtDlpRunnerMock, :run, fn _url, _opts, _ot, _addl_args -> {:ok, ""} end) stub(YtDlpRunnerMock, :run, fn _url, _opts, _ot, _addl_args -> {:ok, ""} end)
{:ok, %{media_item: media_item}} {:ok, %{media_item: media_item}}
@@ -49,6 +50,14 @@ defmodule Pinchflat.Downloading.MediaDownloaderTest do
assert updated_media_item.metadata.thumbnail_filepath =~ "media_items/#{media_item.id}/thumbnail.jpg" assert updated_media_item.metadata.thumbnail_filepath =~ "media_items/#{media_item.id}/thumbnail.jpg"
end end
test "errors for non-downloadable media are passed through", %{media_item: media_item} do
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot ->
{:ok, Phoenix.json_library().encode!(%{"live_status" => "is_live"})}
end)
assert {:error, :unsuitable_for_download} = MediaDownloader.download_for_media_item(media_item)
end
test "non-recoverable errors are passed through", %{media_item: media_item} do test "non-recoverable errors are passed through", %{media_item: media_item} do
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot, _addl -> expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot, _addl ->
{:error, :some_error, 1} {:error, :some_error, 1}
@@ -67,6 +76,36 @@ defmodule Pinchflat.Downloading.MediaDownloaderTest do
end end
end end
describe "download_for_media_item/3 when testing non-downloadable media" do
test "calls the download runner if the media is currently downloadable", %{media_item: media_item} do
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot ->
{:ok, Phoenix.json_library().encode!(%{"live_status" => "was_live"})}
end)
expect(YtDlpRunnerMock, :run, 2, fn _url, _opts, _ot, _addl ->
{:ok, render_metadata(:media_metadata)}
end)
assert {:ok, _} = MediaDownloader.download_for_media_item(media_item)
end
test "does not call the download runner if the media is not downloadable", %{media_item: media_item} do
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot ->
{:ok, Phoenix.json_library().encode!(%{"live_status" => "is_live"})}
end)
expect(YtDlpRunnerMock, :run, 0, fn _url, _opts, _ot, _addl -> {:ok, ""} end)
assert {:error, :unsuitable_for_download} = MediaDownloader.download_for_media_item(media_item)
end
test "returns unexpected errors from the download status determination method", %{media_item: media_item} do
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot -> {:error, :what_tha} end)
assert {:error, "Unknown error: {:error, :what_tha}"} = MediaDownloader.download_for_media_item(media_item)
end
end
describe "download_for_media_item/3 when testing override options" do describe "download_for_media_item/3 when testing override options" do
test "includes override opts if specified", %{media_item: media_item} do test "includes override opts if specified", %{media_item: media_item} do
expect(YtDlpRunnerMock, :run, 1, fn _url, opts, _ot, _addl -> expect(YtDlpRunnerMock, :run, 1, fn _url, opts, _ot, _addl ->
@@ -46,6 +46,23 @@ defmodule Pinchflat.Downloading.MediaRetentionWorkerTest do
refute Repo.reload!(old_media_item).media_filepath refute Repo.reload!(old_media_item).media_filepath
end end
test "deletes media files that are on their retention date per the 24-h clock" do
{_source, old_media_item, new_media_item} = prepare_records_for_retention_date(2)
just_over_two_days_ago = now_minus(2, :days) |> DateTime.add(-1, :minute)
just_under_two_days_ago = now_minus(2, :days) |> DateTime.add(1, :minute)
Media.update_media_item(old_media_item, %{media_downloaded_at: just_over_two_days_ago})
Media.update_media_item(new_media_item, %{media_downloaded_at: just_under_two_days_ago})
perform_job(MediaRetentionWorker, %{})
assert File.exists?(new_media_item.media_filepath)
refute File.exists?(old_media_item.media_filepath)
assert Repo.reload!(new_media_item).media_filepath
refute Repo.reload!(old_media_item).media_filepath
end
test "sets culled_at and prevent_download" do test "sets culled_at and prevent_download" do
{_source, old_media_item, new_media_item} = prepare_records_for_retention_date() {_source, old_media_item, new_media_item} = prepare_records_for_retention_date()
@@ -106,6 +123,25 @@ defmodule Pinchflat.Downloading.MediaRetentionWorkerTest do
refute Repo.reload!(old_media_item).media_filepath refute Repo.reload!(old_media_item).media_filepath
end end
# NOTE: Since this is a date and not a datetime, we can't add logic to have to-the-minute
# comparison like we can with retention periods. We can only compare to the day.
test "doesn't cull media from on or after the cutoff date" do
{_source, old_media_item, new_media_item} = prepare_records_for_source_cutoff_date(2)
Media.update_media_item(old_media_item, %{uploaded_at: now_minus(2, :days)})
Media.update_media_item(new_media_item, %{uploaded_at: now_minus(1, :day)})
perform_job(MediaRetentionWorker, %{})
assert File.exists?(new_media_item.media_filepath)
assert File.exists?(old_media_item.media_filepath)
assert Repo.reload!(new_media_item).media_filepath
assert Repo.reload!(old_media_item).media_filepath
refute Repo.reload!(new_media_item).culled_at
refute Repo.reload!(old_media_item).culled_at
end
test "sets culled_at but not prevent_download" do test "sets culled_at but not prevent_download" do
{_source, old_media_item, new_media_item} = prepare_records_for_source_cutoff_date() {_source, old_media_item, new_media_item} = prepare_records_for_source_cutoff_date()
@@ -131,23 +167,6 @@ defmodule Pinchflat.Downloading.MediaRetentionWorkerTest do
refute Repo.reload!(old_media_item).culled_at refute Repo.reload!(old_media_item).culled_at
end end
test "doesn't cull media from on or after the cutoff date" do
{_source, old_media_item, new_media_item} = prepare_records_for_source_cutoff_date(2)
Media.update_media_item(old_media_item, %{uploaded_at: now_minus(2, :days)})
Media.update_media_item(new_media_item, %{uploaded_at: now_minus(1, :day)})
perform_job(MediaRetentionWorker, %{})
assert File.exists?(new_media_item.media_filepath)
assert File.exists?(old_media_item.media_filepath)
assert Repo.reload!(new_media_item).media_filepath
assert Repo.reload!(old_media_item).media_filepath
refute Repo.reload!(new_media_item).culled_at
refute Repo.reload!(old_media_item).culled_at
end
test "doesn't cull media items that have prevent_culling set" do test "doesn't cull media items that have prevent_culling set" do
{_source, old_media_item, _new_media_item} = prepare_records_for_source_cutoff_date() {_source, old_media_item, _new_media_item} = prepare_records_for_source_cutoff_date()
@@ -0,0 +1,109 @@
defmodule Pinchflat.Downloading.QualityOptionBuilderTest do
use Pinchflat.DataCase
import Pinchflat.ProfilesFixtures
alias Pinchflat.Profiles
alias Pinchflat.Settings
alias Pinchflat.Downloading.QualityOptionBuilder
describe "build/1" do
test "includes format options if audio_track is set to original" do
media_profile = media_profile_fixture(%{audio_track: "original"})
assert res = QualityOptionBuilder.build(media_profile)
assert {:format, "bestvideo+bestaudio[format_note*=original]/bestvideo*+bestaudio/best"} in res
end
test "includes format options if audio_track is set to default" do
media_profile = media_profile_fixture(%{audio_track: "default"})
assert res = QualityOptionBuilder.build(media_profile)
assert {:format, "bestvideo+bestaudio[format_note*='(default)']/bestvideo*+bestaudio/best"} in res
end
test "includes format options if audio_track is set to a language code" do
media_profile = media_profile_fixture(%{audio_track: "en"})
assert res = QualityOptionBuilder.build(media_profile)
assert {:format, "bestvideo+bestaudio[language^=en]/bestvideo*+bestaudio/best"} in res
end
end
describe "build/1 when testing audio profiles" do
setup do
{:ok, media_profile: media_profile_fixture(%{preferred_resolution: :audio})}
end
test "includes quality options for audio only", %{media_profile: media_profile} do
assert res = QualityOptionBuilder.build(media_profile)
assert :extract_audio in res
assert {:format_sort, "+acodec:m4a"} in res
refute {:remux_video, "mp4"} in res
end
test "includes custom format target for audio if specified", %{media_profile: media_profile} do
{:ok, media_profile} =
Profiles.update_media_profile(media_profile, %{media_container: "flac", preferred_resolution: :audio})
assert res = QualityOptionBuilder.build(media_profile)
assert {:audio_format, "flac"} in res
end
test "includes custom format options", %{media_profile: media_profile} do
assert res = QualityOptionBuilder.build(media_profile)
assert {:format, "bestaudio/best"} in res
end
end
describe "build/1 when testing non-audio profiles" do
setup do
{:ok, media_profile: media_profile_fixture(%{preferred_resolution: :"480p"})}
end
test "includes quality options" do
resolutions = ["360", "480", "720", "1080", "2160", "4320"]
Enum.each(resolutions, fn resolution ->
resolution_atom = String.to_existing_atom(resolution <> "p")
media_profile = media_profile_fixture(%{preferred_resolution: resolution_atom})
assert res = QualityOptionBuilder.build(media_profile)
assert {:format_sort, "res:#{resolution},+codec:avc:m4a"} in res
assert {:remux_video, "mp4"} in res
end)
end
test "includes custom quality options if specified", %{media_profile: media_profile} do
Settings.set(video_codec_preference: "av01")
Settings.set(audio_codec_preference: "aac")
{:ok, media_profile} = Profiles.update_media_profile(media_profile, %{preferred_resolution: :"1080p"})
assert res = QualityOptionBuilder.build(media_profile)
assert {:format_sort, "res:1080,+codec:av01:aac"} in res
end
test "includes custom remux target for videos if specified", %{media_profile: media_profile} do
{:ok, media_profile} = Profiles.update_media_profile(media_profile, %{media_container: "mkv"})
assert res = QualityOptionBuilder.build(media_profile)
assert {:remux_video, "mkv"} in res
end
test "includes custom format options", %{media_profile: media_profile} do
assert res = QualityOptionBuilder.build(media_profile)
assert {:format, "bestvideo*+bestaudio/best"} in res
end
end
end
@@ -1,6 +1,7 @@
defmodule Pinchflat.FastIndexing.FastIndexingHelpersTest do defmodule Pinchflat.FastIndexing.FastIndexingHelpersTest do
use Pinchflat.DataCase use Pinchflat.DataCase
import Pinchflat.TasksFixtures
import Pinchflat.MediaFixtures import Pinchflat.MediaFixtures
import Pinchflat.SourcesFixtures import Pinchflat.SourcesFixtures
import Pinchflat.ProfilesFixtures import Pinchflat.ProfilesFixtures
@@ -8,6 +9,7 @@ defmodule Pinchflat.FastIndexing.FastIndexingHelpersTest do
alias Pinchflat.Tasks alias Pinchflat.Tasks
alias Pinchflat.Settings alias Pinchflat.Settings
alias Pinchflat.Media.MediaItem alias Pinchflat.Media.MediaItem
alias Pinchflat.FastIndexing.FastIndexingWorker
alias Pinchflat.Downloading.MediaDownloadWorker alias Pinchflat.Downloading.MediaDownloadWorker
alias Pinchflat.FastIndexing.FastIndexingHelpers alias Pinchflat.FastIndexing.FastIndexingHelpers
@@ -19,6 +21,23 @@ defmodule Pinchflat.FastIndexing.FastIndexingHelpersTest do
{:ok, [source: source_fixture()]} {:ok, [source: source_fixture()]}
end end
describe "kickoff_indexing_task/1" do
test "deletes any existing fast indexing tasks", %{source: source} do
{:ok, job} = Oban.insert(FastIndexingWorker.new(%{"id" => source.id}))
task = task_fixture(source_id: source.id, job_id: job.id)
assert Repo.reload!(task)
assert {:ok, _} = FastIndexingHelpers.kickoff_indexing_task(source)
assert_raise Ecto.NoResultsError, fn -> Repo.reload!(task) end
end
test "kicks off a new fast indexing task", %{source: source} do
assert {:ok, _} = FastIndexingHelpers.kickoff_indexing_task(source)
assert [worker] = all_enqueued(worker: FastIndexingWorker)
assert worker.args["id"] == source.id
end
end
describe "kickoff_download_tasks_from_youtube_rss_feed/1" do describe "kickoff_download_tasks_from_youtube_rss_feed/1" do
test "enqueues a new worker for each new media_id in the source's RSS feed", %{source: source} do test "enqueues a new worker for each new media_id in the source's RSS feed", %{source: source} do
expect(HTTPClientMock, :get, fn _url -> {:ok, "<yt:videoId>test_1</yt:videoId>"} end) expect(HTTPClientMock, :get, fn _url -> {:ok, "<yt:videoId>test_1</yt:videoId>"} end)
@@ -61,6 +80,18 @@ defmodule Pinchflat.FastIndexing.FastIndexingHelpersTest do
assert [_] = Tasks.list_tasks_for(media_item, "MediaDownloadWorker") assert [_] = Tasks.list_tasks_for(media_item, "MediaDownloadWorker")
end end
test "passes the source's download options to the yt-dlp runner", %{source: source} do
expect(HTTPClientMock, :get, fn _url -> {:ok, "<yt:videoId>test_1</yt:videoId>"} end)
expect(YtDlpRunnerMock, :run, fn _url, opts, _ot, _addl_opts ->
assert {:output, "/tmp/test/media/%(title)S.%(ext)S"} in opts
assert {:remux_video, "mp4"} in opts
{:ok, media_attributes_return_fixture()}
end)
FastIndexingHelpers.kickoff_download_tasks_from_youtube_rss_feed(source)
end
test "sets use_cookies if the source uses cookies" do test "sets use_cookies if the source uses cookies" do
expect(HTTPClientMock, :get, fn _url -> {:ok, "<yt:videoId>test_1</yt:videoId>"} end) expect(HTTPClientMock, :get, fn _url -> {:ok, "<yt:videoId>test_1</yt:videoId>"} end)
@@ -100,7 +131,7 @@ defmodule Pinchflat.FastIndexing.FastIndexingHelpersTest do
Phoenix.json_library().encode!(%{ Phoenix.json_library().encode!(%{
id: "video2", id: "video2",
title: "Video 2", title: "Video 2",
webpage_url: "https://example.com/shorts/video2", original_url: "https://example.com/shorts/video2",
live_status: "is_live", live_status: "is_live",
description: "desc2", description: "desc2",
aspect_ratio: 1.67, aspect_ratio: 1.67,
+22
View File
@@ -441,6 +441,13 @@ defmodule Pinchflat.MediaTest do
assert Media.pending_download?(media_item) assert Media.pending_download?(media_item)
end end
test "returns true if the cutoff date is equal to the upload date" do
source = source_fixture(%{download_cutoff_date: now_minus(2, :days)})
media_item = media_item_fixture(%{source_id: source.id, media_filepath: nil, uploaded_at: now_minus(2, :days)})
assert Media.pending_download?(media_item)
end
test "returns false if there is a cutoff date after the media's upload date" do test "returns false if there is a cutoff date after the media's upload date" do
source = source_fixture(%{download_cutoff_date: now_minus(1, :day)}) source = source_fixture(%{download_cutoff_date: now_minus(1, :day)})
media_item = media_item_fixture(%{source_id: source.id, media_filepath: nil, uploaded_at: now_minus(2, :days)}) media_item = media_item_fixture(%{source_id: source.id, media_filepath: nil, uploaded_at: now_minus(2, :days)})
@@ -705,6 +712,21 @@ defmodule Pinchflat.MediaTest do
assert media_item.media_filepath == update_attrs.media_filepath assert media_item.media_filepath == update_attrs.media_filepath
end end
test "updating strips playlist_index from the provided attrs" do
media_item = media_item_fixture(playlist_index: 5)
update_attrs = %{
media_id: Faker.String.base64(12),
title: Faker.Commerce.product_name(),
media_filepath: "/video/#{Faker.File.file_name(:video)}",
source_id: source_fixture().id,
playlist_index: 1
}
assert {:ok, %MediaItem{} = media_item} = Media.update_media_item(media_item, update_attrs)
assert media_item.playlist_index == 5
end
test "updating with invalid data returns error changeset" do test "updating with invalid data returns error changeset" do
media_item = media_item_fixture() media_item = media_item_fixture()
assert {:error, %Ecto.Changeset{}} = Media.update_media_item(media_item, @invalid_attrs) assert {:error, %Ecto.Changeset{}} = Media.update_media_item(media_item, @invalid_attrs)
@@ -23,6 +23,36 @@ defmodule Pinchflat.SlowIndexing.SlowIndexingHelpersTest do
assert_enqueued(worker: MediaCollectionIndexingWorker, args: %{"id" => source.id}) assert_enqueued(worker: MediaCollectionIndexingWorker, args: %{"id" => source.id})
end end
test "schedules a job for the future based on when the source was last indexed" do
source = source_fixture(index_frequency_minutes: 30, last_indexed_at: now_minus(5, :minutes))
assert {:ok, _} = SlowIndexingHelpers.kickoff_indexing_task(source)
[job] = all_enqueued(worker: MediaCollectionIndexingWorker, args: %{"id" => source.id})
assert_in_delta DateTime.diff(job.scheduled_at, DateTime.utc_now(), :minute), 25, 1
end
test "schedules a job immediately if the source was indexed far in the past" do
source = source_fixture(index_frequency_minutes: 30, last_indexed_at: now_minus(60, :minutes))
assert {:ok, _} = SlowIndexingHelpers.kickoff_indexing_task(source)
[job] = all_enqueued(worker: MediaCollectionIndexingWorker, args: %{"id" => source.id})
assert_in_delta DateTime.diff(job.scheduled_at, DateTime.utc_now(), :second), 0, 1
end
test "schedules a job immediately if the source has never been indexed" do
source = source_fixture(index_frequency_minutes: 30, last_indexed_at: nil)
assert {:ok, _} = SlowIndexingHelpers.kickoff_indexing_task(source)
[job] = all_enqueued(worker: MediaCollectionIndexingWorker, args: %{"id" => source.id})
assert_in_delta DateTime.diff(job.scheduled_at, DateTime.utc_now(), :second), 0, 1
end
test "creates and attaches a task" do test "creates and attaches a task" do
source = source_fixture(index_frequency_minutes: 1) source = source_fixture(index_frequency_minutes: 1)
@@ -92,6 +122,56 @@ defmodule Pinchflat.SlowIndexing.SlowIndexingHelpersTest do
end end
end end
describe "delete_indexing_tasks/2" do
setup do
source = source_fixture()
{:ok, %{source: source}}
end
test "deletes slow indexing tasks for the source", %{source: source} do
{:ok, job} = Oban.insert(MediaCollectionIndexingWorker.new(%{"id" => source.id}))
_task = task_fixture(source_id: source.id, job_id: job.id)
assert_enqueued(worker: MediaCollectionIndexingWorker, args: %{"id" => source.id})
assert :ok = SlowIndexingHelpers.delete_indexing_tasks(source)
refute_enqueued(worker: MediaCollectionIndexingWorker)
end
test "deletes fast indexing tasks for the source", %{source: source} do
{:ok, job} = Oban.insert(FastIndexingWorker.new(%{"id" => source.id}))
_task = task_fixture(source_id: source.id, job_id: job.id)
assert_enqueued(worker: FastIndexingWorker, args: %{"id" => source.id})
assert :ok = SlowIndexingHelpers.delete_indexing_tasks(source)
refute_enqueued(worker: FastIndexingWorker)
end
test "doesn't normally delete currently executing tasks", %{source: source} do
{:ok, job} = Oban.insert(MediaCollectionIndexingWorker.new(%{"id" => source.id}))
task = task_fixture(source_id: source.id, job_id: job.id)
from(Oban.Job, where: [id: ^job.id], update: [set: [state: "executing"]])
|> Repo.update_all([])
assert Repo.reload!(task)
assert :ok = SlowIndexingHelpers.delete_indexing_tasks(source)
assert Repo.reload!(task)
end
test "can optionally delete currently executing tasks", %{source: source} do
{:ok, job} = Oban.insert(MediaCollectionIndexingWorker.new(%{"id" => source.id}))
task = task_fixture(source_id: source.id, job_id: job.id)
from(Oban.Job, where: [id: ^job.id], update: [set: [state: "executing"]])
|> Repo.update_all([])
assert Repo.reload!(task)
assert :ok = SlowIndexingHelpers.delete_indexing_tasks(source, include_executing: true)
assert_raise Ecto.NoResultsError, fn -> Repo.reload!(task) end
end
end
describe "index_and_enqueue_download_for_media_items/1" do describe "index_and_enqueue_download_for_media_items/1" do
setup do setup do
stub(YtDlpRunnerMock, :run, fn _url, _opts, _ot, _addl_opts -> stub(YtDlpRunnerMock, :run, fn _url, _opts, _ot, _addl_opts ->
@@ -188,7 +268,7 @@ defmodule Pinchflat.SlowIndexing.SlowIndexingHelpersTest do
description: "desc3", description: "desc3",
# Only focusing on these because these are passed to functions that # Only focusing on these because these are passed to functions that
# could fail if they're not present # could fail if they're not present
webpage_url: nil, original_url: nil,
aspect_ratio: nil, aspect_ratio: nil,
duration: nil, duration: nil,
upload_date: nil upload_date: nil
@@ -202,6 +282,16 @@ defmodule Pinchflat.SlowIndexing.SlowIndexingHelpersTest do
assert %Ecto.Changeset{} = changeset assert %Ecto.Changeset{} = changeset
end end
test "passes the source's download options to the yt-dlp runner", %{source: source} do
expect(YtDlpRunnerMock, :run, fn _url, opts, _ot, _addl_opts ->
assert {:output, "/tmp/test/media/%(title)S.%(ext)S"} in opts
assert {:remux_video, "mp4"} in opts
{:ok, source_attributes_return_fixture()}
end)
SlowIndexingHelpers.index_and_enqueue_download_for_media_items(source)
end
test "sets use_cookies if the source uses cookies" do test "sets use_cookies if the source uses cookies" do
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot, addl_opts -> expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot, addl_opts ->
assert {:use_cookies, true} in addl_opts assert {:use_cookies, true} in addl_opts
@@ -299,7 +389,7 @@ defmodule Pinchflat.SlowIndexing.SlowIndexingHelpersTest do
Phoenix.json_library().encode!(%{ Phoenix.json_library().encode!(%{
id: "video2", id: "video2",
title: "Video 2", title: "Video 2",
webpage_url: "https://example.com/shorts/video2", original_url: "https://example.com/shorts/video2",
live_status: "is_live", live_status: "is_live",
description: "desc2", description: "desc2",
aspect_ratio: 1.67, aspect_ratio: 1.67,
+171 -34
View File
@@ -147,6 +147,18 @@ defmodule Pinchflat.SourcesTest do
assert "could not fetch source details from URL" in errors_on(changeset).original_url assert "could not fetch source details from URL" in errors_on(changeset).original_url
end end
test "adds an error if the runner succeeds but the result was invalid JSON" do
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot, _addl -> {:ok, "Not JSON"} end)
valid_attrs = %{
media_profile_id: media_profile_fixture().id,
original_url: "https://www.youtube.com/channel/abc123"
}
assert {:error, %Ecto.Changeset{} = changeset} = Sources.create_source(valid_attrs)
assert "could not fetch source details from URL" in errors_on(changeset).original_url
end
test "you can specify a custom custom_name" do test "you can specify a custom custom_name" do
expect(YtDlpRunnerMock, :run, &channel_mock/4) expect(YtDlpRunnerMock, :run, &channel_mock/4)
@@ -406,6 +418,100 @@ defmodule Pinchflat.SourcesTest do
assert {:ok, %Source{}} = Sources.update_source(source, update_attrs) assert {:ok, %Source{}} = Sources.update_source(source, update_attrs)
end end
test "updates with invalid data returns error changeset" do
source = source_fixture()
assert {:error, %Ecto.Changeset{}} =
Sources.update_source(source, @invalid_source_attrs)
assert source == Sources.get_source!(source.id)
end
test "updating will kickoff a metadata storage worker if the original_url changes" do
expect(YtDlpRunnerMock, :run, &playlist_mock/4)
source = source_fixture()
update_attrs = %{original_url: "https://www.youtube.com/channel/cba321"}
assert {:ok, %Source{} = source} = Sources.update_source(source, update_attrs)
assert_enqueued(worker: SourceMetadataStorageWorker, args: %{"id" => source.id})
end
test "updating will not kickoff a metadata storage worker other attrs change" do
source = source_fixture()
update_attrs = %{name: "some new name"}
assert {:ok, %Source{}} = Sources.update_source(source, update_attrs)
refute_enqueued(worker: SourceMetadataStorageWorker)
end
end
describe "update_source/3 when testing media download tasks" do
test "enabling the download_media attribute will schedule a download task" do
source = source_fixture(download_media: false)
media_item = media_item_fixture(source_id: source.id, media_filepath: nil)
update_attrs = %{download_media: true}
refute_enqueued(worker: MediaDownloadWorker)
assert {:ok, %Source{}} = Sources.update_source(source, update_attrs)
assert_enqueued(worker: MediaDownloadWorker, args: %{"id" => media_item.id})
end
test "disabling the download_media attribute will cancel the download task" do
source = source_fixture(download_media: true, enabled: true)
media_item = media_item_fixture(source_id: source.id, media_filepath: nil)
update_attrs = %{download_media: false}
DownloadingHelpers.enqueue_pending_download_tasks(source)
assert_enqueued(worker: MediaDownloadWorker, args: %{"id" => media_item.id})
assert {:ok, %Source{}} = Sources.update_source(source, update_attrs)
refute_enqueued(worker: MediaDownloadWorker)
end
test "enabling download_media will not schedule a task if the source is disabled" do
source = source_fixture(download_media: false, enabled: false)
_media_item = media_item_fixture(source_id: source.id, media_filepath: nil)
update_attrs = %{download_media: true}
refute_enqueued(worker: MediaDownloadWorker)
assert {:ok, %Source{}} = Sources.update_source(source, update_attrs)
refute_enqueued(worker: MediaDownloadWorker)
end
test "disabling a source will cancel any pending download tasks" do
source = source_fixture(download_media: true, enabled: true)
media_item = media_item_fixture(source_id: source.id, media_filepath: nil)
update_attrs = %{enabled: false}
DownloadingHelpers.enqueue_pending_download_tasks(source)
assert_enqueued(worker: MediaDownloadWorker, args: %{"id" => media_item.id})
assert {:ok, %Source{}} = Sources.update_source(source, update_attrs)
refute_enqueued(worker: MediaDownloadWorker)
end
test "enabling a source will schedule a download task if download_media is true" do
source = source_fixture(download_media: true, enabled: false)
media_item = media_item_fixture(source_id: source.id, media_filepath: nil)
update_attrs = %{enabled: true}
refute_enqueued(worker: MediaDownloadWorker)
assert {:ok, %Source{}} = Sources.update_source(source, update_attrs)
assert_enqueued(worker: MediaDownloadWorker, args: %{"id" => media_item.id})
end
test "enabling a source will not schedule a download task if download_media is false" do
source = source_fixture(download_media: false, enabled: false)
_media_item = media_item_fixture(source_id: source.id, media_filepath: nil)
update_attrs = %{enabled: true}
refute_enqueued(worker: MediaDownloadWorker)
assert {:ok, %Source{}} = Sources.update_source(source, update_attrs)
refute_enqueued(worker: MediaDownloadWorker)
end
end
describe "update_source/3 when testing slow indexing" do
test "updating the index frequency to >0 will re-schedule the indexing task" do test "updating the index frequency to >0 will re-schedule the indexing task" do
source = source_fixture() source = source_fixture()
update_attrs = %{index_frequency_minutes: 123} update_attrs = %{index_frequency_minutes: 123}
@@ -450,27 +556,47 @@ defmodule Pinchflat.SourcesTest do
refute_enqueued(worker: MediaCollectionIndexingWorker, args: %{"id" => source.id}) refute_enqueued(worker: MediaCollectionIndexingWorker, args: %{"id" => source.id})
end end
test "enabling the download_media attribute will schedule a download task" do test "disabling a source will delete any pending tasks" do
source = source_fixture(download_media: false) source = source_fixture()
media_item = media_item_fixture(source_id: source.id, media_filepath: nil) update_attrs = %{enabled: false}
update_attrs = %{download_media: true}
{:ok, job} = Oban.insert(MediaCollectionIndexingWorker.new(%{"id" => source.id}))
task = task_fixture(source_id: source.id, job_id: job.id)
refute_enqueued(worker: MediaDownloadWorker)
assert {:ok, %Source{}} = Sources.update_source(source, update_attrs) assert {:ok, %Source{}} = Sources.update_source(source, update_attrs)
assert_enqueued(worker: MediaDownloadWorker, args: %{"id" => media_item.id})
assert_raise Ecto.NoResultsError, fn -> Repo.reload!(task) end
end end
test "disabling the download_media attribute will cancel the download task" do test "updating the index frequency will not create a task if the source is disabled" do
source = source_fixture(download_media: true) source = source_fixture(enabled: false)
media_item = media_item_fixture(source_id: source.id, media_filepath: nil) update_attrs = %{index_frequency_minutes: 123}
update_attrs = %{download_media: false}
DownloadingHelpers.enqueue_pending_download_tasks(source)
assert_enqueued(worker: MediaDownloadWorker, args: %{"id" => media_item.id}) refute_enqueued(worker: MediaCollectionIndexingWorker)
assert {:ok, %Source{}} = Sources.update_source(source, update_attrs) assert {:ok, %Source{}} = Sources.update_source(source, update_attrs)
refute_enqueued(worker: MediaDownloadWorker) refute_enqueued(worker: MediaCollectionIndexingWorker)
end end
test "enabling a source will create a task if the index frequency is >0" do
source = source_fixture(enabled: false, index_frequency_minutes: 123)
update_attrs = %{enabled: true}
refute_enqueued(worker: MediaCollectionIndexingWorker)
assert {:ok, %Source{}} = Sources.update_source(source, update_attrs)
assert_enqueued(worker: MediaCollectionIndexingWorker, args: %{"id" => source.id})
end
test "enabling a source will not create a task if the index frequency is 0" do
source = source_fixture(enabled: false, index_frequency_minutes: 0)
update_attrs = %{enabled: true}
refute_enqueued(worker: MediaCollectionIndexingWorker)
assert {:ok, %Source{}} = Sources.update_source(source, update_attrs)
refute_enqueued(worker: MediaCollectionIndexingWorker)
end
end
describe "update_source/3 when testing fast indexing" do
test "enabling fast_index will schedule a fast indexing task" do test "enabling fast_index will schedule a fast indexing task" do
source = source_fixture(fast_index: false) source = source_fixture(fast_index: false)
update_attrs = %{fast_index: true} update_attrs = %{fast_index: true}
@@ -491,15 +617,6 @@ defmodule Pinchflat.SourcesTest do
refute_enqueued(worker: FastIndexingWorker) refute_enqueued(worker: FastIndexingWorker)
end end
test "updates with invalid data returns error changeset" do
source = source_fixture()
assert {:error, %Ecto.Changeset{}} =
Sources.update_source(source, @invalid_source_attrs)
assert source == Sources.get_source!(source.id)
end
test "fast_index forces the index frequency to be a default value" do test "fast_index forces the index frequency to be a default value" do
source = source_fixture(%{fast_index: true}) source = source_fixture(%{fast_index: true})
update_attrs = %{index_frequency_minutes: 0} update_attrs = %{index_frequency_minutes: 0}
@@ -518,23 +635,43 @@ defmodule Pinchflat.SourcesTest do
assert source.index_frequency_minutes == 0 assert source.index_frequency_minutes == 0
end end
test "updating will kickoff a metadata storage worker if the original_url changes" do test "disabling a source will delete any pending tasks" do
expect(YtDlpRunnerMock, :run, &playlist_mock/4)
source = source_fixture() source = source_fixture()
update_attrs = %{original_url: "https://www.youtube.com/channel/cba321"} update_attrs = %{enabled: false}
assert {:ok, %Source{} = source} = Sources.update_source(source, update_attrs) {:ok, job} = Oban.insert(FastIndexingWorker.new(%{"id" => source.id}))
task = task_fixture(source_id: source.id, job_id: job.id)
assert_enqueued(worker: SourceMetadataStorageWorker, args: %{"id" => source.id})
end
test "updating will not kickoff a metadata storage worker other attrs change" do
source = source_fixture()
update_attrs = %{name: "some new name"}
assert {:ok, %Source{}} = Sources.update_source(source, update_attrs) assert {:ok, %Source{}} = Sources.update_source(source, update_attrs)
refute_enqueued(worker: SourceMetadataStorageWorker) assert_raise Ecto.NoResultsError, fn -> Repo.reload!(task) end
end
test "updating fast indexing will not create a task if the source is disabled" do
source = source_fixture(enabled: false, fast_index: false)
update_attrs = %{fast_index: true}
refute_enqueued(worker: FastIndexingWorker)
assert {:ok, %Source{}} = Sources.update_source(source, update_attrs)
refute_enqueued(worker: FastIndexingWorker)
end
test "enabling a source will create a task if fast_index is true" do
source = source_fixture(enabled: false, fast_index: true)
update_attrs = %{enabled: true}
refute_enqueued(worker: FastIndexingWorker)
assert {:ok, %Source{}} = Sources.update_source(source, update_attrs)
assert_enqueued(worker: FastIndexingWorker, args: %{"id" => source.id})
end
test "enabling a source will not create a task if fast_index is false" do
source = source_fixture(enabled: false, fast_index: false)
update_attrs = %{enabled: true}
refute_enqueued(worker: FastIndexingWorker)
assert {:ok, %Source{}} = Sources.update_source(source, update_attrs)
refute_enqueued(worker: FastIndexingWorker)
end end
end end
+1 -1
View File
@@ -247,7 +247,7 @@ defmodule Pinchflat.TasksTest do
assert_raise Ecto.NoResultsError, fn -> Repo.reload!(task) end assert_raise Ecto.NoResultsError, fn -> Repo.reload!(task) end
end end
test "deletion can optionall include executing tasks" do test "deletion can optionally include executing tasks" do
source = source_fixture() source = source_fixture()
task = task_fixture(source_id: source.id) task = task_fixture(source_id: source.id)
@@ -35,6 +35,16 @@ defmodule Pinchflat.YtDlp.MediaCollectionTest do
assert {:error, "Big issue", 1} = MediaCollection.get_media_attributes_for_collection(@channel_url) assert {:error, "Big issue", 1} = MediaCollection.get_media_attributes_for_collection(@channel_url)
end end
test "passes long additional command options" do
expect(YtDlpRunnerMock, :run, fn _url, opts, _ot, _addl_opts ->
assert :foo in opts
{:ok, ""}
end)
assert {:ok, _} = MediaCollection.get_media_attributes_for_collection(@channel_url, [:foo])
end
test "passes additional args to runner" do test "passes additional args to runner" do
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot, addl_opts -> expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot, addl_opts ->
assert [{:output_filepath, filepath} | _] = addl_opts assert [{:output_filepath, filepath} | _] = addl_opts
@@ -56,7 +66,7 @@ defmodule Pinchflat.YtDlp.MediaCollectionTest do
end end
assert {:ok, _} = assert {:ok, _} =
MediaCollection.get_media_attributes_for_collection(@channel_url, file_listener_handler: handler) MediaCollection.get_media_attributes_for_collection(@channel_url, [], file_listener_handler: handler)
assert_receive {:handler, filename} assert_receive {:handler, filename}
assert String.ends_with?(filename, ".json") assert String.ends_with?(filename, ".json")
@@ -133,7 +143,7 @@ defmodule Pinchflat.YtDlp.MediaCollectionTest do
test "returns an error if the output is not JSON" do test "returns an error if the output is not JSON" do
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot, _addl_opts -> {:ok, "Not JSON"} end) expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot, _addl_opts -> {:ok, "Not JSON"} end)
assert {:error, %Jason.DecodeError{}} = MediaCollection.get_source_details(@channel_url) assert {:error, "Error decoding JSON response"} = MediaCollection.get_source_details(@channel_url)
end end
end end
+86 -17
View File
@@ -58,6 +58,64 @@ defmodule Pinchflat.YtDlp.MediaTest do
end end
end end
describe "get_downloadable_status/1" do
test "returns :downloadable if the media was never live" do
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot ->
{:ok, Phoenix.json_library().encode!(%{"live_status" => "not_live"})}
end)
assert {:ok, :downloadable} = Media.get_downloadable_status(@media_url)
end
test "returns :downloadable if the media was live and has been processed" do
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot ->
{:ok, Phoenix.json_library().encode!(%{"live_status" => "was_live"})}
end)
assert {:ok, :downloadable} = Media.get_downloadable_status(@media_url)
end
test "returns :downloadable if the media's live_status is nil" do
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot ->
{:ok, Phoenix.json_library().encode!(%{"live_status" => nil})}
end)
assert {:ok, :downloadable} = Media.get_downloadable_status(@media_url)
end
test "returns :ignorable if the media is currently live" do
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot ->
{:ok, Phoenix.json_library().encode!(%{"live_status" => "is_live"})}
end)
assert {:ok, :ignorable} = Media.get_downloadable_status(@media_url)
end
test "returns :ignorable if the media is scheduled to be live" do
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot ->
{:ok, Phoenix.json_library().encode!(%{"live_status" => "is_upcoming"})}
end)
assert {:ok, :ignorable} = Media.get_downloadable_status(@media_url)
end
test "returns :ignorable if the media was live but hasn't been processed" do
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot ->
{:ok, Phoenix.json_library().encode!(%{"live_status" => "post_live"})}
end)
assert {:ok, :ignorable} = Media.get_downloadable_status(@media_url)
end
test "returns an error if the downloadable status can't be determined" do
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot ->
{:ok, Phoenix.json_library().encode!(%{"live_status" => "what_tha"})}
end)
assert {:error, "Unknown live status: what_tha"} = Media.get_downloadable_status(@media_url)
end
end
describe "download_thumbnail/2" do describe "download_thumbnail/2" do
test "calls the backend runner with the expected arguments" do test "calls the backend runner with the expected arguments" do
expect(YtDlpRunnerMock, :run, fn @media_url, opts, ot, _addl -> expect(YtDlpRunnerMock, :run, fn @media_url, opts, ot, _addl ->
@@ -120,13 +178,22 @@ defmodule Pinchflat.YtDlp.MediaTest do
assert {:ok, _} = Media.get_media_attributes(@media_url) assert {:ok, _} = Media.get_media_attributes(@media_url)
end end
test "passes along additional command options" do
expect(YtDlpRunnerMock, :run, fn _url, opts, _ot, _addl ->
assert [:simulate, :skip_download, :custom_arg] = opts
{:ok, media_attributes_return_fixture()}
end)
assert {:ok, _} = Media.get_media_attributes(@media_url, [:custom_arg])
end
test "passes along additional options" do test "passes along additional options" do
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot, addl -> expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot, addl ->
assert [addl_arg: true] = addl assert [addl_arg: true] = addl
{:ok, media_attributes_return_fixture()} {:ok, media_attributes_return_fixture()}
end) end)
assert {:ok, _} = Media.get_media_attributes(@media_url, addl_arg: true) assert {:ok, _} = Media.get_media_attributes(@media_url, [], addl_arg: true)
end end
test "returns the error straight through when the command fails" do test "returns the error straight through when the command fails" do
@@ -139,7 +206,7 @@ defmodule Pinchflat.YtDlp.MediaTest do
describe "indexing_output_template/0" do describe "indexing_output_template/0" do
test "contains all the greatest hits" do test "contains all the greatest hits" do
attrs = attrs =
~w(id title live_status webpage_url description aspect_ratio duration upload_date timestamp playlist_index)a ~w(id title live_status original_url description aspect_ratio duration upload_date timestamp playlist_index filename)a
formatted_attrs = "%(.{#{Enum.join(attrs, ",")}})j" formatted_attrs = "%(.{#{Enum.join(attrs, ",")}})j"
@@ -153,13 +220,14 @@ defmodule Pinchflat.YtDlp.MediaTest do
"id" => "TiZPUDkDYbk", "id" => "TiZPUDkDYbk",
"title" => "Trying to Wheelie Without the Rear Brake", "title" => "Trying to Wheelie Without the Rear Brake",
"description" => "I'm not sure what I expected.", "description" => "I'm not sure what I expected.",
"webpage_url" => "https://www.youtube.com/watch?v=TiZPUDkDYbk", "original_url" => "https://www.youtube.com/watch?v=TiZPUDkDYbk",
"live_status" => "not_live", "live_status" => "not_live",
"aspect_ratio" => 1.0, "aspect_ratio" => 1.0,
"duration" => 60, "duration" => 60,
"upload_date" => "20210101", "upload_date" => "20210101",
"timestamp" => 1_600_000_000, "timestamp" => 1_600_000_000,
"playlist_index" => 1 "playlist_index" => 1,
"filename" => "TiZPUDkDYbk.mp4"
} }
assert %Media{ assert %Media{
@@ -171,13 +239,14 @@ defmodule Pinchflat.YtDlp.MediaTest do
short_form_content: false, short_form_content: false,
uploaded_at: ~U[2020-09-13 12:26:40Z], uploaded_at: ~U[2020-09-13 12:26:40Z],
duration_seconds: 60, duration_seconds: 60,
playlist_index: 1 playlist_index: 1,
predicted_media_filepath: "TiZPUDkDYbk.mp4"
} == Media.response_to_struct(response) } == Media.response_to_struct(response)
end end
test "sets short_form_content to true if the URL contains /shorts/" do test "sets short_form_content to true if the URL contains /shorts/" do
response = %{ response = %{
"webpage_url" => "https://www.youtube.com/shorts/TiZPUDkDYbk", "original_url" => "https://www.youtube.com/shorts/TiZPUDkDYbk",
"aspect_ratio" => 1.0, "aspect_ratio" => 1.0,
"duration" => 61, "duration" => 61,
"upload_date" => "20210101" "upload_date" => "20210101"
@@ -188,7 +257,7 @@ defmodule Pinchflat.YtDlp.MediaTest do
test "sets short_form_content to true if the aspect ratio are duration are right" do test "sets short_form_content to true if the aspect ratio are duration are right" do
response = %{ response = %{
"webpage_url" => "https://www.youtube.com/watch?v=TiZPUDkDYbk", "original_url" => "https://www.youtube.com/watch?v=TiZPUDkDYbk",
"aspect_ratio" => 0.5, "aspect_ratio" => 0.5,
"duration" => 59, "duration" => 59,
"upload_date" => "20210101" "upload_date" => "20210101"
@@ -199,7 +268,7 @@ defmodule Pinchflat.YtDlp.MediaTest do
test "sets short_form_content to false otherwise" do test "sets short_form_content to false otherwise" do
response = %{ response = %{
"webpage_url" => "https://www.youtube.com/watch?v=TiZPUDkDYbk", "original_url" => "https://www.youtube.com/watch?v=TiZPUDkDYbk",
"aspect_ratio" => 1.0, "aspect_ratio" => 1.0,
"duration" => 61, "duration" => 61,
"upload_date" => "20210101" "upload_date" => "20210101"
@@ -210,7 +279,7 @@ defmodule Pinchflat.YtDlp.MediaTest do
test "doesn't blow up if short form content-related fields are missing" do test "doesn't blow up if short form content-related fields are missing" do
response = %{ response = %{
"webpage_url" => nil, "original_url" => nil,
"aspect_ratio" => nil, "aspect_ratio" => nil,
"duration" => nil, "duration" => nil,
"upload_date" => "20210101" "upload_date" => "20210101"
@@ -221,7 +290,7 @@ defmodule Pinchflat.YtDlp.MediaTest do
test "parses the duration" do test "parses the duration" do
response = %{ response = %{
"webpage_url" => "https://www.youtube.com/watch?v=TiZPUDkDYbk", "original_url" => "https://www.youtube.com/watch?v=TiZPUDkDYbk",
"aspect_ratio" => 1.0, "aspect_ratio" => 1.0,
"duration" => 60.4, "duration" => 60.4,
"upload_date" => "20210101" "upload_date" => "20210101"
@@ -232,7 +301,7 @@ defmodule Pinchflat.YtDlp.MediaTest do
test "doesn't blow up if duration is missing" do test "doesn't blow up if duration is missing" do
response = %{ response = %{
"webpage_url" => "https://www.youtube.com/watch?v=TiZPUDkDYbk", "original_url" => "https://www.youtube.com/watch?v=TiZPUDkDYbk",
"aspect_ratio" => 1.0, "aspect_ratio" => 1.0,
"duration" => nil, "duration" => nil,
"upload_date" => "20210101" "upload_date" => "20210101"
@@ -243,7 +312,7 @@ defmodule Pinchflat.YtDlp.MediaTest do
test "sets livestream to false if the live_status field isn't present" do test "sets livestream to false if the live_status field isn't present" do
response = %{ response = %{
"webpage_url" => "https://www.youtube.com/watch?v=TiZPUDkDYbk", "original_url" => "https://www.youtube.com/watch?v=TiZPUDkDYbk",
"aspect_ratio" => 1.0, "aspect_ratio" => 1.0,
"duration" => 60, "duration" => 60,
"upload_date" => "20210101" "upload_date" => "20210101"
@@ -254,7 +323,7 @@ defmodule Pinchflat.YtDlp.MediaTest do
test "doesn't blow up if playlist_index is missing" do test "doesn't blow up if playlist_index is missing" do
response = %{ response = %{
"webpage_url" => "https://www.youtube.com/watch?v=TiZPUDkDYbk", "original_url" => "https://www.youtube.com/watch?v=TiZPUDkDYbk",
"aspect_ratio" => 1.0, "aspect_ratio" => 1.0,
"duration" => nil, "duration" => nil,
"upload_date" => "20210101" "upload_date" => "20210101"
@@ -267,7 +336,7 @@ defmodule Pinchflat.YtDlp.MediaTest do
describe "response_to_struct/1 when testing uploaded_at" do describe "response_to_struct/1 when testing uploaded_at" do
test "parses the upload date from the timestamp if present" do test "parses the upload date from the timestamp if present" do
response = %{ response = %{
"webpage_url" => "https://www.youtube.com/watch?v=TiZPUDkDYbk", "original_url" => "https://www.youtube.com/watch?v=TiZPUDkDYbk",
"aspect_ratio" => 1.0, "aspect_ratio" => 1.0,
"duration" => 61, "duration" => 61,
"upload_date" => "20210101", "upload_date" => "20210101",
@@ -281,7 +350,7 @@ defmodule Pinchflat.YtDlp.MediaTest do
test "parses the upload date from the uploaded_at if timestamp is present but nil" do test "parses the upload date from the uploaded_at if timestamp is present but nil" do
response = %{ response = %{
"webpage_url" => "https://www.youtube.com/watch?v=TiZPUDkDYbk", "original_url" => "https://www.youtube.com/watch?v=TiZPUDkDYbk",
"aspect_ratio" => 1.0, "aspect_ratio" => 1.0,
"duration" => 61, "duration" => 61,
"upload_date" => "20210101", "upload_date" => "20210101",
@@ -295,7 +364,7 @@ defmodule Pinchflat.YtDlp.MediaTest do
test "parses the upload date from the uploaded_at if timestamp absent" do test "parses the upload date from the uploaded_at if timestamp absent" do
response = %{ response = %{
"webpage_url" => "https://www.youtube.com/watch?v=TiZPUDkDYbk", "original_url" => "https://www.youtube.com/watch?v=TiZPUDkDYbk",
"aspect_ratio" => 1.0, "aspect_ratio" => 1.0,
"duration" => 61, "duration" => 61,
"upload_date" => "20210101" "upload_date" => "20210101"
@@ -308,7 +377,7 @@ defmodule Pinchflat.YtDlp.MediaTest do
test "doesn't blow up if upload date is missing" do test "doesn't blow up if upload date is missing" do
response = %{ response = %{
"webpage_url" => "https://www.youtube.com/watch?v=TiZPUDkDYbk", "original_url" => "https://www.youtube.com/watch?v=TiZPUDkDYbk",
"aspect_ratio" => 1.0, "aspect_ratio" => 1.0,
"duration" => 61, "duration" => 61,
"upload_date" => nil "upload_date" => nil
@@ -79,6 +79,15 @@ defmodule PinchflatWeb.MediaProfileControllerTest do
refute html_response(conn, 200) =~ "MENU" refute html_response(conn, 200) =~ "MENU"
end end
test "preloads some attributes when using a template", %{conn: conn} do
profile = media_profile_fixture(name: "My first profile", download_subs: true, sub_langs: "de")
conn = get(conn, ~p"/media_profiles/new", %{"template_id" => profile.id})
assert html_response(conn, 200) =~ "New Media Profile"
assert html_response(conn, 200) =~ profile.sub_langs
refute html_response(conn, 200) =~ profile.name
end
end end
describe "edit media_profile" do describe "edit media_profile" do
@@ -34,27 +34,10 @@ defmodule PinchflatWeb.SourceControllerTest do
end end
describe "index" do describe "index" do
test "lists all sources", %{conn: conn} do # Most of the tests are in `index_table_list_test.exs`
source = source_fixture() test "returns 200", %{conn: conn} do
conn = get(conn, ~p"/sources") conn = get(conn, ~p"/sources")
assert html_response(conn, 200) =~ "Sources" assert html_response(conn, 200) =~ "Sources"
assert html_response(conn, 200) =~ source.custom_name
end
test "omits sources that have marked_for_deletion_at set", %{conn: conn} do
source = source_fixture(marked_for_deletion_at: DateTime.utc_now())
conn = get(conn, ~p"/sources")
refute html_response(conn, 200) =~ source.custom_name
end
test "omits sources who's media profile has marked_for_deletion_at set", %{conn: conn} do
media_profile = media_profile_fixture(marked_for_deletion_at: DateTime.utc_now())
source = source_fixture(media_profile_id: media_profile.id)
conn = get(conn, ~p"/sources")
refute html_response(conn, 200) =~ source.custom_name
end end
end end
@@ -0,0 +1,55 @@
defmodule PinchflatWeb.Sources.IndexTableLiveTest do
use PinchflatWeb.ConnCase
import Phoenix.LiveViewTest
import Pinchflat.SourcesFixtures
import Pinchflat.ProfilesFixtures
alias Pinchflat.Sources.Source
alias PinchflatWeb.Sources.IndexTableLive
describe "initial rendering" do
test "lists all sources", %{conn: conn} do
source = source_fixture()
{:ok, _view, html} = live_isolated(conn, IndexTableLive)
assert html =~ source.custom_name
end
test "omits sources that have marked_for_deletion_at set", %{conn: conn} do
source = source_fixture(marked_for_deletion_at: DateTime.utc_now())
{:ok, _view, html} = live_isolated(conn, IndexTableLive)
refute html =~ source.custom_name
end
test "omits sources who's media profile has marked_for_deletion_at set", %{conn: conn} do
media_profile = media_profile_fixture(marked_for_deletion_at: DateTime.utc_now())
source = source_fixture(media_profile_id: media_profile.id)
{:ok, _view, html} = live_isolated(conn, IndexTableLive)
refute html =~ source.custom_name
end
end
describe "when a source is enabled or disabled" do
test "updates the source's enabled status", %{conn: conn} do
source = source_fixture(enabled: true)
{:ok, view, _html} = live_isolated(conn, IndexTableLive)
params = %{
"event" => "toggle_enabled",
"id" => source.id,
"value" => "false"
}
# Send an event to the server directly
render_change(view, "formless-input", params)
assert %{enabled: false} = Repo.get!(Source, source.id)
end
end
end
@@ -6,7 +6,7 @@ defmodule PinchflatWeb.Sources.MediaItemTableLiveTest do
import Pinchflat.SourcesFixtures import Pinchflat.SourcesFixtures
import Pinchflat.ProfilesFixtures import Pinchflat.ProfilesFixtures
alias Pinchflat.Sources.MediaItemTableLive alias PinchflatWeb.Sources.MediaItemTableLive
setup do setup do
source = source_fixture() source = source_fixture()
+1 -1
View File
@@ -95,7 +95,7 @@ defmodule Pinchflat.MediaFixtures do
media_attributes = %{ media_attributes = %{
id: "video1", id: "video1",
title: "Video 1", title: "Video 1",
webpage_url: "https://example.com/video1", original_url: "https://example.com/video1",
live_status: "not_live", live_status: "not_live",
description: "desc1", description: "desc1",
aspect_ratio: 1.67, aspect_ratio: 1.67,
+4 -3
View File
@@ -20,6 +20,7 @@ defmodule Pinchflat.SourcesFixtures do
Enum.into( Enum.into(
attrs, attrs,
%{ %{
enabled: true,
collection_name: "Source ##{:rand.uniform(1_000_000)}", collection_name: "Source ##{:rand.uniform(1_000_000)}",
collection_id: Base.encode16(:crypto.hash(:md5, "#{:rand.uniform(1_000_000)}")), collection_id: Base.encode16(:crypto.hash(:md5, "#{:rand.uniform(1_000_000)}")),
collection_type: "channel", collection_type: "channel",
@@ -80,7 +81,7 @@ defmodule Pinchflat.SourcesFixtures do
%{ %{
id: "video1", id: "video1",
title: "Video 1", title: "Video 1",
webpage_url: "https://example.com/video1", original_url: "https://example.com/video1",
live_status: "not_live", live_status: "not_live",
description: "desc1", description: "desc1",
aspect_ratio: 1.67, aspect_ratio: 1.67,
@@ -90,7 +91,7 @@ defmodule Pinchflat.SourcesFixtures do
%{ %{
id: "video2", id: "video2",
title: "Video 2", title: "Video 2",
webpage_url: "https://example.com/video2", original_url: "https://example.com/video2",
live_status: "is_live", live_status: "is_live",
description: "desc2", description: "desc2",
aspect_ratio: 1.67, aspect_ratio: 1.67,
@@ -100,7 +101,7 @@ defmodule Pinchflat.SourcesFixtures do
%{ %{
id: "video3", id: "video3",
title: "Video 3", title: "Video 3",
webpage_url: "https://example.com/video3", original_url: "https://example.com/video3",
live_status: "not_live", live_status: "not_live",
description: "desc3", description: "desc3",
aspect_ratio: 1.0, aspect_ratio: 1.0,