Update dependencies and lints

This commit is contained in:
2026-09-07 22:31:04 -07:00
parent b518d762f1
commit 9c288d051c
79 changed files with 3473 additions and 2923 deletions
+15 -4
View File
@@ -1,29 +1,40 @@
//! Command line argument parsing for the `flix` subcommand.
use flix::model::numbers::{EpisodeNumber, SeasonNumber};
use chrono::NaiveDate;
use clap::Subcommand;
/// Subcommand for adding `flix` media.
#[derive(Subcommand)]
pub enum AddCommand {
/// Add a flix collection
pub(crate) enum AddCommand {
/// Add a flix collection.
Collection {
/// The collection's title.
#[arg(value_name = "TITLE")]
title: String,
/// The collection's overview.
#[arg(value_name = "OVERVIEW")]
overview: String,
},
/// Add a flix episode
/// Add a flix episode.
Episode {
/// The episode's show's web slug.
#[arg(value_name = "SHOW_WEB_SLUG")]
show_slug: String,
show_web_slug: String,
/// The episode's season number.
#[arg(value_name = "NUMBER")]
season_number: SeasonNumber,
/// The episode's number.
#[arg(value_name = "NUMBER")]
episode_number: EpisodeNumber,
/// The episode's title.
#[arg(value_name = "TITLE")]
title: String,
/// The episode's overview.
#[arg(value_name = "OVERVIEW")]
overview: String,
/// The episode's air date.
#[arg(value_name = "DATE")]
air_date: NaiveDate,
},
+68 -52
View File
@@ -1,15 +1,18 @@
//! Command line argument parsing.
use std::path::{Path, PathBuf};
use anyhow::{Result, anyhow};
use clap::{Args, Parser, Subcommand};
pub mod flix;
pub mod tmdb;
pub(crate) mod flix;
pub(crate) mod tmdb;
/// Command line argument parser struct.
#[derive(Parser)]
#[command(version, about, long_about = None)]
pub struct Cli {
/// Use a custom config file
pub(crate) struct Cli {
/// Use a custom config file.
#[arg(
short,
long,
@@ -17,41 +20,53 @@ pub struct Cli {
default_value = "~/.config/flix/config.toml"
)]
config: PathBuf,
/// Use a custom cache file
/// Use a custom cache file.
#[arg(short = 'C', long, value_name = "FILE", default_value = "./flix.redb")]
cache: PathBuf,
/// Use a custom database file
/// Use a custom database file.
#[arg(short, long, value_name = "FILE", default_value = "./flix.db")]
database: PathBuf,
/// Enable tracing
/// Enable tracing.
#[arg(short, long)]
pub trace: bool,
trace: bool,
/// Subcommand to execute.
#[command(subcommand)]
command: Command,
}
impl Cli {
pub fn config_path(&self) -> PathBuf {
fn expect_home_dir() -> PathBuf {
#[allow(clippy::expect_used)]
std::env::home_dir().expect("you do not have a home directory")
}
match self.config.strip_prefix("~/") {
Ok(path) => expect_home_dir().join(path),
Err(_) => self.config.to_owned(),
}
/// Get the config file path.
///
/// # Panics
/// If the user doesn't have a home directory.
#[inline]
pub(crate) fn config_path(&self) -> PathBuf {
self.config.strip_prefix("~/").map_or_else(
|_| self.config.clone(),
|path| {
#[expect(
clippy::expect_used,
reason = "without a home directory this program is useless"
)]
std::env::home_dir()
.expect("you do not have a home directory")
.join(path)
},
)
}
pub fn cache_path(&self) -> &Path {
/// Get the path to the cache file.
#[inline]
pub(crate) fn cache_path(&self) -> &Path {
&self.cache
}
pub fn database_path(&self) -> Result<String> {
/// Get the path to the destination database.
///
/// # Errors
/// If the database path is not utf8.
#[inline]
pub(crate) fn database_path(&self) -> Result<String> {
self.database
.as_os_str()
.to_str()
@@ -59,77 +74,78 @@ impl Cli {
.ok_or_else(|| anyhow!(".as_os_str().to_str()"))
}
pub fn command(self) -> Command {
/// Get whether or not the trace flag was enabled.
#[inline]
pub(crate) const fn trace(&self) -> bool {
self.trace
}
/// Get the subcommand to run.
#[inline]
pub(crate) fn get_command(self) -> Command {
self.command
}
}
/// Optional overrides for media information.
#[derive(Args)]
pub struct AddOverrides {
pub(crate) struct AddOverrides {
/// Override the displayed title.
#[arg(long)]
pub title: Option<String>,
/// Override the title used to sort.
#[arg(long)]
pub sort_title: Option<String>,
/// Override the filesystem slug.
#[arg(long)]
pub fs_slug: Option<String>,
/// Overrride the web slug.
#[arg(long)]
pub web_slug: Option<String>,
}
/// Top level cli commands.
#[derive(Subcommand)]
pub enum Command {
/// Initialize a new database
pub(crate) enum Command {
/// Initialize a new database.
Init,
/// Add new items to the database
/// Add new items to the database.
Add {
/// Overrides.
#[command(flatten)]
overrides: AddOverrides,
/// Command.
#[command(subcommand)]
command: AddCommand,
},
/// Update an existing item in the database
Update {
#[command(subcommand)]
command: UpdateCommand,
},
}
/// Wrapper for `add` around different backends.
#[derive(Subcommand)]
pub enum AddCommand {
/// Use the flix backend
pub(crate) enum AddCommand {
/// Use the flix backend.
Flix {
/// Command backend.
#[command(subcommand)]
command: flix::AddCommand,
},
/// Use the TMDB backend
/// Use the TMDB backend.
Tmdb {
/// Command backend.
#[command(subcommand)]
command: tmdb::Command,
},
}
impl From<flix::AddCommand> for AddCommand {
#[inline]
fn from(value: flix::AddCommand) -> Self {
Self::Flix { command: value }
}
}
impl From<tmdb::Command> for AddCommand {
fn from(value: tmdb::Command) -> Self {
Self::Tmdb { command: value }
}
}
#[derive(Subcommand)]
pub enum UpdateCommand {
/// Use the TMDB backend
Tmdb {
#[command(subcommand)]
command: tmdb::Command,
},
}
impl From<tmdb::Command> for UpdateCommand {
#[inline]
fn from(value: tmdb::Command) -> Self {
Self::Tmdb { command: value }
}
+24 -12
View File
@@ -1,41 +1,53 @@
//! Command line argument parsing for the `tmdb` subcommand.
use flix::model::numbers::{EpisodeNumber, SeasonNumber};
use flix::tmdb::model::id::RawId;
use flix::tmdb::model::id::TmdbRepr;
use clap::Subcommand;
/// Subcommand for adding `tmdb` media.
#[derive(Subcommand)]
pub enum Command {
/// Process a TMDB collection
pub(crate) enum Command {
/// Process a TMDB collection.
Collection {
/// The collection's ID.
#[arg(value_name = "TMDB_ID")]
id: RawId,
id: TmdbRepr,
},
/// Process a TMDB movie
/// Process a TMDB movie.
Movie {
/// The movie's ID.
#[arg(value_name = "TMDB_ID")]
id: RawId,
id: TmdbRepr,
},
/// Process a TMDB show
/// Process a TMDB show.
Show {
/// The show's ID.
#[arg(value_name = "TMDB_ID")]
id: RawId,
id: TmdbRepr,
},
/// Process a TMDB season
/// Process a TMDB season.
Season {
/// The season's show's ID.
#[arg(value_name = "TMDB_ID")]
id: RawId,
id: TmdbRepr,
/// The season's number.
#[arg(value_name = "SEASON_NUM")]
season: SeasonNumber,
},
/// Process a TMDB episode
/// Process a TMDB episode.
#[command(trailing_var_arg = true)]
Episode {
/// The episode's show's ID.
#[arg(value_name = "TMDB_ID")]
id: RawId,
id: TmdbRepr,
/// The episode's season's number.
#[arg(value_name = "SEASON_NUM")]
season: SeasonNumber,
/// The episode's number.
#[arg(value_name = "EPISODE_NUM")]
episode: EpisodeNumber,
/// Additional episode numbers for merged media files.
#[arg(value_name = "...")]
episodes: Vec<EpisodeNumber>,
},
+12 -4
View File
@@ -1,21 +1,29 @@
//! CLI configuration.
/// Top level config struct.
#[derive(serde::Deserialize)]
pub struct Config {
pub(crate) struct Config {
/// The TMDB config.
tmdb: TmdbConfig,
}
/// TMDB config struct.
#[derive(serde::Deserialize)]
pub struct TmdbConfig {
pub(crate) struct TmdbConfig {
/// The bearer token to use for API requests.
bearer_token: String,
}
impl Config {
pub fn tmdb(&self) -> &TmdbConfig {
/// Get the TMDB config.
pub(crate) const fn tmdb(&self) -> &TmdbConfig {
&self.tmdb
}
}
impl TmdbConfig {
pub fn bearer_token(&self) -> &str {
/// Get the bearer token.
pub(crate) fn bearer_token(&self) -> &str {
&self.bearer_token
}
}
+22 -6
View File
@@ -1,9 +1,17 @@
//! Databse helpers.
use std::path::Path;
use flix::db::connection::Connection;
use anyhow::{Context, Result, bail};
use anyhow::{Context as _, Result, bail};
use sea_orm::{ConnectOptions, Database};
use tokio::fs;
/// Connect to a database using a connection string.
///
/// # Errors
/// If the database cannot be opened.
async fn connect(string: String) -> Result<Connection> {
Connection::try_from(
Database::connect(ConnectOptions::new(string))
@@ -14,14 +22,22 @@ async fn connect(string: String) -> Result<Connection> {
.context("Connection::try_from")
}
pub async fn open(database_path: String) -> Result<Connection> {
connect(format!("sqlite:{database_path}?mode=rw")).await
/// Helper for opening an existing database at the given path.
///
/// # Errors
/// If the database cannot be opened.
pub(crate) async fn open(path: &Path) -> Result<Connection> {
connect(format!("sqlite:{}?mode=rw", path.display())).await
}
pub async fn open_new(database_path: String) -> Result<Connection> {
if fs::try_exists(&database_path).await? {
/// Helper for creating then opening a database at the given path.
///
/// # Errors
/// If the database already exists or cannot be openend after creation.
pub(crate) async fn open_new(path: &Path) -> Result<Connection> {
if fs::try_exists(path).await? {
bail!("database already exists");
}
connect(format!("sqlite:{database_path}?mode=rwc")).await
connect(format!("sqlite:{}?mode=rwc", path.display())).await
}
+29 -27
View File
@@ -1,15 +1,19 @@
//! flix-cli
//! flix-cli.
use std::rc::Rc;
extern crate alloc;
use std::path::Path;
use alloc::sync::Arc;
use flix::tmdb::{self, CachePolicy, Client, RedbCache};
use anyhow::{Context, Result};
use clap::Parser;
use anyhow::{Context as _, Result};
use clap::Parser as _;
use tokio::fs;
mod cli;
use cli::{AddCommand, Cli, Command, UpdateCommand};
use cli::{AddCommand, Cli, Command};
mod config;
use config::Config;
@@ -20,47 +24,57 @@ mod db;
mod run;
#[tokio::main(flavor = "current_thread")]
#[cfg_attr(test, expect(clippy::missing_errors_doc, reason = "main function"))]
#[cfg_attr(test, expect(clippy::missing_panics_doc, reason = "main function "))]
async fn main() -> Result<()> {
let cli = Cli::parse();
let config = fs::read_to_string(cli.config_path())
.await
.with_context(|| format!("could not read config: {:?}", cli.config_path()))?;
.with_context(|| format!("could not read config: {}", cli.config_path().display()))?;
let config: Config = toml::from_str(config.as_str())
.with_context(|| format!("could not parse config: {:?}", cli.config_path()))?;
.with_context(|| format!("could not parse config: {}", cli.config_path().display()))?;
let database_path = cli.database_path()?;
let database_path = Path::new(&database_path);
let config = tmdb::Config::new(config.tmdb().bearer_token().to_owned());
let cache = Rc::new(RedbCache::new(cli.cache_path())?);
let cache = Arc::new(RedbCache::new(cli.cache_path())?);
let client = Client::new(config, cache, CachePolicy::Full);
if cli.trace {
if cli.trace() {
tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.with_test_writer()
.init();
}
match cli.command() {
match cli.get_command() {
Command::Init => exec_init(database_path).await?,
Command::Add { command, overrides } => {
exec_add(client, database_path, command, overrides).await?
exec_add(client, database_path, command, overrides).await?;
}
Command::Update { command } => exec_update(client, database_path, command).await?,
}
Ok(())
}
async fn exec_init(database_path: String) -> Result<()> {
db::open_new(database_path).await?;
/// Execute the `init` command.
///
/// # Errors
/// Forwards any errors.
async fn exec_init(database_path: &Path) -> Result<()> {
drop(db::open_new(database_path).await?);
Ok(())
}
/// Execute the `add` command.
///
/// # Errors
/// Forwards any errors.
async fn exec_add(
client: Client,
database_path: String,
database_path: &Path,
command: AddCommand,
overrides: AddOverrides,
) -> Result<()> {
@@ -77,15 +91,3 @@ async fn exec_add(
Ok(())
}
async fn exec_update(client: Client, database_path: String, command: UpdateCommand) -> Result<()> {
let database = db::open(database_path).await?;
match command {
UpdateCommand::Tmdb { command } => {
run::tmdb::update(client, database.as_ref(), command).await?;
}
}
Ok(())
}
+24 -13
View File
@@ -1,3 +1,5 @@
//! The `flix` runtime backend.
use flix::db::entity;
use flix::model::id::{CollectionId, ShowId};
use flix::model::numbers::{EpisodeNumber, SeasonNumber};
@@ -5,12 +7,19 @@ use flix::model::text;
use anyhow::Result;
use sea_orm::ActiveValue::{NotSet, Set};
use sea_orm::{ActiveModelTrait, DatabaseConnection, DbErr, TransactionError, TransactionTrait};
use sea_orm::{
ActiveModelTrait as _, DatabaseConnection, DbErr, TransactionError, TransactionTrait as _,
};
use crate::cli::AddOverrides;
use crate::cli::flix::AddCommand;
pub async fn add(
/// Execute an `add` command.
///
/// # Errors
/// Forwards any database transaction failures.
#[expect(clippy::print_stdout, reason = "we want to print in a binary")]
pub(crate) async fn add(
db: &DatabaseConnection,
command: AddCommand,
overrides: AddOverrides,
@@ -50,15 +59,16 @@ pub async fn add(
match result {
Ok(_) => {}
Err(TransactionError::Connection(err)) => Err(err)?,
Err(TransactionError::Transaction(err)) => Err(err)?,
};
println!("Created Collection: {}", title);
Err(TransactionError::Connection(err) | TransactionError::Transaction(err)) => {
return Err(err.into());
}
}
println!("Created Collection: {title}");
Ok(())
}
AddCommand::Episode {
show_slug,
show_web_slug,
season_number,
episode_number,
title,
@@ -70,11 +80,11 @@ pub async fn add(
let title = overrides.title.unwrap_or_else(|| title.clone());
Box::pin(async move {
let show = entity::info::shows::Entity::find_by_web_slug(&show_slug)
let show = entity::info::shows::Entity::find_by_web_slug(&show_web_slug)
.one(txn)
.await?
.ok_or_else(|| {
DbErr::Custom(format!("show '{}' does not exist", show_slug))
DbErr::Custom(format!("show '{show_web_slug}' does not exist"))
})?;
let flix = entity::info::episodes::ActiveModel {
@@ -95,10 +105,11 @@ pub async fn add(
match result {
Ok(_) => {}
Err(TransactionError::Connection(err)) => Err(err)?,
Err(TransactionError::Transaction(err)) => Err(err)?,
};
println!("Created Episode: {}", title);
Err(TransactionError::Connection(err) | TransactionError::Transaction(err)) => {
return Err(err.into());
}
}
println!("Created Episode: {title}");
Ok(())
}
+4 -2
View File
@@ -1,2 +1,4 @@
pub mod flix;
pub mod tmdb;
//! Various runtime backends.
pub(crate) mod flix;
pub(crate) mod tmdb;
+142 -673
View File
@@ -1,4 +1,6 @@
use std::collections::HashMap;
//! The `flix` runtime backend.
use alloc::collections::BTreeMap;
use flix::db::entity;
use flix::model::id::{CollectionId, MovieId, ShowId};
@@ -9,17 +11,24 @@ use flix::tmdb::model::id::{
CollectionId as TmdbCollectionId, MovieId as TmdbMovieId, ShowId as TmdbShowId,
};
use anyhow::{Context, Result, bail};
use chrono::{Datelike, Utc};
use anyhow::{Context as _, Result, bail};
use chrono::{Datelike as _, Utc};
use sea_orm::ActiveValue::{NotSet, Set};
use sea_orm::{
ActiveModelTrait, DatabaseConnection, DbErr, EntityTrait, TransactionError, TransactionTrait,
ActiveModelTrait as _, DatabaseConnection, DbErr, EntityTrait as _, TransactionError,
TransactionTrait as _,
};
use crate::cli::AddOverrides;
use crate::cli::tmdb::Command;
pub async fn add(
/// Execute an `add` command.
///
/// # Errors
/// Forwards any database transaction failures or TMDB API failures.
#[expect(clippy::print_stderr, reason = "we want to print in a binary")]
#[expect(clippy::print_stdout, reason = "we want to print in a binary")]
pub(crate) async fn add(
client: Client,
db: &DatabaseConnection,
command: Command,
@@ -54,13 +63,15 @@ pub async fn add(
.web_slug
.unwrap_or_else(|| text::make_web_slug(&title));
const COLLECTION_SUFFIX_TO_REMOVE: &str = "-collection";
if web_slug.ends_with(COLLECTION_SUFFIX_TO_REMOVE) {
web_slug.truncate(
web_slug
.len()
.saturating_sub(COLLECTION_SUFFIX_TO_REMOVE.len()),
);
{
const COLLECTION_SUFFIX_TO_REMOVE: &str = "-collection";
if web_slug.ends_with(COLLECTION_SUFFIX_TO_REMOVE) {
web_slug.truncate(
web_slug
.len()
.saturating_sub(COLLECTION_SUFFIX_TO_REMOVE.len()),
);
}
}
let result: Result<CollectionId, TransactionError<DbErr>> = db
@@ -78,7 +89,7 @@ pub async fn add(
.insert(txn)
.await?;
entity::tmdb::collections::ActiveModel {
_ = entity::tmdb::collections::ActiveModel {
tmdb_id: Set(id),
flix_id: Set(flix.id),
last_update: Set(Utc::now()),
@@ -94,10 +105,11 @@ pub async fn add(
match result {
Ok(_) => {}
Err(TransactionError::Connection(err)) => Err(err)?,
Err(TransactionError::Transaction(err)) => Err(err)?,
};
println!("Created Collection: {}", title);
Err(TransactionError::Connection(err) | TransactionError::Transaction(err)) => {
return Err(err.into());
}
}
println!("Created Collection: {title}");
Ok(())
}
@@ -145,7 +157,7 @@ pub async fn add(
.insert(txn)
.await?;
entity::tmdb::movies::ActiveModel {
_ = entity::tmdb::movies::ActiveModel {
tmdb_id: Set(id),
flix_id: Set(flix.id),
last_update: Set(Utc::now()),
@@ -162,10 +174,11 @@ pub async fn add(
match result {
Ok(_) => {}
Err(TransactionError::Connection(err)) => Err(err)?,
Err(TransactionError::Transaction(err)) => Err(err)?,
};
println!("Created Movie: {} ({})", title, year);
Err(TransactionError::Connection(err) | TransactionError::Transaction(err)) => {
return Err(err.into());
}
}
println!("Created Movie: {title} ({year})");
Ok(())
}
@@ -183,7 +196,7 @@ pub async fn add(
.await
.with_context(|| format!("shows().get_details({})", id.into_raw()))?;
let mut seasons = Vec::new();
let mut episodes = HashMap::new();
let mut episodes = BTreeMap::new();
for season in 1..=show.number_of_seasons {
let season = SeasonNumber::new(season);
@@ -191,12 +204,11 @@ pub async fn add(
.seasons()
.get_details(id, season, None)
.await
.with_context(|| {
format!("seasons().get_details({}, {})", id.into_raw(), season)
}) {
.with_context(|| format!("seasons().get_details({}, {season})", id.into_raw()))
{
Ok(season) => season,
Err(err) => {
eprintln!("{err:?}");
eprintln!("{err}");
continue;
}
};
@@ -227,11 +239,9 @@ pub async fn add(
Ok(value) => value,
Err(err) => {
eprintln!(
"skipping episode ({}, {}, {}) - {}",
"skipping episode ({}, {}, {episode}) - {err}",
id.into_raw(),
season.season_number,
episode,
err
);
break;
}
@@ -239,7 +249,7 @@ pub async fn add(
season_episodes.push(episode);
}
episodes.insert(season.season_number, season_episodes);
drop(episodes.insert(season.season_number, season_episodes));
seasons.push(season);
}
@@ -273,7 +283,7 @@ pub async fn add(
.insert(txn)
.await?;
entity::tmdb::shows::ActiveModel {
_ = entity::tmdb::shows::ActiveModel {
tmdb_id: Set(id),
flix_id: Set(flix.id),
last_update: Set(Utc::now()),
@@ -283,17 +293,19 @@ pub async fn add(
.await?;
for season in seasons {
entity::info::seasons::ActiveModel {
show_id: Set(flix.id),
season_number: Set(season.season_number),
title: Set(season.title),
overview: Set(season.overview),
date: Set(season.air_date),
}
.insert(txn)
.await?;
drop(
entity::info::seasons::ActiveModel {
show_id: Set(flix.id),
season_number: Set(season.season_number),
title: Set(season.title),
overview: Set(season.overview),
date: Set(season.air_date),
}
.insert(txn)
.await?,
);
entity::tmdb::seasons::ActiveModel {
_ = entity::tmdb::seasons::ActiveModel {
tmdb_show: Set(id),
tmdb_season: Set(season.season_number),
flix_show: Set(flix.id),
@@ -306,18 +318,20 @@ pub async fn add(
for (season, episodes) in episodes {
for episode in episodes {
entity::info::episodes::ActiveModel {
show_id: Set(flix.id),
season_number: Set(season),
episode_number: Set(episode.episode_number),
title: Set(episode.title),
overview: Set(episode.overview),
date: Set(episode.air_date),
}
.insert(txn)
.await?;
drop(
entity::info::episodes::ActiveModel {
show_id: Set(flix.id),
season_number: Set(season),
episode_number: Set(episode.episode_number),
title: Set(episode.title),
overview: Set(episode.overview),
date: Set(episode.air_date),
}
.insert(txn)
.await?,
);
entity::tmdb::episodes::ActiveModel {
_ = entity::tmdb::episodes::ActiveModel {
tmdb_show: Set(id),
tmdb_season: Set(season),
tmdb_episode: Set(episode.episode_number),
@@ -339,10 +353,11 @@ pub async fn add(
match result {
Ok(_) => {}
Err(TransactionError::Connection(err)) => Err(err)?,
Err(TransactionError::Transaction(err)) => Err(err)?,
};
println!("Created Show: {} ({})", title, year);
Err(TransactionError::Connection(err) | TransactionError::Transaction(err)) => {
return Err(err.into());
}
}
println!("Created Show: {title} ({year})");
Ok(())
}
@@ -366,11 +381,7 @@ pub async fn add(
.get_details(id, season_number, None)
.await
.with_context(|| {
format!(
"seasons().get_details({}, {})",
id.into_raw(),
season_number
)
format!("seasons().get_details({}, {season_number})", id.into_raw())
})?;
let mut episodes = Vec::new();
@@ -391,11 +402,9 @@ pub async fn add(
Ok(value) => value,
Err(err) => {
eprintln!(
"skipping episode ({}, {}, {}) - {}",
"skipping episode ({}, {}, {episode}) - {err}",
id.into_raw(),
season.season_number,
episode,
err
);
break;
}
@@ -406,17 +415,19 @@ pub async fn add(
let result: Result<(), TransactionError<DbErr>> = db
.transaction(|txn| {
Box::pin(async move {
entity::info::seasons::ActiveModel {
show_id: Set(show.flix_id),
season_number: Set(season_number),
title: Set(season.title),
overview: Set(season.overview),
date: Set(season.air_date),
}
.insert(txn)
.await?;
drop(
entity::info::seasons::ActiveModel {
show_id: Set(show.flix_id),
season_number: Set(season_number),
title: Set(season.title),
overview: Set(season.overview),
date: Set(season.air_date),
}
.insert(txn)
.await?,
);
entity::tmdb::seasons::ActiveModel {
_ = entity::tmdb::seasons::ActiveModel {
tmdb_show: Set(show.tmdb_id),
tmdb_season: Set(season_number),
flix_show: Set(show.flix_id),
@@ -427,18 +438,20 @@ pub async fn add(
.await?;
for episode in episodes {
entity::info::episodes::ActiveModel {
show_id: Set(show.flix_id),
season_number: Set(season_number),
episode_number: Set(episode.episode_number),
title: Set(episode.title),
overview: Set(episode.overview),
date: Set(episode.air_date),
}
.insert(txn)
.await?;
drop(
entity::info::episodes::ActiveModel {
show_id: Set(show.flix_id),
season_number: Set(season_number),
episode_number: Set(episode.episode_number),
title: Set(episode.title),
overview: Set(episode.overview),
date: Set(episode.air_date),
}
.insert(txn)
.await?,
);
entity::tmdb::episodes::ActiveModel {
_ = entity::tmdb::episodes::ActiveModel {
tmdb_show: Set(show.tmdb_id),
tmdb_season: Set(season_number),
tmdb_episode: Set(episode.episode_number),
@@ -458,14 +471,14 @@ pub async fn add(
.await;
match result {
Ok(_) => {}
Err(TransactionError::Connection(err)) => Err(err)?,
Err(TransactionError::Transaction(err)) => Err(err)?,
};
Ok(()) => {}
Err(TransactionError::Connection(err) | TransactionError::Transaction(err)) => {
return Err(err.into());
}
}
println!(
"Created Season: {} S{}",
"Created Season: {} S{season_number}",
show.flix_id.into_raw(),
season_number
);
Ok(())
@@ -476,19 +489,10 @@ pub async fn add(
episode,
episodes,
} => {
let id = TmdbShowId::from_raw(id);
let season_number = season;
let Some(show) = entity::tmdb::shows::Entity::find_by_id(id).one(db).await? else {
bail!("show does not exists");
};
let Some(_) = entity::tmdb::seasons::Entity::find_by_id((id, season))
.one(db)
.await?
else {
bail!("season does not exists");
};
/// Fetch and store episode information.
///
/// # Errors
/// Forwards any database transaction failures or TMDB API failures.
async fn fetch_episode(
client: &Client,
db: &DatabaseConnection,
@@ -512,24 +516,26 @@ pub async fn add(
.get_details(id, season, episode_number, None)
.await
.with_context(|| {
format!("episodes().get_details({}, {})", id.into_raw(), season)
format!("episodes().get_details({}, {season})", id.into_raw())
})?;
let result: Result<(), TransactionError<DbErr>> = db
.transaction(|txn| {
Box::pin(async move {
entity::info::episodes::ActiveModel {
show_id: Set(flix_id),
season_number: Set(season),
episode_number: Set(episode_number),
title: Set(episode.title),
overview: Set(episode.overview),
date: Set(episode.air_date),
}
.insert(txn)
.await?;
drop(
entity::info::episodes::ActiveModel {
show_id: Set(flix_id),
season_number: Set(season),
episode_number: Set(episode_number),
title: Set(episode.title),
overview: Set(episode.overview),
date: Set(episode.air_date),
}
.insert(txn)
.await?,
);
entity::tmdb::episodes::ActiveModel {
_ = entity::tmdb::episodes::ActiveModel {
tmdb_show: Set(tmdb_id),
tmdb_season: Set(season),
tmdb_episode: Set(episode_number),
@@ -548,20 +554,32 @@ pub async fn add(
.await;
match result {
Ok(_) => {}
Err(TransactionError::Connection(err)) => Err(err)?,
Err(TransactionError::Transaction(err)) => Err(err)?,
};
Ok(()) => {}
Err(TransactionError::Connection(err) | TransactionError::Transaction(err)) => {
return Err(err.into());
}
}
println!(
"Created Episode: {} S{}E{}",
"Created Episode: {} S{season}E{episode_number}",
flix_id.into_raw(),
season,
episode_number
);
Ok(())
}
let id = TmdbShowId::from_raw(id);
let season_number = season;
let Some(show) = entity::tmdb::shows::Entity::find_by_id(id).one(db).await? else {
bail!("show does not exists");
};
let Some(_) = entity::tmdb::seasons::Entity::find_by_id((id, season))
.one(db)
.await?
else {
bail!("season does not exists");
};
let flix_id = show.flix_id;
let tmdb_id = show.tmdb_id;
@@ -574,552 +592,3 @@ pub async fn add(
}
}
}
pub async fn update(client: Client, db: &DatabaseConnection, command: Command) -> Result<()> {
_ = client;
_ = db;
_ = command;
unimplemented!("updates")
// match command {
// Command::Collection { id } => {
// let id = TmdbCollectionId::from_raw(id);
// let collection = entity::tmdb::collections::Entity::find_by_id(id)
// .one(db)
// .await?;
// if collection.is_some() {
// bail!("collection already exists");
// }
// let collection = client
// .collections()
// .get_details(id, None)
// .await
// .with_context(|| format!("collections().get_details({})", id.into_raw()))?;
// let title = overrides.title.unwrap_or(collection.title);
// let sort_title = overrides
// .sort_title
// .unwrap_or_else(|| text::make_sortable_title(&title));
// let fs_slug = overrides
// .fs_slug
// .unwrap_or_else(|| text::make_fs_slug(&title));
// let web_slug = overrides
// .web_slug
// .unwrap_or_else(|| text::make_web_slug(&title));
// let result: Result<CollectionId, TransactionError<DbErr>> = db
// .transaction(|txn| {
// let title = title.clone();
// Box::pin(async move {
// let flix = entity::info::collections::ActiveModel {
// id: NotSet,
// title: Set(title),
// overview: Set(collection.overview),
// sort_title: Set(sort_title),
// fs_slug: Set(fs_slug),
// web_slug: Set(web_slug),
// }
// .insert(txn)
// .await?;
// entity::tmdb::collections::ActiveModel {
// tmdb_id: Set(id),
// flix_id: Set(flix.id),
// last_update: Set(Utc::now()),
// movie_count: Set(collection.movies.len().try_into().unwrap_or(0)),
// }
// .insert(txn)
// .await?;
// Ok(flix.id)
// })
// })
// .await;
// let flix_id = match result {
// Ok(id) => id,
// Err(TransactionError::Connection(err)) => Err(err)?,
// Err(TransactionError::Transaction(err)) => Err(err)?,
// };
// println!("Created Collection: {}", title, flix_id.into_raw());
// Ok(())
// }
// Command::Movie { id } => {
// let id = TmdbMovieId::from_raw(id);
// let movie = entity::tmdb::movies::Entity::find_by_id(id).one(db).await?;
// if movie.is_some() {
// bail!("movie already exists");
// }
// let movie = client
// .movies()
// .get_details(id, None)
// .await
// .with_context(|| format!("movies().get_details({})", id.into_raw()))?;
// let title = overrides.title.unwrap_or(movie.title);
// let year = movie.release_date.year();
// let sort_title = overrides
// .sort_title
// .unwrap_or_else(|| text::make_sortable_title(&title));
// let fs_slug = overrides
// .fs_slug
// .unwrap_or_else(|| text::make_fs_slug_year(&title, year));
// let web_slug = overrides
// .web_slug
// .unwrap_or_else(|| text::make_web_slug_year(&title, year));
// let result: Result<MovieId, TransactionError<DbErr>> = db
// .transaction(|txn| {
// let title = title.clone();
// Box::pin(async move {
// let flix = entity::info::movies::ActiveModel {
// id: NotSet,
// title: Set(title),
// tagline: Set(movie.tagline),
// overview: Set(movie.overview),
// date: Set(movie.release_date),
// sort_title: Set(sort_title),
// fs_slug: Set(fs_slug),
// web_slug: Set(web_slug),
// }
// .insert(txn)
// .await?;
// entity::tmdb::movies::ActiveModel {
// tmdb_id: Set(id),
// flix_id: Set(flix.id),
// last_update: Set(Utc::now()),
// runtime: Set(movie.runtime.into()),
// collection_id: Set(movie.collection.map(|c| c.id)),
// }
// .insert(txn)
// .await?;
// Ok(flix.id)
// })
// })
// .await;
// let flix_id = match result {
// Ok(id) => id,
// Err(TransactionError::Connection(err)) => Err(err)?,
// Err(TransactionError::Transaction(err)) => Err(err)?,
// };
// println!(
// "Created Movie: {} ({})",
// title,
// year,
// flix_id.into_raw(),
// );
// Ok(())
// }
// Command::Show { id } => {
// let id = TmdbShowId::from_raw(id);
// let show = entity::tmdb::shows::Entity::find_by_id(id).one(db).await?;
// if show.is_some() {
// bail!("show already exists");
// }
// let show = client
// .shows()
// .get_details(id, None)
// .await
// .with_context(|| format!("shows().get_details({})", id.into_raw()))?;
// let mut seasons = Vec::new();
// let mut episodes = HashMap::new();
// for season in 1..=show.number_of_seasons {
// let season = SeasonNumber::new(season);
// let season = match client
// .seasons()
// .get_details(id, season, None)
// .await
// .with_context(|| {
// format!("seasons().get_details({}, {})", id.into_raw(), season)
// }) {
// Ok(season) => season,
// Err(err) => {
// eprintln!("{err:?}");
// continue;
// }
// };
// if season.air_date > Utc::now().naive_utc().date() {
// eprintln!(
// "skipping season ({}, {})",
// id.into_raw(),
// season.season_number
// );
// break;
// }
// let Ok(number_of_episodes) = u32::try_from(season.episodes.len()) else {
// bail!(
// "could not convert {} to an EpisodeNumber",
// season.episodes.len()
// )
// };
// let mut season_episodes = Vec::new();
// for episode in 1..=number_of_episodes {
// let episode = EpisodeNumber::new(episode);
// let Ok(episode) = client
// .episodes()
// .get_details(id, season.season_number, episode, None)
// .await
// else {
// eprintln!(
// "skipping episode ({}, {}, {})",
// id.into_raw(),
// season.season_number,
// episode
// );
// break;
// };
// season_episodes.push(episode);
// }
// episodes.insert(season.season_number, season_episodes);
// seasons.push(season);
// }
// let title = overrides.title.unwrap_or(show.title);
// let year = show.first_air_date.year();
// let sort_title = overrides
// .sort_title
// .unwrap_or_else(|| text::make_sortable_title(&title));
// let fs_slug = overrides
// .fs_slug
// .unwrap_or_else(|| text::make_fs_slug_year(&title, year));
// let web_slug = overrides
// .web_slug
// .unwrap_or_else(|| text::make_web_slug_year(&title, year));
// let result: Result<ShowId, TransactionError<DbErr>> = db
// .transaction(|txn| {
// let title = title.clone();
// Box::pin(async move {
// let flix = entity::info::shows::ActiveModel {
// id: NotSet,
// title: Set(title),
// tagline: Set(show.tagline),
// overview: Set(show.overview),
// date: Set(show.first_air_date),
// sort_title: Set(sort_title),
// fs_slug: Set(fs_slug),
// web_slug: Set(web_slug),
// }
// .insert(txn)
// .await?;
// entity::tmdb::shows::ActiveModel {
// tmdb_id: Set(id),
// flix_id: Set(flix.id),
// last_update: Set(Utc::now()),
// number_of_seasons: Set(show.number_of_seasons),
// }
// .insert(txn)
// .await?;
// for season in seasons {
// entity::info::seasons::ActiveModel {
// show_id: Set(flix.id),
// season_number: Set(season.season_number),
// title: Set(season.title),
// overview: Set(season.overview),
// date: Set(season.air_date),
// }
// .insert(txn)
// .await?;
// entity::tmdb::seasons::ActiveModel {
// tmdb_show: Set(id),
// tmdb_season: Set(season.season_number),
// flix_show: Set(flix.id),
// flix_season: Set(season.season_number),
// last_update: Set(Utc::now()),
// }
// .insert(txn)
// .await?;
// }
// for (season, episodes) in episodes {
// for episode in episodes {
// entity::info::episodes::ActiveModel {
// show_id: Set(flix.id),
// season_number: Set(season),
// episode_number: Set(episode.episode_number),
// title: Set(episode.title),
// overview: Set(episode.overview),
// date: Set(episode.air_date),
// }
// .insert(txn)
// .await?;
// entity::tmdb::episodes::ActiveModel {
// tmdb_show: Set(id),
// tmdb_season: Set(season),
// tmdb_episode: Set(episode.episode_number),
// flix_show: Set(flix.id),
// flix_season: Set(season),
// flix_episode: Set(episode.episode_number),
// last_update: Set(Utc::now()),
// runtime: Set(episode.runtime.into()),
// }
// .insert(txn)
// .await?;
// }
// }
// Ok(flix.id)
// })
// })
// .await;
// let flix_id = match result {
// Ok(id) => id,
// Err(TransactionError::Connection(err)) => Err(err)?,
// Err(TransactionError::Transaction(err)) => Err(err)?,
// };
// println!(
// "Created Show: {} ({})",
// title,
// year,
// flix_id.into_raw()
// );
// Ok(())
// }
// Command::Season { id, season } => {
// let id = TmdbShowId::from_raw(id);
// let season_number = season;
// let Some(show) = entity::tmdb::shows::Entity::find_by_id(id).one(db).await? else {
// bail!("show does not exists");
// };
// let season = entity::tmdb::seasons::Entity::find_by_id((id, season))
// .one(db)
// .await?;
// if season.is_some() {
// bail!("season already exists");
// }
// let season = client
// .seasons()
// .get_details(id, season_number, None)
// .await
// .with_context(|| {
// format!(
// "seasons().get_details({}, {})",
// id.into_raw(),
// season_number
// )
// })?;
// let mut episodes = Vec::new();
// let Ok(number_of_episodes) = u32::try_from(season.episodes.len()) else {
// bail!(
// "could not convert {} to an EpisodeNumber",
// season.episodes.len()
// )
// };
// for episode in 1..=number_of_episodes {
// let episode = EpisodeNumber::new(episode);
// let Ok(episode) = client
// .episodes()
// .get_details(id, season.season_number, episode, None)
// .await
// else {
// eprintln!(
// "skipping episode ({}, {}, {})",
// id.into_raw(),
// season.season_number,
// episode
// );
// break;
// };
// episodes.push(episode);
// }
// let result: Result<(), TransactionError<DbErr>> = db
// .transaction(|txn| {
// Box::pin(async move {
// entity::info::seasons::ActiveModel {
// show_id: Set(show.flix_id),
// season_number: Set(season_number),
// title: Set(season.title),
// overview: Set(season.overview),
// date: Set(season.air_date),
// }
// .insert(txn)
// .await?;
// entity::tmdb::seasons::ActiveModel {
// tmdb_show: Set(show.tmdb_id),
// tmdb_season: Set(season_number),
// flix_show: Set(show.flix_id),
// flix_season: Set(season_number),
// last_update: Set(Utc::now()),
// }
// .insert(txn)
// .await?;
// for episode in episodes {
// entity::info::episodes::ActiveModel {
// show_id: Set(show.flix_id),
// season_number: Set(season_number),
// episode_number: Set(episode.episode_number),
// title: Set(episode.title),
// overview: Set(episode.overview),
// date: Set(episode.air_date),
// }
// .insert(txn)
// .await?;
// entity::tmdb::episodes::ActiveModel {
// tmdb_show: Set(show.tmdb_id),
// tmdb_season: Set(season_number),
// tmdb_episode: Set(episode.episode_number),
// flix_show: Set(show.flix_id),
// flix_season: Set(season_number),
// flix_episode: Set(episode.episode_number),
// last_update: Set(Utc::now()),
// runtime: Set(episode.runtime.into()),
// }
// .insert(txn)
// .await?;
// }
// Ok(())
// })
// })
// .await;
// match result {
// Ok(_) => (),
// Err(TransactionError::Connection(err)) => Err(err)?,
// Err(TransactionError::Transaction(err)) => Err(err)?,
// };
// println!(
// "Created Season: {} S{}",
// show.flix_id.into_raw(),
// season_number
// );
// Ok(())
// }
// Command::Episode {
// id,
// season,
// episode,
// episodes,
// } => {
// let id = TmdbShowId::from_raw(id);
// let season_number = season;
// let Some(show) = entity::tmdb::shows::Entity::find_by_id(id).one(db).await? else {
// bail!("show does not exists");
// };
// let Some(_) = entity::tmdb::seasons::Entity::find_by_id((id, season))
// .one(db)
// .await?
// else {
// bail!("season does not exists");
// };
// async fn fetch_episode(
// client: &Client,
// db: &DatabaseConnection,
// flix_id: ShowId,
// tmdb_id: TmdbShowId,
// id: TmdbShowId,
// season: SeasonNumber,
// episode: EpisodeNumber,
// ) -> Result<()> {
// let episode_number = episode;
// let episode = entity::tmdb::episodes::Entity::find_by_id((id, season, episode))
// .one(db)
// .await?;
// if episode.is_some() {
// bail!("episode already exists");
// }
// let episode = client
// .episodes()
// .get_details(id, season, episode_number, None)
// .await
// .with_context(|| {
// format!("episodes().get_details({}, {})", id.into_raw(), season)
// })?;
// let result: Result<(), TransactionError<DbErr>> = db
// .transaction(|txn| {
// Box::pin(async move {
// entity::info::episodes::ActiveModel {
// show_id: Set(flix_id),
// season_number: Set(season),
// episode_number: Set(episode_number),
// title: Set(episode.title),
// overview: Set(episode.overview),
// date: Set(episode.air_date),
// }
// .insert(txn)
// .await?;
// entity::tmdb::episodes::ActiveModel {
// tmdb_show: Set(tmdb_id),
// tmdb_season: Set(season),
// tmdb_episode: Set(episode_number),
// flix_show: Set(flix_id),
// flix_season: Set(season),
// flix_episode: Set(episode_number),
// last_update: Set(Utc::now()),
// runtime: Set(episode.runtime.into()),
// }
// .insert(txn)
// .await?;
// Ok(())
// })
// })
// .await;
// match result {
// Ok(_) => (),
// Err(TransactionError::Connection(err)) => Err(err)?,
// Err(TransactionError::Transaction(err)) => Err(err)?,
// };
// println!(
// "Created Episode: {} S{}E{}",
// flix_id.into_raw(),
// season,
// episode_number
// );
// Ok(())
// }
// let flix_id = show.flix_id;
// let tmdb_id = show.tmdb_id;
// fetch_episode(&client, db, flix_id, tmdb_id, id, season_number, episode).await?;
// for episode in episodes {
// fetch_episode(&client, db, flix_id, tmdb_id, id, season_number, episode).await?;
// }
// Ok(())
// }
// }
}