Compare commits

..

4 Commits

Author SHA1 Message Date
Kieran Eglin a9f40ed843 Bumped version 2024-04-06 13:28:06 -07:00
Kieran f27323ffa3 [Ehnacement] More gracefully handle Sponsorblock failures (#169)
* Updated downloader and runner to handle sponsorblock failures more gracefully

* stopped download worker from running if a media item is preventing download
2024-04-06 13:23:36 -07:00
Kieran 81b49f55bf [Bugfix] Properly escape NFO files (#168)
* Properly escaped NFO file contents

* Added an NFO backfill worker

* Added a try-catch to the backfill since I _really_ don't want failures to halt app boot
2024-04-06 11:48:28 -07:00
Kieran 24875eaeac [Housekeeping] Refactor settings model (#165)
* [WIP] renamed current settings module and tables to have backup suffix

* Created new settings table, schema, and context

* Migrated from old settings module to new one

* Removed settings backup modules

* Added some tests and docs
2024-04-04 12:43:17 -07:00
27 changed files with 487 additions and 251 deletions
+70
View File
@@ -0,0 +1,70 @@
defmodule Pinchflat.Boot.NfoBackfillWorker do
@moduledoc false
use Oban.Worker,
queue: :local_metadata,
# This should have it running once _ever_ (until the job is pruned, anyway)
# NOTE: remove within the next month
unique: [period: :infinity, states: Oban.Job.states()],
tags: ["media_item", "media_metadata", "local_metadata", "data_backfill"]
import Ecto.Query, warn: false
require Logger
alias Pinchflat.Repo
alias Pinchflat.Media
alias Pinchflat.Media.MediaItem
alias Pinchflat.Metadata.NfoBuilder
alias Pinchflat.Metadata.MetadataFileHelpers
@doc """
Runs a one-off backfill job to regenerate NFO files for media items that have
both an NFO file and a metadata file. This is needed because NFO files weren't
escaping characters properly so we need to regenerate them.
This job will only run once as long as I remove it before the jobs are pruned in a month.
Returns :ok
"""
@impl Oban.Worker
def perform(%Oban.Job{}) do
Logger.info("Running NFO backfill worker")
media_items = get_media_items_to_backfill()
Enum.each(media_items, fn media_item ->
nfo_exists = File.exists?(media_item.nfo_filepath)
metadata_exists = File.exists?(media_item.metadata.metadata_filepath)
if nfo_exists && metadata_exists do
Logger.info("NFO and metadata exist for media item #{media_item.id} - proceeding")
regenerate_nfo_for_media_item(media_item)
end
end)
:ok
end
defp get_media_items_to_backfill do
from(m in MediaItem, where: not is_nil(m.nfo_filepath))
|> Repo.all()
|> Repo.preload([:metadata, source: :media_profile])
end
defp regenerate_nfo_for_media_item(media_item) do
try do
case MetadataFileHelpers.read_compressed_metadata(media_item.metadata.metadata_filepath) do
{:ok, metadata} ->
Media.update_media_item(media_item, %{
nfo_filepath: NfoBuilder.build_and_store_for_media_item(media_item.nfo_filepath, metadata)
})
_err ->
Logger.error("Failed to read metadata for media item #{media_item.id}")
end
rescue
e -> Logger.error("Unknown error regenerating NFO file for MI ##{media_item.id}: #{inspect(e)}")
end
end
end
+5 -1
View File
@@ -7,6 +7,9 @@ defmodule Pinchflat.Boot.PostJobStartupTasks do
Phoenix supervision tree. Phoenix supervision tree.
""" """
alias Pinchflat.Repo
alias Pinchflat.Boot.NfoBackfillWorker
# restart: :temporary means that this process will never be restarted (ie: will run once and then die) # restart: :temporary means that this process will never be restarted (ie: will run once and then die)
use GenServer, restart: :temporary use GenServer, restart: :temporary
import Ecto.Query, warn: false import Ecto.Query, warn: false
@@ -26,7 +29,8 @@ defmodule Pinchflat.Boot.PostJobStartupTasks do
""" """
@impl true @impl true
def init(state) do def init(state) do
# Empty for now, keeping because tasks _will_ be added in future Repo.insert_unique_job(NfoBackfillWorker.new(%{}))
{:ok, state} {:ok, state}
end end
end end
+1 -3
View File
@@ -65,8 +65,6 @@ defmodule Pinchflat.Boot.PreJobStartupTasks do
defp apply_default_settings do defp apply_default_settings do
{:ok, yt_dlp_version} = CommandRunner.version() {:ok, yt_dlp_version} = CommandRunner.version()
Settings.fetch!(:onboarding, true) Settings.set(yt_dlp_version: yt_dlp_version)
Settings.fetch!(:pro_enabled, false)
Settings.set!(:yt_dlp_version, yt_dlp_version)
end end
end end
@@ -40,8 +40,8 @@ defmodule Pinchflat.Downloading.MediaDownloadWorker do
|> Media.get_media_item!() |> Media.get_media_item!()
|> Repo.preload(:source) |> Repo.preload(:source)
# If the source is set to not download media, perform a no-op # If the source or media item is set to not download media, perform a no-op unless forced
if media_item.source.download_media || args["force"] do if (media_item.source.download_media && !media_item.prevent_download) || args["force"] do
download_media_and_schedule_jobs(media_item) download_media_and_schedule_jobs(media_item)
else else
:ok :ok
@@ -58,9 +58,10 @@ defmodule Pinchflat.Downloading.MediaDownloadWorker do
{:ok, updated_media_item} {:ok, updated_media_item}
err -> {:recovered, _} ->
Logger.error("Failed to download media for media item #{media_item.id}: #{inspect(err)}") {:error, :retry}
{:error, _message} ->
{:error, :download_failed} {:error, :download_failed}
end end
end end
+57 -12
View File
@@ -5,12 +5,15 @@ defmodule Pinchflat.Downloading.MediaDownloader do
to download the media with the desired options. to download the media with the desired options.
""" """
require Logger
alias Pinchflat.Repo alias Pinchflat.Repo
alias Pinchflat.Media alias Pinchflat.Media
alias Pinchflat.Media.MediaItem alias Pinchflat.Media.MediaItem
alias Pinchflat.Metadata.NfoBuilder alias Pinchflat.Metadata.NfoBuilder
alias Pinchflat.Metadata.MetadataParser alias Pinchflat.Metadata.MetadataParser
alias Pinchflat.Metadata.MetadataFileHelpers alias Pinchflat.Metadata.MetadataFileHelpers
alias Pinchflat.Filesystem.FilesystemHelpers
alias Pinchflat.Downloading.DownloadOptionBuilder alias Pinchflat.Downloading.DownloadOptionBuilder
alias Pinchflat.YtDlp.Media, as: YtDlpMedia alias Pinchflat.YtDlp.Media, as: YtDlpMedia
@@ -27,31 +30,67 @@ defmodule Pinchflat.Downloading.MediaDownloader do
Returns {:ok, %MediaItem{}} | {:error, any, ...any} Returns {:ok, %MediaItem{}} | {:error, any, ...any}
""" """
def download_for_media_item(%MediaItem{} = media_item) do def download_for_media_item(%MediaItem{} = media_item) do
item_with_preloads = Repo.preload(media_item, [:metadata, source: :media_profile]) output_filepath = FilesystemHelpers.generate_metadata_tmpfile(:json)
media_with_preloads = Repo.preload(media_item, [:metadata, source: :media_profile])
case download_with_options(media_item.original_url, item_with_preloads) do case download_with_options(media_item.original_url, media_with_preloads, output_filepath) do
{:ok, parsed_json} -> {:ok, parsed_json} ->
update_media_item_from_parsed_json(media_with_preloads, parsed_json)
{:error, message, _exit_code} ->
Logger.error("yt-dlp download error for media item ##{media_with_preloads.id}: #{inspect(message)}")
if String.contains?(to_string(message), recoverable_errors()) do
attempt_update_media_item(media_with_preloads, output_filepath)
{:recovered, message}
else
{:error, message}
end
err ->
Logger.error("Unknown error downloading media item ##{media_with_preloads.id}: #{inspect(err)}")
{:error, "Unknown error: #{inspect(err)}"}
end
end
defp attempt_update_media_item(media_with_preloads, output_filepath) do
with {:ok, contents} <- File.read(output_filepath),
{:ok, parsed_json} <- Phoenix.json_library().decode(contents) do
Logger.info("""
Recovery from yt-dlp error seems possible. Updating media item ##{media_with_preloads.id}
with parsed JSON from partial download attempt. Full download will be re-attemted in future
anyway
""")
update_media_item_from_parsed_json(media_with_preloads, parsed_json)
else
err ->
Logger.error("Unable to recover error for media item ##{media_with_preloads.id}: #{inspect(err)}")
{:error, :retry_failed}
end
end
defp update_media_item_from_parsed_json(media_with_preloads, parsed_json) do
parsed_attrs = parsed_attrs =
parsed_json parsed_json
|> MetadataParser.parse_for_media_item() |> MetadataParser.parse_for_media_item()
|> Map.merge(%{ |> Map.merge(%{
media_downloaded_at: DateTime.utc_now(), media_downloaded_at: DateTime.utc_now(),
nfo_filepath: determine_nfo_filepath(item_with_preloads, parsed_json), nfo_filepath: determine_nfo_filepath(media_with_preloads, parsed_json),
metadata: %{ metadata: %{
# IDEA: might be worth kicking off a job for this since thumbnail fetching # IDEA: might be worth kicking off a job for this since thumbnail fetching
# could fail and I want to handle that in isolation # could fail and I want to handle that in isolation
metadata_filepath: MetadataFileHelpers.compress_and_store_metadata_for(media_item, parsed_json), metadata_filepath: MetadataFileHelpers.compress_and_store_metadata_for(media_with_preloads, parsed_json),
thumbnail_filepath: MetadataFileHelpers.download_and_store_thumbnail_for(media_item, parsed_json) thumbnail_filepath: MetadataFileHelpers.download_and_store_thumbnail_for(media_with_preloads, parsed_json)
} }
}) })
# Don't forgor to use preloaded associations or updates to # Don't forgor to use preloaded associations or updates to
# associations won't work! # associations won't work!
Media.update_media_item(item_with_preloads, parsed_attrs) Media.update_media_item(media_with_preloads, parsed_attrs)
err ->
err
end
end end
defp determine_nfo_filepath(media_item, parsed_json) do defp determine_nfo_filepath(media_item, parsed_json) do
@@ -64,9 +103,15 @@ defmodule Pinchflat.Downloading.MediaDownloader do
end end
end end
defp download_with_options(url, item_with_preloads) do defp download_with_options(url, item_with_preloads, output_filepath) do
{:ok, options} = DownloadOptionBuilder.build(item_with_preloads) {:ok, options} = DownloadOptionBuilder.build(item_with_preloads)
YtDlpMedia.download(url, options) YtDlpMedia.download(url, options, output_filepath: output_filepath)
end
defp recoverable_errors do
[
"Unable to communicate with SponsorBlock"
]
end end
end end
+11 -9
View File
@@ -4,6 +4,8 @@ defmodule Pinchflat.Metadata.NfoBuilder do
use by Kodi/Jellyfin and other media center software. use by Kodi/Jellyfin and other media center software.
""" """
import Pinchflat.Utils.XmlUtils, only: [safe: 1]
alias Pinchflat.Metadata.MetadataFileHelpers alias Pinchflat.Metadata.MetadataFileHelpers
alias Pinchflat.Filesystem.FilesystemHelpers alias Pinchflat.Filesystem.FilesystemHelpers
@@ -42,12 +44,12 @@ defmodule Pinchflat.Metadata.NfoBuilder do
""" """
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> <?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<episodedetails> <episodedetails>
<title>#{metadata["title"]}</title> <title>#{safe(metadata["title"])}</title>
<showtitle>#{metadata["uploader"]}</showtitle> <showtitle>#{safe(metadata["uploader"])}</showtitle>
<uniqueid type="youtube" default="true">#{metadata["id"]}</uniqueid> <uniqueid type="youtube" default="true">#{safe(metadata["id"])}</uniqueid>
<plot>#{metadata["description"]}</plot> <plot>#{safe(metadata["description"])}</plot>
<aired>#{upload_date}</aired> <aired>#{safe(upload_date)}</aired>
<season>#{upload_date.year}</season> <season>#{safe(upload_date.year)}</season>
<episode>#{Calendar.strftime(upload_date, "%m%d")}</episode> <episode>#{Calendar.strftime(upload_date, "%m%d")}</episode>
<genre>YouTube</genre> <genre>YouTube</genre>
</episodedetails> </episodedetails>
@@ -58,9 +60,9 @@ defmodule Pinchflat.Metadata.NfoBuilder do
""" """
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> <?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<tvshow> <tvshow>
<title>#{metadata["title"]}</title> <title>#{safe(metadata["title"])}</title>
<plot>#{metadata["description"]}</plot> <plot>#{safe(metadata["description"])}</plot>
<uniqueid type="youtube" default="true">#{metadata["id"]}</uniqueid> <uniqueid type="youtube" default="true">#{safe(metadata["id"])}</uniqueid>
<genre>YouTube</genre> <genre>YouTube</genre>
</tvshow> </tvshow>
""" """
+2 -8
View File
@@ -5,6 +5,8 @@ defmodule Pinchflat.Podcasts.RssFeedBuilder do
@datetime_format "%a, %d %b %Y %H:%M:%S %z" @datetime_format "%a, %d %b %Y %H:%M:%S %z"
import Pinchflat.Utils.XmlUtils, only: [safe: 1]
alias Pinchflat.Utils.DatetimeUtils alias Pinchflat.Utils.DatetimeUtils
alias Pinchflat.Podcasts.PodcastHelpers alias Pinchflat.Podcasts.PodcastHelpers
alias PinchflatWeb.Router.Helpers, as: Routes alias PinchflatWeb.Router.Helpers, as: Routes
@@ -94,14 +96,6 @@ defmodule Pinchflat.Podcasts.RssFeedBuilder do
""" """
end end
defp safe(nil), do: ""
defp safe(value) do
value
|> Phoenix.HTML.html_escape()
|> Phoenix.HTML.safe_to_string()
end
defp generate_self_link(url_base, source) do defp generate_self_link(url_base, source) do
Path.join(url_base, "#{podcast_route(:rss_feed, source.uuid)}.xml") Path.join(url_base, "#{podcast_route(:rss_feed, source.uuid)}.xml")
end end
+17 -9
View File
@@ -1,24 +1,32 @@
defmodule Pinchflat.Settings.Setting do defmodule Pinchflat.Settings.Setting do
@moduledoc """ @moduledoc """
A Setting is a key-value pair with a datatype used to track user-level settings. The Setting schema.
""" """
use Ecto.Schema use Ecto.Schema
import Ecto.Changeset import Ecto.Changeset
schema "settings" do @allowed_fields [
field :name, :string :onboarding,
field :value, :string :pro_enabled,
field :datatype, Ecto.Enum, values: ~w(boolean string integer float)a :yt_dlp_version
]
timestamps(type: :utc_datetime) @required_fields ~w(
onboarding
pro_enabled
)a
schema "settings" do
field :onboarding, :boolean, default: true
field :pro_enabled, :boolean, default: false
field :yt_dlp_version, :string
end end
@doc false @doc false
def changeset(setting, attrs) do def changeset(setting, attrs) do
setting setting
|> cast(attrs, [:name, :value, :datatype]) |> cast(attrs, @allowed_fields)
|> validate_required([:name, :value, :datatype]) |> validate_required(@required_fields)
|> unique_constraint([:name])
end end
end end
+38 -69
View File
@@ -2,94 +2,63 @@ defmodule Pinchflat.Settings do
@moduledoc """ @moduledoc """
The Settings context. The Settings context.
""" """
import Ecto.Query, warn: false import Ecto.Query, warn: false
alias Pinchflat.Repo
alias Pinchflat.Repo
alias Pinchflat.Settings.Setting alias Pinchflat.Settings.Setting
@doc """ @doc """
Returns the list of settings. Returns the only setting record. It _should_ be impossible
to create or delete this record, so it's assertive about
assuming it's the only one.
Returns [%Setting{}, ...] Returns %Setting{}
""" """
def list_settings do def record do
Repo.all(Setting) Setting
|> limit(1)
|> Repo.one()
end end
@doc """ @doc """
Creates or updates a setting, returning the parsed value. Updates a setting, returning the new value.
Raises if an unsupported datatype is used. Optionally allows Is setup to take a keyword list argument so you
specifying the datatype. can call it like `Settings.set(onboarding: true)`
Returns value in type of `Ecto.Enum.mappings(Setting, :datatype)` Returns {:ok, value} | {:error, :invalid_key} | {:error, %Ecto.Changeset{}}
""" """
def set!(name, value) do def set([{attr, value}]) do
set!(name, value, infer_datatype(value)) record()
end |> Setting.changeset(%{attr => value})
|> Repo.update()
def set!(name, value, datatype) do |> case do
# Only create if doesn't exist {:ok, %{^attr => _}} -> {:ok, value}
case Repo.get_by(Setting, name: to_string(name)) do {:ok, _} -> {:error, :invalid_key}
nil -> create_setting!(name, value, datatype) {:error, changeset} -> {:error, changeset}
setting -> update_setting!(setting, value, datatype)
end end
end end
@doc """ @doc """
Gets the parsed value of a setting. Raises if the setting does not exist. Gets the value of a setting.
Returns value in type of `Ecto.Enum.mappings(Setting, :datatype)` Returns {:ok, value} | {:error, :invalid_key}
"""
def get(name) do
case Map.fetch(record(), name) do
{:ok, value} -> {:ok, value}
:error -> {:error, :invalid_key}
end
end
@doc """
Gets the value of a setting, raising if it doesn't exist.
Returns value
""" """
def get!(name) do def get!(name) do
Setting case get(name) do
|> Repo.get_by!(name: to_string(name)) {:ok, value} -> value
|> read_setting() {:error, _} -> raise "Setting `#{name}` not found"
end
@doc """
Attempts to find a setting by name or creates a setting with value
if one doesn't exist, returning the parsed value. Optionally allows
specifying the datatype.
Returns value in type of `Ecto.Enum.mappings(Setting, :datatype)`
"""
def fetch!(name, value) do
fetch!(name, value, infer_datatype(value))
end
def fetch!(name, value, datatype) do
case Repo.get_by(Setting, name: to_string(name)) do
nil -> create_setting!(name, value, datatype)
setting -> read_setting(setting)
end end
end end
defp change_setting(setting, attrs) do
Setting.changeset(setting, attrs)
end
defp create_setting!(name, value, datatype) do
%Setting{}
|> change_setting(%{name: to_string(name), value: to_string(value), datatype: datatype})
|> Repo.insert!()
|> read_setting()
end
defp update_setting!(setting, value, datatype) do
setting
|> change_setting(%{value: to_string(value), datatype: datatype})
|> Repo.update!()
|> read_setting()
end
defp read_setting(%{value: value, datatype: :string}), do: value
defp read_setting(%{value: value, datatype: :boolean}), do: value in ["true", "t", "1"]
defp read_setting(%{value: value, datatype: :integer}), do: String.to_integer(value)
defp read_setting(%{value: value, datatype: :float}), do: String.to_float(value)
defp infer_datatype(value) when is_boolean(value), do: :boolean
defp infer_datatype(value) when is_integer(value), do: :integer
defp infer_datatype(value) when is_float(value), do: :float
defp infer_datatype(value) when is_binary(value), do: :string
end end
+17
View File
@@ -0,0 +1,17 @@
defmodule Pinchflat.Utils.XmlUtils do
@moduledoc """
Utility methods for working with XML documents
"""
@doc """
Escapes invalid XML characters in a string
Returns binary()
"""
def safe(value) do
value
|> to_string()
|> Phoenix.HTML.html_escape()
|> Phoenix.HTML.safe_to_string()
end
end
+8 -1
View File
@@ -29,7 +29,7 @@ defmodule Pinchflat.YtDlp.CommandRunner do
command = backend_executable() command = backend_executable()
# These must stay in exactly this order, hence why I'm giving it its own variable. # These must stay in exactly this order, hence why I'm giving it its own variable.
# Also, can't use RAM file since yt-dlp needs a concrete filepath. # Also, can't use RAM file since yt-dlp needs a concrete filepath.
output_filepath = Keyword.get(addl_opts, :output_filepath, FSUtils.generate_metadata_tmpfile(:json)) output_filepath = generate_output_filepath(addl_opts)
print_to_file_opts = [{:print_to_file, output_template}, output_filepath] print_to_file_opts = [{:print_to_file, output_template}, output_filepath]
cookie_opts = build_cookie_options() cookie_opts = build_cookie_options()
formatted_command_opts = [url] ++ parse_options(command_opts ++ print_to_file_opts ++ cookie_opts) formatted_command_opts = [url] ++ parse_options(command_opts ++ print_to_file_opts ++ cookie_opts)
@@ -61,6 +61,13 @@ defmodule Pinchflat.YtDlp.CommandRunner do
end end
end end
defp generate_output_filepath(addl_opts) do
case Keyword.get(addl_opts, :output_filepath) do
nil -> FSUtils.generate_metadata_tmpfile(:json)
path -> path
end
end
defp build_cookie_options do defp build_cookie_options do
base_dir = Application.get_env(:pinchflat, :extras_directory) base_dir = Application.get_env(:pinchflat, :extras_directory)
cookie_file = Path.join(base_dir, "cookies.txt") cookie_file = Path.join(base_dir, "cookies.txt")
+2 -2
View File
@@ -35,10 +35,10 @@ defmodule Pinchflat.YtDlp.Media do
Returns {:ok, map()} | {:error, any, ...}. Returns {:ok, map()} | {:error, any, ...}.
""" """
def download(url, command_opts \\ []) do def download(url, command_opts \\ [], addl_opts \\ []) do
opts = [:no_simulate] ++ command_opts opts = [:no_simulate] ++ command_opts
with {:ok, output} <- backend_runner().run(url, opts, "after_move:%()j"), with {:ok, output} <- backend_runner().run(url, opts, "after_move:%()j", addl_opts),
{:ok, parsed_json} <- Phoenix.json_library().decode(output) do {:ok, parsed_json} <- Phoenix.json_library().decode(output) do
{:ok, parsed_json} {:ok, parsed_json}
else else
@@ -30,7 +30,7 @@ defmodule Pinchflat.UpgradeButtonLive do
|> String.downcase() |> String.downcase()
if normalized_text == "got it!" do if normalized_text == "got it!" do
Settings.set!(:pro_enabled, true) Settings.set(pro_enabled: true)
{:noreply, update(socket, :button_disabled, fn _ -> false end)} {:noreply, update(socket, :button_disabled, fn _ -> false end)}
else else
@@ -11,7 +11,7 @@ defmodule PinchflatWeb.Pages.PageController do
done_onboarding = params["onboarding"] == "0" done_onboarding = params["onboarding"] == "0"
force_onboarding = params["onboarding"] == "1" force_onboarding = params["onboarding"] == "1"
if done_onboarding, do: Settings.set!(:onboarding, false) if done_onboarding, do: Settings.set(onboarding: false)
if force_onboarding || Settings.get!(:onboarding) do if force_onboarding || Settings.get!(:onboarding) do
render_onboarding_page(conn) render_onboarding_page(conn)
@@ -30,7 +30,7 @@ defmodule PinchflatWeb.Pages.PageController do
end end
defp render_onboarding_page(conn) do defp render_onboarding_page(conn) do
Settings.set!(:onboarding, true) Settings.set(onboarding: true)
conn conn
|> render(:onboarding_checklist, |> render(:onboarding_checklist,
+1 -1
View File
@@ -4,7 +4,7 @@ defmodule Pinchflat.MixProject do
def project do def project do
[ [
app: :pinchflat, app: :pinchflat,
version: "0.1.8", version: "0.1.9",
elixir: "~> 1.16", elixir: "~> 1.16",
elixirc_paths: elixirc_paths(Mix.env()), elixirc_paths: elixirc_paths(Mix.env()),
start_permanent: Mix.env() == :prod, start_permanent: Mix.env() == :prod,
@@ -0,0 +1,7 @@
defmodule Pinchflat.Repo.Migrations.RenameSettingsTable do
use Ecto.Migration
def change do
rename table(:settings), to: table(:settings_backup)
end
end
@@ -0,0 +1,29 @@
defmodule Pinchflat.Repo.Migrations.CreateNewSettings do
use Ecto.Migration
def up do
create table(:settings) do
add :onboarding, :boolean, default: true, null: false
add :pro_enabled, :boolean, default: false, null: false
add :yt_dlp_version, :string
end
# Make an initial record because this will be the only one ever inserted
execute "INSERT INTO settings (onboarding, pro_enabled, yt_dlp_version) VALUES (true, false, NULL)"
# Set the value of onboarding to the previous version set in `settings_backup`
execute """
UPDATE settings
SET onboarding = COALESCE((SELECT value = 'true' FROM settings_backup WHERE name = 'onboarding'), true)
"""
execute """
UPDATE settings
SET pro_enabled = COALESCE((SELECT value = 'true' FROM settings_backup WHERE name = 'pro_enabled'), false)
"""
end
def down do
drop table(:settings)
end
end
@@ -1,25 +1,47 @@
defmodule Pinchflat.Boot.PreJobStartupTasksTest do defmodule Pinchflat.Boot.PreJobStartupTasksTest do
use Pinchflat.DataCase use Pinchflat.DataCase
import Pinchflat.JobFixtures
alias Pinchflat.Settings alias Pinchflat.Settings
alias Pinchflat.Settings.Setting
alias Pinchflat.Boot.PreJobStartupTasks alias Pinchflat.Boot.PreJobStartupTasks
describe "apply_default_settings" do describe "reset_executing_jobs" do
setup do test "resets executing jobs" do
Repo.delete_all(Setting) job = job_fixture()
Repo.update_all(Oban.Job, set: [state: "executing"])
:ok assert Repo.reload!(job).state == "executing"
end
test "sets default settings" do
assert_raise Ecto.NoResultsError, fn -> Settings.get!(:onboarding) end
assert_raise Ecto.NoResultsError, fn -> Settings.get!(:pro_enabled) end
PreJobStartupTasks.start_link() PreJobStartupTasks.start_link()
assert Settings.get!(:onboarding) assert Repo.reload!(job).state == "retryable"
refute Settings.get!(:pro_enabled) end
end
describe "create_blank_cookie_file" do
test "creates a blank cookie file" do
base_dir = Application.get_env(:pinchflat, :extras_directory)
filepath = Path.join(base_dir, "cookies.txt")
File.rm(filepath)
refute File.exists?(filepath)
PreJobStartupTasks.start_link()
assert File.exists?(filepath)
end
end
describe "apply_default_settings" do
test "sets default settings" do
Settings.set(yt_dlp_version: nil)
refute Settings.get!(:yt_dlp_version)
PreJobStartupTasks.start_link()
assert Settings.get!(:yt_dlp_version)
end end
end end
end end
@@ -4,6 +4,7 @@ defmodule Pinchflat.Downloading.MediaDownloadWorkerTest do
import Mox import Mox
import Pinchflat.MediaFixtures import Pinchflat.MediaFixtures
alias Pinchflat.Media
alias Pinchflat.Sources alias Pinchflat.Sources
alias Pinchflat.Filesystem.FilesystemHelpers alias Pinchflat.Filesystem.FilesystemHelpers
alias Pinchflat.Downloading.MediaDownloadWorker alias Pinchflat.Downloading.MediaDownloadWorker
@@ -55,7 +56,7 @@ defmodule Pinchflat.Downloading.MediaDownloadWorkerTest do
describe "perform/1" do describe "perform/1" do
test "it saves attributes to the media_item", %{media_item: media_item} do test "it saves attributes to the media_item", %{media_item: media_item} do
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot -> expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot, _addl ->
{:ok, render_metadata(:media_metadata)} {:ok, render_metadata(:media_metadata)}
end) end)
@@ -65,7 +66,7 @@ defmodule Pinchflat.Downloading.MediaDownloadWorkerTest do
end end
test "it saves the metadata to the media_item", %{media_item: media_item} do test "it saves the metadata to the media_item", %{media_item: media_item} do
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot -> expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot, _addl ->
{:ok, render_metadata(:media_metadata)} {:ok, render_metadata(:media_metadata)}
end) end)
@@ -82,7 +83,19 @@ defmodule Pinchflat.Downloading.MediaDownloadWorkerTest do
end end
test "it sets the job to retryable if the download fails", %{media_item: media_item} do test "it sets the job to retryable if the download fails", %{media_item: media_item} do
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot -> {:error, "error"} end) expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot, _addl -> {:error, "error"} end)
Oban.Testing.with_testing_mode(:inline, fn ->
{:ok, job} = Oban.insert(MediaDownloadWorker.new(%{id: media_item.id}))
assert job.state == "retryable"
end)
end
test "sets the job to retryable if the download failed and was retried", %{media_item: media_item} do
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot, _addl ->
{:error, "Unable to communicate with SponsorBlock", 1}
end)
Oban.Testing.with_testing_mode(:inline, fn -> Oban.Testing.with_testing_mode(:inline, fn ->
{:ok, job} = Oban.insert(MediaDownloadWorker.new(%{id: media_item.id})) {:ok, job} = Oban.insert(MediaDownloadWorker.new(%{id: media_item.id}))
@@ -92,29 +105,38 @@ defmodule Pinchflat.Downloading.MediaDownloadWorkerTest do
end end
test "it ensures error are returned in a 2-item tuple", %{media_item: media_item} do test "it ensures error are returned in a 2-item tuple", %{media_item: media_item} do
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot -> {:error, "error", 1} end) expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot, _addl -> {:error, "error", 1} end)
assert {:error, :download_failed} = perform_job(MediaDownloadWorker, %{id: media_item.id}) assert {:error, :download_failed} = perform_job(MediaDownloadWorker, %{id: media_item.id})
end end
test "it does not download if the source is set to not download", %{media_item: media_item} do test "it does not download if the source is set to not download", %{media_item: media_item} do
expect(YtDlpRunnerMock, :run, 0, fn _url, _opts, _ot -> :ok end) expect(YtDlpRunnerMock, :run, 0, fn _url, _opts, _ot, _addl -> :ok end)
Sources.update_source(media_item.source, %{download_media: false}) Sources.update_source(media_item.source, %{download_media: false})
perform_job(MediaDownloadWorker, %{id: media_item.id}) perform_job(MediaDownloadWorker, %{id: media_item.id})
end end
test "does not download if the media item is set to not download", %{media_item: media_item} do
expect(YtDlpRunnerMock, :run, 0, fn _url, _opts, _ot, _addl -> :ok end)
Media.update_media_item(media_item, %{prevent_download: true})
perform_job(MediaDownloadWorker, %{id: media_item.id})
end
test "downloads anyway if forced", %{media_item: media_item} do test "downloads anyway if forced", %{media_item: media_item} do
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot -> :ok end) expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot, _addl -> :ok end)
Sources.update_source(media_item.source, %{download_media: false}) Sources.update_source(media_item.source, %{download_media: false})
Media.update_media_item(media_item, %{prevent_download: true})
perform_job(MediaDownloadWorker, %{id: media_item.id, force: true}) perform_job(MediaDownloadWorker, %{id: media_item.id, force: true})
end end
test "it saves the file's size to the database", %{media_item: media_item} do test "it saves the file's size to the database", %{media_item: media_item} do
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot -> expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot, _addl ->
metadata = render_parsed_metadata(:media_metadata) metadata = render_parsed_metadata(:media_metadata)
FilesystemHelpers.write_p!(metadata["filepath"], "test") FilesystemHelpers.write_p!(metadata["filepath"], "test")
@@ -25,9 +25,11 @@ defmodule Pinchflat.Downloading.MediaDownloaderTest do
describe "download_for_media_item/3" do describe "download_for_media_item/3" do
test "it calls the backend runner", %{media_item: media_item} do test "it calls the backend runner", %{media_item: media_item} do
expect(YtDlpRunnerMock, :run, fn url, _opts, ot -> expect(YtDlpRunnerMock, :run, fn url, _opts, ot, addl ->
assert url == media_item.original_url assert url == media_item.original_url
assert ot == "after_move:%()j" assert ot == "after_move:%()j"
assert [{:output_filepath, filepath}] = addl
assert is_binary(filepath)
{:ok, render_metadata(:media_metadata)} {:ok, render_metadata(:media_metadata)}
end) end)
@@ -36,7 +38,7 @@ defmodule Pinchflat.Downloading.MediaDownloaderTest do
end end
test "it saves the metadata filepath to the database", %{media_item: media_item} do test "it saves the metadata filepath to the database", %{media_item: media_item} do
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot -> expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot, _addl ->
{:ok, render_metadata(:media_metadata)} {:ok, render_metadata(:media_metadata)}
end) end)
@@ -47,18 +49,56 @@ defmodule Pinchflat.Downloading.MediaDownloaderTest do
assert updated_media_item.metadata.thumbnail_filepath =~ "media_items/#{media_item.id}/maxresdefault.jpg" assert updated_media_item.metadata.thumbnail_filepath =~ "media_items/#{media_item.id}/maxresdefault.jpg"
end end
test "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 -> expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot, _addl ->
{:error, :some_error} {:error, :some_error, 1}
end) end)
assert {:error, :some_error} = MediaDownloader.download_for_media_item(media_item) assert {:error, :some_error} = MediaDownloader.download_for_media_item(media_item)
end end
test "unknown errors are passed through", %{media_item: media_item} do
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot, _addl ->
{:error, :some_error}
end)
assert {:error, message} = MediaDownloader.download_for_media_item(media_item)
assert message == "Unknown error: {:error, :some_error}"
end
end
describe "download_for_media_item/3 when testing retries" do
test "returns a recovered tuple on recoverable errors", %{media_item: media_item} do
message = "Unable to communicate with SponsorBlock"
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot, _addl ->
{:error, message, 1}
end)
assert {:recovered, ^message} = MediaDownloader.download_for_media_item(media_item)
end
test "attempts to update the media item on recoverable errors", %{media_item: media_item} do
message = "Unable to communicate with SponsorBlock"
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot, addl ->
[{:output_filepath, filepath}] = addl
File.write(filepath, render_metadata(:media_metadata))
{:error, message, 1}
end)
assert {:recovered, ^message} = MediaDownloader.download_for_media_item(media_item)
media_item = Repo.reload(media_item)
assert DateTime.diff(DateTime.utc_now(), media_item.media_downloaded_at) < 2
assert String.ends_with?(media_item.media_filepath, ".mkv")
end
end end
describe "download_for_media_item/3 when testing media_item attributes" do describe "download_for_media_item/3 when testing media_item attributes" do
setup do setup do
stub(YtDlpRunnerMock, :run, fn _url, _opts, _ot -> stub(YtDlpRunnerMock, :run, fn _url, _opts, _ot, _addl ->
{:ok, render_metadata(:media_metadata)} {:ok, render_metadata(:media_metadata)}
end) end)
@@ -100,7 +140,7 @@ defmodule Pinchflat.Downloading.MediaDownloaderTest do
end end
test "it extracts the thumbnail_filepath", %{media_item: media_item} do test "it extracts the thumbnail_filepath", %{media_item: media_item} do
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot -> expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot, _addl ->
metadata = render_parsed_metadata(:media_metadata) metadata = render_parsed_metadata(:media_metadata)
thumbnail_filepath = thumbnail_filepath =
@@ -124,7 +164,7 @@ defmodule Pinchflat.Downloading.MediaDownloaderTest do
end end
test "it extracts the metadata_filepath", %{media_item: media_item} do test "it extracts the metadata_filepath", %{media_item: media_item} do
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot -> expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot, _addl ->
metadata = render_parsed_metadata(:media_metadata) metadata = render_parsed_metadata(:media_metadata)
infojson_filepath = metadata["infojson_filename"] infojson_filepath = metadata["infojson_filename"]
@@ -143,7 +183,7 @@ defmodule Pinchflat.Downloading.MediaDownloaderTest do
describe "download_for_media_item/3 when testing NFO generation" do describe "download_for_media_item/3 when testing NFO generation" do
setup do setup do
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot -> expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot, _addl ->
{:ok, render_metadata(:media_metadata)} {:ok, render_metadata(:media_metadata)}
end) end)
@@ -30,6 +30,21 @@ defmodule Pinchflat.Metadata.NfoBuilderTest do
assert String.contains?(nfo, ~S(<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>)) assert String.contains?(nfo, ~S(<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>))
assert String.contains?(nfo, "<title>#{metadata["title"]}</title>") assert String.contains?(nfo, "<title>#{metadata["title"]}</title>")
end end
test "escapes invalid characters", %{filepath: filepath} do
metadata = %{
"title" => "hello' & <world>",
"uploader" => "uploader",
"id" => "id",
"description" => "description",
"upload_date" => "20210101"
}
result = NfoBuilder.build_and_store_for_media_item(filepath, metadata)
nfo = File.read!(result)
assert String.contains?(nfo, "hello&#39; &amp; &lt;world&gt;")
end
end end
describe "build_and_store_for_source/2" do describe "build_and_store_for_source/2" do
@@ -46,5 +61,18 @@ defmodule Pinchflat.Metadata.NfoBuilderTest do
assert String.contains?(nfo, ~S(<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>)) assert String.contains?(nfo, ~S(<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>))
assert String.contains?(nfo, "<title>#{metadata["title"]}</title>") assert String.contains?(nfo, "<title>#{metadata["title"]}</title>")
end end
test "escapes invalid characters", %{filepath: filepath} do
metadata = %{
"title" => "hello' & <world>",
"description" => "description",
"id" => "id"
}
result = NfoBuilder.build_and_store_for_source(filepath, metadata)
nfo = File.read!(result)
assert String.contains?(nfo, "hello&#39; &amp; &lt;world&gt;")
end
end end
end end
+29 -74
View File
@@ -9,100 +9,55 @@ defmodule Pinchflat.SettingsTest do
# are always created on app boot (including in the test env), # are always created on app boot (including in the test env),
# so we can't treat these like a clean slate. # so we can't treat these like a clean slate.
describe "list_settings/0" do setup do
test "returns all settings" do # Ensure we have a clean slate
Settings.set!("foo", "bar") Settings.set(onboarding: false)
results = Settings.list_settings() Settings.set(pro_enabled: false)
Settings.set(yt_dlp_version: nil)
assert Enum.all?(results, fn setting -> match?(%Setting{}, setting) end) :ok
end
describe "record/0" do
test "returns the only setting" do
assert %Setting{} = Settings.record()
end end
end end
describe "set/2" do describe "set/1" do
test "creates a new setting if one does not exist" do test "updates the setting" do
original = Repo.aggregate(Setting, :count, :id) assert {:ok, true} = Settings.set(onboarding: true)
Settings.set!("foo", "bar") assert {:ok, true} = Settings.get(:onboarding)
assert Repo.aggregate(Setting, :count, :id) == original + 1
end end
test "updates an existing setting if one exists" do test "returns an error if the setting key doesn't exist" do
Settings.set!("foo", "bar") assert {:error, :invalid_key} = Settings.set(foo: "bar")
original = Repo.aggregate(Setting, :count, :id)
Settings.set!("foo", "baz")
assert Repo.aggregate(Setting, :count, :id) == original
assert Settings.get!("foo") == "baz"
end end
test "returns the parsed value" do test "returns an error if the setting value is invalid" do
assert Settings.set!("foo", true) == true assert {:error, %Ecto.Changeset{}} = Settings.set(onboarding: "bar")
assert Settings.set!("foo", false) == false
assert Settings.set!("foo", 123) == 123
assert Settings.set!("foo", 12.34) == 12.34
assert Settings.set!("foo", "bar") == "bar"
end
test "allows for atom keys" do
assert Settings.set!(:foo, "bar") == "bar"
end
test "blows up when an unsupported datatype is used" do
assert_raise FunctionClauseError, fn ->
Settings.set!("foo", nil)
end
end
end
describe "set/3" do
test "allows manual specification of datatype" do
assert Settings.set!("foo", "true", :boolean) == true
assert Settings.set!("foo", "false", :boolean) == false
assert Settings.set!("foo", "123", :integer) == 123
assert Settings.set!("foo", "12.34", :float) == 12.34
end end
end end
describe "get/1" do describe "get/1" do
test "returns the value of the setting" do test "returns the setting value" do
Settings.set!("str", "bar") assert {:ok, false} = Settings.get(:onboarding)
Settings.set!("bool", true)
Settings.set!("int", 123)
Settings.set!("float", 12.34)
assert Settings.get!("str") == "bar"
assert Settings.get!("bool") == true
assert Settings.get!("int") == 123
assert Settings.get!("float") == 12.34
end end
test "allows for atom keys" do test "returns an error if the setting key doesn't exist" do
Settings.set!("str", "bar") assert {:error, :invalid_key} = Settings.get(:foo)
assert Settings.get!(:str) == "bar"
end
test "blows up when the setting does not exist" do
assert_raise Ecto.NoResultsError, fn ->
Settings.get!("foo")
end
end end
end end
describe "fetch/2" do describe "get!/1" do
test "creates a setting if one doesn't exist" do test "returns the setting value" do
original = Repo.aggregate(Setting, :count, :id) assert Settings.get!(:onboarding) == false
assert Settings.fetch!("foo", "bar") == "bar"
assert Repo.aggregate(Setting, :count, :id) == original + 1
end end
test "returns an existing setting if one does exist" do test "raises an error if the setting key doesn't exist" do
Settings.set!("foo", "bar") assert_raise RuntimeError, "Setting `foo` not found", fn ->
Settings.get!(:foo)
assert Settings.fetch!("foo", "baz") == "bar"
end end
end end
describe "fetch/3" do
test "allows manual specification of datatype" do
assert Settings.fetch!("foo", "true", :boolean) == true
end
end end
end end
+16
View File
@@ -0,0 +1,16 @@
defmodule Pinchflat.Utils.XmlUtilsTest do
use ExUnit.Case, async: true
alias Pinchflat.Utils.XmlUtils
describe "safe/1" do
test "escapes invalid characters" do
assert XmlUtils.safe("hello' & <world>") == "hello&#39; &amp; &lt;world&gt;"
end
test "converts input to string" do
assert XmlUtils.safe(42) == "42"
assert XmlUtils.safe(nil) == ""
end
end
end
+7 -5
View File
@@ -11,9 +11,10 @@ defmodule Pinchflat.YtDlp.MediaTest do
describe "download/2" do describe "download/2" do
test "it calls the backend runner with the expected arguments" do test "it calls the backend runner with the expected arguments" do
expect(YtDlpRunnerMock, :run, fn @media_url, opts, ot -> expect(YtDlpRunnerMock, :run, fn @media_url, opts, ot, addl ->
assert [:no_simulate] = opts assert [:no_simulate] = opts
assert "after_move:%()j" = ot assert "after_move:%()j" = ot
assert addl == []
{:ok, render_metadata(:media_metadata)} {:ok, render_metadata(:media_metadata)}
end) end)
@@ -22,17 +23,18 @@ defmodule Pinchflat.YtDlp.MediaTest do
end end
test "it passes along additional options" do test "it passes along additional options" do
expect(YtDlpRunnerMock, :run, fn _url, opts, _ot -> expect(YtDlpRunnerMock, :run, fn _url, opts, _ot, addl ->
assert [:no_simulate, :custom_arg] = opts assert [:no_simulate, :custom_arg] = opts
assert [addl_arg: true] = addl
{:ok, "{}"} {:ok, "{}"}
end) end)
assert {:ok, _} = Media.download(@media_url, [:custom_arg]) assert {:ok, _} = Media.download(@media_url, [:custom_arg], addl_arg: true)
end end
test "it parses and returns the generated file as JSON" do test "it parses and returns the generated file as JSON" do
expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot -> expect(YtDlpRunnerMock, :run, fn _url, _opts, _ot, _addl ->
{:ok, render_metadata(:media_metadata)} {:ok, render_metadata(:media_metadata)}
end) end)
@@ -41,7 +43,7 @@ defmodule Pinchflat.YtDlp.MediaTest do
end end
test "it returns errors" do test "it returns errors" do
expect(YtDlpRunnerMock, :run, fn _url, _opt, _ot -> expect(YtDlpRunnerMock, :run, fn _url, _opt, _ot, _addl ->
{:error, "something"} {:error, "something"}
end) end)
@@ -16,7 +16,7 @@ defmodule PinchflatWeb.MediaProfileControllerTest do
@invalid_attrs %{name: nil, output_path_template: nil} @invalid_attrs %{name: nil, output_path_template: nil}
setup do setup do
Settings.set!(:onboarding, false) Settings.set(onboarding: false)
:ok :ok
end end
@@ -35,7 +35,7 @@ defmodule PinchflatWeb.MediaProfileControllerTest do
end end
test "renders correct layout when onboarding", %{conn: conn} do test "renders correct layout when onboarding", %{conn: conn} do
Settings.set!(:onboarding, true) Settings.set(onboarding: true)
conn = get(conn, ~p"/media_profiles/new") conn = get(conn, ~p"/media_profiles/new")
refute html_response(conn, 200) =~ "MENU" refute html_response(conn, 200) =~ "MENU"
@@ -59,14 +59,14 @@ defmodule PinchflatWeb.MediaProfileControllerTest do
end end
test "redirects to onboarding when onboarding", %{conn: conn} do test "redirects to onboarding when onboarding", %{conn: conn} do
Settings.set!(:onboarding, true) Settings.set(onboarding: true)
conn = post(conn, ~p"/media_profiles", media_profile: @create_attrs) conn = post(conn, ~p"/media_profiles", media_profile: @create_attrs)
assert redirected_to(conn) == ~p"/?onboarding=1" assert redirected_to(conn) == ~p"/?onboarding=1"
end end
test "renders correct layout on error when onboarding", %{conn: conn} do test "renders correct layout on error when onboarding", %{conn: conn} do
Settings.set!(:onboarding, true) Settings.set(onboarding: true)
conn = post(conn, ~p"/media_profiles", media_profile: @invalid_attrs) conn = post(conn, ~p"/media_profiles", media_profile: @invalid_attrs)
refute html_response(conn, 200) =~ "MENU" refute html_response(conn, 200) =~ "MENU"
@@ -10,7 +10,7 @@ defmodule PinchflatWeb.PageControllerTest do
end end
test "displays the onboarding page when onboarding is forced", %{conn: conn} do test "displays the onboarding page when onboarding is forced", %{conn: conn} do
Settings.set!(:onboarding, false) Settings.set(onboarding: false)
conn = get(conn, ~p"/?onboarding=1") conn = get(conn, ~p"/?onboarding=1")
assert html_response(conn, 200) =~ "Welcome to Pinchflat" assert html_response(conn, 200) =~ "Welcome to Pinchflat"
@@ -25,7 +25,7 @@ defmodule PinchflatWeb.PageControllerTest do
end end
test "displays the home page when not onboarding", %{conn: conn} do test "displays the home page when not onboarding", %{conn: conn} do
Settings.set!(:onboarding, false) Settings.set(onboarding: false)
conn = get(conn, ~p"/") conn = get(conn, ~p"/")
assert html_response(conn, 200) =~ "MENU" assert html_response(conn, 200) =~ "MENU"
@@ -13,7 +13,7 @@ defmodule PinchflatWeb.SourceControllerTest do
setup do setup do
media_profile = media_profile_fixture() media_profile = media_profile_fixture()
Settings.set!(:onboarding, false) Settings.set(onboarding: false)
{ {
:ok, :ok,
@@ -47,7 +47,7 @@ defmodule PinchflatWeb.SourceControllerTest do
end end
test "renders correct layout when onboarding", %{conn: conn} do test "renders correct layout when onboarding", %{conn: conn} do
Settings.set!(:onboarding, true) Settings.set(onboarding: true)
conn = get(conn, ~p"/sources/new") conn = get(conn, ~p"/sources/new")
refute html_response(conn, 200) =~ "MENU" refute html_response(conn, 200) =~ "MENU"
@@ -74,14 +74,14 @@ defmodule PinchflatWeb.SourceControllerTest do
test "redirects to onboarding when onboarding", %{conn: conn, create_attrs: create_attrs} do test "redirects to onboarding when onboarding", %{conn: conn, create_attrs: create_attrs} do
expect(YtDlpRunnerMock, :run, 1, &runner_function_mock/3) expect(YtDlpRunnerMock, :run, 1, &runner_function_mock/3)
Settings.set!(:onboarding, true) Settings.set(onboarding: true)
conn = post(conn, ~p"/sources", source: create_attrs) conn = post(conn, ~p"/sources", source: create_attrs)
assert redirected_to(conn) == ~p"/?onboarding=1" assert redirected_to(conn) == ~p"/?onboarding=1"
end end
test "renders correct layout on error when onboarding", %{conn: conn, invalid_attrs: invalid_attrs} do test "renders correct layout on error when onboarding", %{conn: conn, invalid_attrs: invalid_attrs} do
Settings.set!(:onboarding, true) Settings.set(onboarding: true)
conn = post(conn, ~p"/sources", source: invalid_attrs) conn = post(conn, ~p"/sources", source: invalid_attrs)
refute html_response(conn, 200) =~ "MENU" refute html_response(conn, 200) =~ "MENU"