12 Commits

79 changed files with 10801 additions and 1307 deletions
-9
View File
@@ -1,9 +0,0 @@
{
"recommendations": [
"vadimcn.vscode-lldb",
"barbosshack.crates-io",
"usernamehw.errorlens",
"tamasfe.even-better-toml",
"rust-lang.rust-analyzer",
]
}
-33
View File
@@ -1,33 +0,0 @@
{
// VSCode
"editor.detectIndentation": false,
"editor.insertSpaces": false,
"editor.tabSize": 4,
"files.exclude": {
"**/target": true,
"**/Cargo.lock": true,
},
"files.insertFinalNewline": true,
"files.trimFinalNewlines": true,
"files.trimTrailingWhitespace": true,
"files.watcherExclude": {
"**/.git/**": true,
"**/target/**": true,
},
// Extensions
"crates.listPreReleases": true,
"evenBetterToml.formatter.alignComments": true,
"evenBetterToml.formatter.alignEntries": false,
"evenBetterToml.formatter.allowedBlankLines": 1,
"evenBetterToml.formatter.arrayAutoExpand": true,
"evenBetterToml.formatter.arrayTrailingComma": true,
"evenBetterToml.formatter.columnWidth": 80,
"evenBetterToml.formatter.reorderKeys": true,
"evenBetterToml.formatter.trailingNewline": true,
"rust-analyzer.imports.granularity.enforce": true,
"rust-analyzer.imports.granularity.group": "module",
"rust-analyzer.imports.group.enable": true,
"rust-analyzer.imports.merge.glob": false,
"rust-analyzer.imports.preferNoStd": true,
"rust-analyzer.showUnlinkedFileNotification": false,
}
+33
View File
@@ -0,0 +1,33 @@
{
"project_name": null,
"auto_install_extensions": {
"tombi": true,
"cargo-appraiser": true,
},
"languages": {
"TOML": {
"format_on_save": "on",
"formatter": { "language_server": { "name": "tombi" } },
},
},
"lsp": {
"rust-analyzer": {
"initialization_options": {
"imports": {
"granularity": { "enforce": true, "group": "module" },
"group": { "enable": true },
"merge": { "glob": false },
"preferNoStd": true,
},
"server": {
"extraEnv": {
"RUSTUP_TOOLCHAIN": "stable",
},
},
},
},
},
}
Generated
+2658 -381
View File
File diff suppressed because it is too large Load Diff
+42 -28
View File
@@ -1,17 +1,42 @@
[workspace] [workspace]
members = ["crates/*"]
resolver = "2" resolver = "2"
members = ["crates/*"]
[workspace.package] [workspace.package]
authors = []
edition = "2024" edition = "2024"
rust-version = "1.87.0"
license-file = "LICENSE.md" license-file = "LICENSE.md"
rust-version = "1.85.0"
[workspace.lints.rust] [workspace.dependencies]
arithmetic_overflow = "forbid" anyhow = { version = "^1", default-features = false }
missing_docs = "forbid" async-stream = { version = "^0.3", default-features = false }
unsafe_code = "forbid" chrono = { version = "^0.4", default-features = false }
clap = { version = "^4", default-features = false }
flix = { path = "crates/flix", version = "=0.0.16", default-features = false }
flix-cli = { path = "crates/cli", version = "=0.0.16", default-features = false }
flix-db = { path = "crates/db", version = "=0.0.16", default-features = false }
flix-fs = { path = "crates/fs", version = "=0.0.16", default-features = false }
flix-model = { path = "crates/model", version = "=0.0.16", default-features = false }
flix-tmdb = { path = "crates/tmdb", version = "=0.0.16", default-features = false }
futures = { version = "^0.3", default-features = false }
governor = { version = "^0.10", default-features = false }
itertools = { version = "^0.14", default-features = false }
nonzero_ext = { version = "^0.3", default-features = false }
regex = { version = "^1", default-features = false }
reqwest = { version = "^0.13", default-features = false }
sea-orm = { version = "2.0.0-rc.27", default-features = false }
sea-orm-migration = { version = "2.0.0-rc.27", default-features = false }
seamantic = { version = "^0.0.11", default-features = false }
serde = { version = "^1", default-features = false }
serde_test = { version = "^1", default-features = false }
thiserror = { version = "^2", default-features = false }
tokio = { version = "^1", default-features = false }
tokio-stream = { version = "^0.1", default-features = false }
toml = { version = "^0.9", default-features = false }
tracing = { version = "^0.1", default-features = false }
tracing-subscriber = { version = "^0.3", default-features = false }
url = { version = "^2", default-features = false }
url-macro = { version = "^0.2", default-features = false }
[workspace.lints.clippy] [workspace.lints.clippy]
arithmetic_side_effects = "forbid" arithmetic_side_effects = "forbid"
@@ -23,29 +48,18 @@ indexing_slicing = "forbid"
integer_division = "forbid" integer_division = "forbid"
integer_division_remainder_used = "forbid" integer_division_remainder_used = "forbid"
transmute_undefined_repr = "forbid" transmute_undefined_repr = "forbid"
unchecked_duration_subtraction = "forbid" unchecked_time_subtraction = "forbid"
unwrap_used = "forbid" unwrap_used = "forbid"
[workspace.lints.rust]
arithmetic_overflow = "forbid"
missing_docs = "forbid"
unsafe_code = "forbid"
unused_doc_comments = "forbid"
[profile.release] [profile.release]
codegen-units = 1
lto = "fat"
opt-level = 3 opt-level = 3
overflow-checks = true
strip = "debuginfo" strip = "debuginfo"
overflow-checks = true
[workspace.dependencies] lto = "fat"
flix = { path = "crates/flix", version = "=0.0.8", default-features = false } codegen-units = 1
flix-tmdb = { path = "crates/tmdb", version = "=0.0.8", default-features = false }
anyhow = { version = "^1", default-features = false }
chrono = { version = "^0.4", default-features = false }
clap = { version = "^4", default-features = false, features = ["std"] }
futures = { version = "^0.3", default-features = false }
home = { version = "^0.5", default-features = false }
reqwest = { version = "^0.12", default-features = false }
serde = { version = "^1", default-features = false }
thiserror = { version = "^2", default-features = false }
tokio = { version = "^1", default-features = false }
toml = { version = "^0.8", default-features = false }
url = { version = "^2", default-features = false }
url-macro = { version = "^0.2", default-features = false }
+4 -3
View File
@@ -6,9 +6,10 @@ Libraries and tools for dealing with media metadata
- build: `cargo hack --feature-powerset build` - build: `cargo hack --feature-powerset build`
- clippy: `cargo hack --feature-powerset clippy -- -D warnings` - clippy: `cargo hack --feature-powerset clippy -- -D warnings`
- test: `cargo hack --feature-powerset test`
- test old: `cargo +1.87 hack --feature-powerset test`
- fmt: `cargo fmt --check` - fmt: `cargo fmt --check`
- docs: `RUSTDOCFLAGS="--cfg docsrs" cargo +nightly doc --all-features` - docs: `RUSTDOCFLAGS="--cfg docsrs" cargo +nightly doc --all-features`
- install: `cargo install --path crates/cli` - install: `cargo install --path crates/cli`
- publish: `cargo publish --dry-run -p flix-tmdb` - semver: `cargo semver-checks --all-features`
- publish: `cargo publish --dry-run -p flix` - publish: `cargo publish --dry-run --workspace`
- publish: `cargo publish --dry-run -p flix-cli`
+33 -30
View File
@@ -1,24 +1,42 @@
[package] [package]
name = "flix-cli" name = "flix-cli"
version = "0.0.8" version = "0.0.16"
categories = ["command-line-utilities"]
description = "CLI for interacting with flix media"
repository = "https://github.com/QuantumShade/flix"
authors.workspace = true
edition.workspace = true edition.workspace = true
license-file.workspace = true
rust-version.workspace = true rust-version.workspace = true
description = "CLI for interacting with a flix database"
repository = "https://github.com/QuantumShade/flix"
license-file.workspace = true
categories = ["command-line-utilities"]
[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]
[[bin]] [[bin]]
doc = false doc = false
name = "flix" name = "flix"
path = "src/main.rs" path = "src/main.rs"
[lints.rust] [dependencies]
arithmetic_overflow = "forbid" anyhow = { workspace = true }
unsafe_code = "forbid" chrono = { workspace = true, features = ["now"] }
clap = { workspace = true, features = [
"color",
"derive",
"error-context",
"help",
"std",
"suggestions",
"usage",
] }
flix = { workspace = true, features = ["tmdb"] }
futures = { workspace = true }
sea-orm = { workspace = true, features = ["debug-print", "runtime-tokio"] }
serde = { workspace = true, features = ["derive"] }
tokio = { workspace = true, features = ["fs", "macros", "rt"] }
toml = { workspace = true, features = ["parse", "serde"] }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
[lints.clippy] [lints.clippy]
arithmetic_side_effects = "deny" arithmetic_side_effects = "deny"
@@ -30,24 +48,9 @@ indexing_slicing = "deny"
integer_division = "deny" integer_division = "deny"
integer_division_remainder_used = "deny" integer_division_remainder_used = "deny"
transmute_undefined_repr = "deny" transmute_undefined_repr = "deny"
unchecked_duration_subtraction = "deny" unchecked_time_subtraction = "deny"
unwrap_used = "deny" unwrap_used = "deny"
[dependencies] [lints.rust]
flix = { workspace = true, features = ["tmdb"] } arithmetic_overflow = "forbid"
flix-tmdb = { workspace = true } unsafe_code = "forbid"
anyhow = { workspace = true }
clap = { workspace = true, features = [
"derive",
"color",
"error-context",
"help",
"suggestions",
"usage",
] }
home = { workspace = true }
serde = { workspace = true, features = ["derive"] }
futures = { workspace = true }
tokio = { workspace = true, features = ["rt", "fs", "macros"] }
toml = { workspace = true, features = ["display", "parse"] }
+7 -1
View File
@@ -2,4 +2,10 @@
[![Crates Version](https://img.shields.io/crates/v/flix-cli.svg)](https://crates.io/crates/flix-cli) [![Crates Version](https://img.shields.io/crates/v/flix-cli.svg)](https://crates.io/crates/flix-cli)
CLI for interacting with flix media CLI for interacting with a flix database
## Commands
```sh
cargo run -- init
cargo run -- add tmdb movie <id>
```
+12
View File
@@ -0,0 +1,12 @@
use clap::Subcommand;
#[derive(Subcommand)]
pub enum AddCommand {
/// Process a flix collection
Collection {
#[arg(value_name = "TITLE")]
title: String,
#[arg(value_name = "OVERVIEW")]
overview: String,
},
}
+87 -23
View File
@@ -1,7 +1,9 @@
use std::path::PathBuf; use std::path::PathBuf;
use anyhow::{Result, anyhow};
use clap::{Parser, Subcommand}; use clap::{Parser, Subcommand};
pub mod flix;
pub mod tmdb; pub mod tmdb;
#[derive(Parser)] #[derive(Parser)]
@@ -11,18 +13,39 @@ pub struct Cli {
#[arg(short, long, value_name = "FILE", default_value = "~/.flix")] #[arg(short, long, value_name = "FILE", default_value = "~/.flix")]
config: PathBuf, config: PathBuf,
/// Use a custom database file
#[arg(short, long, value_name = "DATABASE", default_value = "./flix.db")]
database: PathBuf,
/// Enable tracing
#[arg(short, long)]
pub trace: bool,
#[command(subcommand)] #[command(subcommand)]
command: Command, command: Command,
} }
impl Cli { impl Cli {
pub fn config_path(&self) -> PathBuf { 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("~/") { match self.config.strip_prefix("~/") {
Ok(path) => expect_home_dir().join(path), Ok(path) => expect_home_dir().join(path),
Err(_) => self.config.to_owned(), Err(_) => self.config.to_owned(),
} }
} }
pub fn database_path(&self) -> Result<String> {
self.database
.as_os_str()
.to_str()
.map(ToOwned::to_owned)
.ok_or_else(|| anyhow!(".as_os_str().to_str()"))
}
pub fn command(self) -> Command { pub fn command(self) -> Command {
self.command self.command
} }
@@ -30,34 +53,44 @@ impl Cli {
#[derive(Subcommand)] #[derive(Subcommand)]
pub enum Command { pub enum Command {
/// Print a flix manifest /// Initialize a new database
Print { Init,
/// Add new items to the database
Add {
#[command(subcommand)] #[command(subcommand)]
command: BackendCommand, command: AddCommand,
}, },
/// Write a flix manifest if the destination does not exist /// Update an existing item in the database
Write {
/// Overwrite the destination
#[arg(short, long, default_value_t = false)]
force: bool,
/// Change the destination
#[arg(short, long, value_name = "FILE", default_value = "flix.toml")]
output: PathBuf,
#[command(subcommand)]
command: BackendCommand,
},
/// Update a flix manifest
Update { Update {
#[command(subcommand)]
command: UpdateCommand,
},
/// Delete an existing item in the database
Delete {
#[command(subcommand)]
command: DeleteCommand,
},
/// Create a toml backup of the database
Backup {
/// Change the destination /// Change the destination
#[arg(short, long, value_name = "FILE", default_value = "flix.toml")] #[arg(short, long, value_name = "FILE", default_value = "./flix.toml")]
output: PathBuf, output: PathBuf,
}, },
/// Create a database from a toml backup
Restore {
/// Change the source
#[arg(short, long, value_name = "FILE", default_value = "./flix.toml")]
input: PathBuf,
},
} }
#[derive(Subcommand)] #[derive(Subcommand)]
pub enum BackendCommand { pub enum AddCommand {
/// Use the flix backend
Flix {
#[command(subcommand)]
command: flix::AddCommand,
},
/// Use the TMDB backend /// Use the TMDB backend
Tmdb { Tmdb {
#[command(subcommand)] #[command(subcommand)]
@@ -65,13 +98,44 @@ pub enum BackendCommand {
}, },
} }
impl From<tmdb::Command> for BackendCommand { impl From<flix::AddCommand> for AddCommand {
fn from(value: flix::AddCommand) -> Self {
Self::Flix { command: value }
}
}
impl From<tmdb::Command> for AddCommand {
fn from(value: tmdb::Command) -> Self { fn from(value: tmdb::Command) -> Self {
Self::Tmdb { command: value } Self::Tmdb { command: value }
} }
} }
fn expect_home_dir() -> PathBuf { #[derive(Subcommand)]
#[allow(clippy::expect_used)] pub enum UpdateCommand {
home::home_dir().expect("you do not have a home directory") /// Use the TMDB backend
Tmdb {
#[command(subcommand)]
command: tmdb::Command,
},
}
impl From<tmdb::Command> for UpdateCommand {
fn from(value: tmdb::Command) -> Self {
Self::Tmdb { command: value }
}
}
#[derive(Subcommand)]
pub enum DeleteCommand {
/// Use the TMDB backend
Tmdb {
#[command(subcommand)]
command: tmdb::Command,
},
}
impl From<tmdb::Command> for DeleteCommand {
fn from(value: tmdb::Command) -> Self {
Self::Tmdb { command: value }
}
} }
+12 -9
View File
@@ -1,3 +1,6 @@
use flix::model::numbers::{EpisodeNumber, SeasonNumber};
use flix::tmdb::model::id::RawId;
use clap::Subcommand; use clap::Subcommand;
#[derive(Subcommand)] #[derive(Subcommand)]
@@ -5,35 +8,35 @@ pub enum Command {
/// Process a TMDB collection /// Process a TMDB collection
Collection { Collection {
#[arg(value_name = "TMDB_ID")] #[arg(value_name = "TMDB_ID")]
id: u32, id: RawId,
}, },
/// Process a TMDB movie /// Process a TMDB movie
Movie { Movie {
#[arg(value_name = "TMDB_ID")] #[arg(value_name = "TMDB_ID")]
id: u32, id: RawId,
}, },
/// Process a TMDB show /// Process a TMDB show
Show { Show {
#[arg(value_name = "TMDB_ID")] #[arg(value_name = "TMDB_ID")]
id: u32, id: RawId,
}, },
/// Process a TMDB season /// Process a TMDB season
Season { Season {
#[arg(value_name = "TMDB_ID")] #[arg(value_name = "TMDB_ID")]
id: u32, id: RawId,
#[arg(value_name = "SEASON_NUM")] #[arg(value_name = "SEASON_NUM")]
season: u32, season: SeasonNumber,
}, },
/// Process a TMDB episode /// Process a TMDB episode
#[command(trailing_var_arg = true)] #[command(trailing_var_arg = true)]
Episode { Episode {
#[arg(value_name = "TMDB_ID")] #[arg(value_name = "TMDB_ID")]
id: u32, id: RawId,
#[arg(value_name = "SEASON_NUM")] #[arg(value_name = "SEASON_NUM")]
season: u32, season: SeasonNumber,
#[arg(value_name = "EPISODE_NUM")] #[arg(value_name = "EPISODE_NUM")]
episode: u32, episode: EpisodeNumber,
#[arg(value_name = "...")] #[arg(value_name = "...")]
episodes: Vec<u32>, episodes: Vec<EpisodeNumber>,
}, },
} }
+27
View File
@@ -0,0 +1,27 @@
use flix::db::connection::Connection;
use anyhow::{Context, Result, bail};
use sea_orm::{ConnectOptions, Database};
use tokio::fs;
async fn connect(string: String) -> Result<Connection> {
Connection::try_from(
Database::connect(ConnectOptions::new(string))
.await
.context("Database::connect")?,
)
.await
.context("Connection::try_from")
}
pub async fn open(database_path: String) -> Result<Connection> {
connect(format!("sqlite:{database_path}?mode=rw")).await
}
pub async fn open_new(database_path: String) -> Result<Connection> {
if fs::try_exists(&database_path).await? {
bail!("database already exists");
}
connect(format!("sqlite:{database_path}?mode=rwc")).await
}
+58 -49
View File
@@ -1,20 +1,19 @@
use std::path::Path; use std::path::PathBuf;
use flix_tmdb::Client; use flix::tmdb::Client;
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use clap::Parser; use clap::Parser;
use tokio::fs; use tokio::fs;
use tokio::io::AsyncWriteExt;
mod cli; mod cli;
use cli::{BackendCommand, Cli, Command}; use cli::{AddCommand, Cli, Command, DeleteCommand, UpdateCommand};
mod config; mod config;
use config::Config; use config::Config;
mod db;
mod run; mod run;
use run::flix::FlixObject;
#[tokio::main(flavor = "current_thread")] #[tokio::main(flavor = "current_thread")]
async fn main() -> Result<()> { async fn main() -> Result<()> {
@@ -25,67 +24,77 @@ async fn main() -> Result<()> {
let config: Config = toml::from_str(config.as_str()) 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()))?;
let database_path = cli.database_path()?;
let client = Client::new(config.tmdb().bearer_token().to_owned()); let client = Client::new(config.tmdb().bearer_token().to_owned());
if cli.trace {
tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.with_test_writer()
.init();
}
match cli.command() { match cli.command() {
Command::Print { command } => exec_print(client, command).await?, Command::Init => exec_init(database_path).await?,
Command::Write { Command::Add { command } => exec_add(client, database_path, command).await?,
force, Command::Update { command } => exec_update(client, database_path, command).await?,
output, Command::Delete { command } => exec_delete(client, database_path, command).await?,
command, Command::Backup { output } => exec_backup(database_path, output).await?,
} => exec_write(client, force, &output, command).await?, Command::Restore { input } => exec_restore(database_path, input).await?,
Command::Update { output } => exec_update(client, &output).await?,
} }
Ok(()) Ok(())
} }
async fn exec_print(client: Client, command: BackendCommand) -> Result<()> { async fn exec_init(database_path: String) -> Result<()> {
db::open_new(database_path).await?;
Ok(())
}
async fn exec_add(client: Client, database_path: String, command: AddCommand) -> Result<()> {
let database = db::open(database_path).await?;
match command { match command {
BackendCommand::Tmdb { command } => { AddCommand::Flix { command } => {
let object = run::tmdb::TmdbObject::fetch(&client, command).await?; run::flix::add(database.as_ref(), command).await?;
println!("{}", object.serialize().context("failed to serialize")?) }
AddCommand::Tmdb { command } => {
run::tmdb::add(client, database.as_ref(), command).await?;
} }
} }
Ok(()) Ok(())
} }
async fn exec_write( async fn exec_update(client: Client, database_path: String, command: UpdateCommand) -> Result<()> {
client: Client, let database = db::open(database_path).await?;
force: bool,
output: &Path,
command: BackendCommand,
) -> Result<()> {
match command { match command {
BackendCommand::Tmdb { command } => { UpdateCommand::Tmdb { command } => {
let object = run::tmdb::TmdbObject::fetch(&client, command).await?; run::tmdb::update(client, database.as_ref(), command).await?;
}
}
let mut file = if force {
fs::File::create(output).await
} else {
fs::File::create_new(output).await
}
.with_context(|| format!("could not create file at path {}", output.display()))?;
file.write_all(
object
.serialize()
.context("failed to serialize tmdb object")?
.as_bytes(),
)
.await
.with_context(|| format!("could not write to file at path {}", output.display()))?;
}
}
Ok(()) Ok(())
} }
async fn exec_update(client: Client, output: &Path) -> Result<()> { async fn exec_delete(client: Client, database_path: String, command: DeleteCommand) -> Result<()> {
let content = fs::read_to_string(output) _ = client;
.await _ = database_path;
.with_context(|| format!("failed to read file at path: {}", output.display()))?; _ = command;
let object: FlixObject = toml::from_str(&content) unimplemented!()
.with_context(|| format!("failed to deserialize flix file: {}", output.display()))?; }
let command = object.backend_command()?; async fn exec_backup(database_path: String, output: PathBuf) -> Result<()> {
exec_write(client, true, output, command).await _ = database_path;
_ = output;
unimplemented!()
}
async fn exec_restore(database_path: String, input: PathBuf) -> Result<()> {
_ = database_path;
_ = input;
unimplemented!()
} }
+41 -67
View File
@@ -1,75 +1,49 @@
use flix::model::{Collection, Episode, Movie, Season, Show, Verse}; use flix::db::entity;
use flix::model::id::CollectionId;
use flix::model::text;
use anyhow::{Result, anyhow, bail}; use anyhow::Result;
use sea_orm::ActiveValue::{NotSet, Set};
use sea_orm::{ActiveModelTrait, DatabaseConnection, DbErr, TransactionError, TransactionTrait};
use crate::cli::BackendCommand; use crate::cli::flix::AddCommand;
use crate::cli::tmdb;
#[derive(Debug, serde::Deserialize)] pub async fn add(db: &DatabaseConnection, command: AddCommand) -> Result<()> {
#[serde(untagged)] match command {
pub enum FlixObject { AddCommand::Collection { title, overview } => {
Collection(Collection), let result: Result<CollectionId, TransactionError<DbErr>> = db
Movie(Movie), .transaction(|txn| {
Show(Show), let title = title.clone();
Season(Season),
Episode(Episode),
// DEAD CODE: The TMDB backend does not support Verses
#[allow(dead_code)]
Verse(Verse),
}
impl FlixObject { let sort_title = text::make_sortable_title(&title);
pub fn backend_command(&self) -> Result<BackendCommand> { let fs_slug = text::make_fs_slug(&title);
Ok(match self { let web_slug = text::make_web_slug(&title);
FlixObject::Collection(collection) => {
let Some(ref tmdb) = collection.tmdb else { Box::pin(async move {
bail!("missing tmdb data") let flix = entity::info::collections::ActiveModel {
}; id: NotSet,
tmdb::Command::Collection { id: tmdb.id.into() }.into() title: Set(title),
} overview: Set(overview),
FlixObject::Movie(movie) => { sort_title: Set(sort_title),
let Some(ref tmdb) = movie.tmdb else { fs_slug: Set(fs_slug),
bail!("missing tmdb data") web_slug: Set(web_slug),
};
tmdb::Command::Movie { id: tmdb.id.into() }.into()
}
FlixObject::Show(show) => {
let Some(ref tmdb) = show.tmdb else {
bail!("missing tmdb data")
};
tmdb::Command::Show { id: tmdb.id.into() }.into()
}
FlixObject::Season(season) => {
let Some(ref tmdb) = season.tmdb else {
bail!("missing tmdb data")
};
tmdb::Command::Season {
id: tmdb.show_id.into(),
season: season.season.number,
}
.into()
}
FlixObject::Episode(episode) => {
let Some(ref tmdb) = episode.tmdb else {
bail!("missing tmdb data")
};
tmdb::Command::Episode {
id: tmdb.show_id.into(),
season: episode.episode.season,
episode: episode
.episode
.number
.primary_episode_number()
.ok_or_else(|| {
anyhow!("the episode does not have a primary episode number")
})?,
episodes: episode.episode.number.additional_episode_numbers(),
}
.into()
}
FlixObject::Verse(_) => {
bail!("verses are not handled")
} }
.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(())
}
} }
} }
+518 -126
View File
@@ -1,157 +1,549 @@
use flix::model::{ use std::collections::HashMap;
Collection, Episode, EpisodeNumber, GenericCollection, GenericEpisode, GenericMovie,
GenericSeason, GenericShow, Movie, Season, Show, TmdbCollection, TmdbEpisode, TmdbMovie, use flix::db::entity;
TmdbSeason, TmdbShow, use flix::model::id::{CollectionId, MovieId, ShowId};
}; use flix::model::numbers::{EpisodeNumber, SeasonNumber};
use flix_tmdb::Client; use flix::model::text;
use flix_tmdb::model::{ use flix::tmdb::Client;
Collection as TCollection, Episode as TEpisode, Movie as TMovie, Season as TSeason, use flix::tmdb::model::id::{
Show as TShow, ShowId, CollectionId as TmdbCollectionId, MovieId as TmdbMovieId, ShowId as TmdbShowId,
}; };
use anyhow::{Context, Result}; use anyhow::{Context, Result, bail};
use futures::{StreamExt, TryStreamExt, stream}; use chrono::{Datelike, Utc};
use sea_orm::ActiveValue::{NotSet, Set};
use sea_orm::{
ActiveModelTrait, DatabaseConnection, DbErr, EntityTrait, TransactionError, TransactionTrait,
};
use crate::cli::tmdb::Command; use crate::cli::tmdb::Command;
pub enum TmdbObject { pub async fn add(client: Client, db: &DatabaseConnection, command: Command) -> Result<()> {
Collection(TCollection), match command {
Movie(TMovie), Command::Collection { id } => {
Show(TShow), let id = TmdbCollectionId::from_raw(id);
Season(TSeason, ShowId),
Episode(TEpisode, Vec<u32>, u32, ShowId),
}
impl TmdbObject { let collection = entity::tmdb::collections::Entity::find_by_id(id)
pub fn serialize(self) -> Result<String> { .one(db)
Ok(match self { .await?;
TmdbObject::Collection(tmdb) => toml::to_string(&Collection { if collection.is_some() {
collection: GenericCollection { bail!("collection already exists");
title: tmdb.title,
overview: tmdb.overview,
},
tmdb: Some(TmdbCollection { id: tmdb.id }),
})?,
TmdbObject::Movie(tmdb) => toml::to_string(&Movie {
movie: GenericMovie {
title: tmdb.title,
overview: tmdb.overview,
genres: tmdb.genres.iter().cloned().map(|g| g.name).collect(),
release_date: tmdb.release_date,
},
tmdb: Some(TmdbMovie {
id: tmdb.id,
genres: tmdb.genres.iter().map(|g| g.id).collect(),
}),
})?,
TmdbObject::Show(tmdb) => toml::to_string(&Show {
show: GenericShow {
title: tmdb.title,
overview: tmdb.overview,
genres: tmdb.genres.iter().cloned().map(|g| g.name).collect(),
air_date: tmdb.first_air_date,
},
tmdb: Some(TmdbShow {
id: tmdb.id,
genres: tmdb.genres.iter().map(|g| g.id).collect(),
}),
})?,
TmdbObject::Season(tmdb, show_id) => toml::to_string(&Season {
season: GenericSeason {
number: tmdb.season_number,
title: tmdb.title,
overview: tmdb.overview,
air_date: tmdb.air_date,
},
tmdb: Some(TmdbSeason { show_id }),
})?,
TmdbObject::Episode(tmdb, mut episode_numbers, season_number, show_id) => {
toml::to_string(&Episode {
episode: GenericEpisode {
number: if episode_numbers.is_empty() {
EpisodeNumber::Single {
number: tmdb.episode_number,
} }
} else {
episode_numbers.insert(0, tmdb.episode_number);
EpisodeNumber::Multiple {
numbers: episode_numbers,
}
},
season: season_number,
title: tmdb.title,
overview: tmdb.overview,
air_date: tmdb.air_date,
},
tmdb: Some(TmdbEpisode { show_id }),
})?
}
})
}
}
impl TmdbObject { let collection = client
pub async fn fetch(client: &Client, command: Command) -> Result<Self> {
Ok(match command {
Command::Collection { id } => Self::Collection(
client
.collections() .collections()
.get_details(id, None) .get_details(id, None)
.await .await
.with_context(|| format!("could not get collection details for '{id}'"))?, .with_context(|| format!("collections().get_details({})", id.into_raw()))?;
),
Command::Movie { id } => Self::Movie( let title = collection.title.clone();
client
let sort_title = text::make_sortable_title(&title);
let fs_slug = text::make_fs_slug(&title);
let web_slug = text::make_web_slug(&title);
let result: Result<CollectionId, TransactionError<DbErr>> = db
.transaction(|txn| {
Box::pin(async move {
let flix = entity::info::collections::ActiveModel {
id: NotSet,
title: Set(collection.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() .movies()
.get_details(id, None) .get_details(id, None)
.await .await
.with_context(|| format!("could not get movie details for '{id}'"))?, .with_context(|| format!("movies().get_details({})", id.into_raw()))?;
),
Command::Show { id } => Self::Show( let title = movie.title.clone();
client let year = movie.release_date.year();
let sort_title = text::make_sortable_title(&title);
let fs_slug = text::make_fs_slug_year(&title, year);
let web_slug = text::make_web_slug_year(&title, year);
let result: Result<MovieId, TransactionError<DbErr>> = db
.transaction(|txn| {
Box::pin(async move {
let flix = entity::info::movies::ActiveModel {
id: NotSet,
title: Set(movie.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() .shows()
.get_details(id, None) .get_details(id, None)
.await .await
.with_context(|| format!("could not get show details for '{id}'"))?, .with_context(|| format!("shows().get_details({})", id.into_raw()))?;
), let mut seasons = Vec::new();
Command::Season { id, season } => Self::Season( let mut episodes = HashMap::new();
client
let title = show.title.clone();
let year = show.first_air_date.year();
for season in 1..=show.number_of_seasons {
let season = SeasonNumber::new(season);
let season = match client
.seasons() .seasons()
.get_details(id, season, None) .get_details(id, season, None)
.await .await
.with_context(|| format!("could not get show details for '{id}' S{season}"))?, .with_context(|| {
id.into(), 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 sort_title = text::make_sortable_title(&show.title);
let fs_slug = text::make_fs_slug_year(&show.title, show.first_air_date.year());
let web_slug = text::make_web_slug_year(&show.title, show.first_air_date.year());
let result: Result<ShowId, TransactionError<DbErr>> = db
.transaction(|txn| {
Box::pin(async move {
let flix = entity::info::shows::ActiveModel {
id: NotSet,
title: Set(show.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 { Command::Episode {
id, id,
season, season,
episode, episode,
episodes, episodes,
} => { } => {
let mut episode = client let id = TmdbShowId::from_raw(id);
.episodes() let season_number = season;
.get_details(id, season, episode, None)
.await let Some(show) = entity::tmdb::shows::Entity::find_by_id(id).one(db).await? else {
.with_context(|| { bail!("show does not exists");
format!("could not get show details for '{id}' S{season}E{episode}") };
})?; let Some(_) = entity::tmdb::seasons::Entity::find_by_id((id, season))
let title = stream::once(async { Ok(episode.title) }) .one(db)
.chain(stream::iter(episodes.clone()).then(|episode| async move {
client
.episodes()
.get_details(id, season, episode, None)
.await
.with_context(|| {
format!("could not get show details for '{id}' S{season}E{episode}")
})
.map(|episode| episode.title)
}))
.try_collect::<Vec<_>>()
.await? .await?
.join(" + "); else {
episode.title = title; bail!("season does not exists");
Self::Episode(episode, episodes, season, id.into()) };
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(())
}
} }
} }
pub async fn update(client: Client, database: &DatabaseConnection, command: Command) -> Result<()> {
_ = client;
_ = database;
_ = command;
unimplemented!("updates")
}
+39
View File
@@ -0,0 +1,39 @@
[package]
name = "flix-db"
version = "0.0.16"
edition.workspace = true
rust-version.workspace = true
description = "Types for storing persistent data about media"
repository = "https://github.com/QuantumShade/flix"
license-file.workspace = true
categories = []
[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]
[dependencies]
chrono = { workspace = true }
flix-model = { workspace = true }
flix-tmdb = { workspace = true, features = ["sea-orm"], optional = true }
sea-orm = { workspace = true, features = [
"entity-registry",
"schema-sync",
"with-chrono",
] }
sea-orm-migration = { workspace = true }
seamantic = { workspace = true, features = ["sqlite"] }
[dev-dependencies]
sea-orm-migration = { workspace = true, features = ["runtime-tokio-rustls"] }
tokio = { version = "^1", default-features = false, features = [
"macros",
"rt",
] }
[features]
default = []
tmdb = ["dep:flix-tmdb"]
[lints]
workspace = true
+5
View File
@@ -0,0 +1,5 @@
# flix-db
[![Crates Version](https://img.shields.io/crates/v/flix-db.svg)](https://crates.io/crates/flix-db)
A library providing types for storing persistent data about media
+32
View File
@@ -0,0 +1,32 @@
//! Types and functions related to [DatabaseConnection]s
use sea_orm::{DatabaseConnection, DbErr};
use sea_orm_migration::MigratorTrait as _;
/// A newtype wrapping a [DatabaseConnection]
pub struct Connection(DatabaseConnection);
impl Connection {
/// Helper function for applying database migrations while wrapping a
/// [DatabaseConnection] in a newtype
pub async fn try_from(db: DatabaseConnection) -> Result<Self, DbErr> {
crate::migration::Migrator::down(&db, None).await?;
db.get_schema_registry("flix_db::*").sync(&db).await?;
db.get_schema_registry("flix_db::*").sync(&db).await?;
crate::migration::Migrator::up(&db, None).await?;
Ok(Self(db))
}
}
impl AsRef<DatabaseConnection> for Connection {
fn as_ref(&self) -> &DatabaseConnection {
&self.0
}
}
#[cfg(test)]
impl Connection {
pub(crate) fn take(self) -> DatabaseConnection {
self.0
}
}
+882
View File
@@ -0,0 +1,882 @@
//! This module contains entities for storing media file information
/// Library entity
pub mod libraries {
use flix_model::id::LibraryId;
use seamantic::model::path::PathBytes;
use chrono::{DateTime, Utc};
use sea_orm::entity::prelude::*;
/// The database representation of a library media folder
#[sea_orm::model]
#[derive(Debug, Clone, DeriveEntityModel)]
#[sea_orm(table_name = "flix_libraries")]
pub struct Model {
/// The library's ID
#[sea_orm(primary_key, auto_increment = false)]
pub id: LibraryId,
/// The library's directory
pub directory: PathBytes,
/// The library's last scan data
pub last_scan: Option<DateTime<Utc>>,
/// Collections that are part of this library
#[sea_orm(has_many)]
pub collections: HasMany<super::collections::Entity>,
/// Movies that are part of this library
#[sea_orm(has_many)]
pub movies: HasMany<super::movies::Entity>,
/// Shows that are part of this library
#[sea_orm(has_many)]
pub shows: HasMany<super::shows::Entity>,
/// Seasons that are part of this library
#[sea_orm(has_many)]
pub seasons: HasMany<super::seasons::Entity>,
/// Episodes that are part of this library
#[sea_orm(has_many)]
pub episodes: HasMany<super::episodes::Entity>,
}
impl ActiveModelBehavior for ActiveModel {}
}
/// Collection entity
pub mod collections {
use flix_model::id::{CollectionId, LibraryId};
use seamantic::model::path::PathBytes;
use sea_orm::entity::prelude::*;
use crate::entity;
/// The database representation of a collection media folder
#[sea_orm::model]
#[derive(Debug, Clone, DeriveEntityModel)]
#[sea_orm(table_name = "flix_collections")]
pub struct Model {
/// The collection's ID
#[sea_orm(primary_key, auto_increment = false)]
pub id: CollectionId,
/// The collection's parent
#[sea_orm(indexed)]
pub parent_id: Option<CollectionId>,
/// The collection's library ID
pub library_id: LibraryId,
/// The collection's directory
pub directory: PathBytes,
/// The collection's poster path
pub relative_poster_path: Option<String>,
/// This collection's parent
#[sea_orm(
self_ref,
relation_enum = "Parent",
from = "parent_id",
to = "id",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub parent: HasOne<Entity>,
/// The library this collection belongs to
#[sea_orm(
belongs_to,
from = "library_id",
to = "id",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub library: HasOne<super::libraries::Entity>,
/// The info for this collection
#[sea_orm(
belongs_to,
relation_enum = "Info",
from = "id",
to = "id",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub info: HasOne<entity::info::collections::Entity>,
/// The watched info for this collection
#[sea_orm(has_many, relation_enum = "Watched", from = "id", to = "id")]
pub watched: HasMany<entity::watched::collections::Entity>,
}
impl ActiveModelBehavior for ActiveModel {}
}
/// Movie entity
pub mod movies {
use flix_model::id::{CollectionId, LibraryId, MovieId};
use seamantic::model::path::PathBytes;
use sea_orm::entity::prelude::*;
use crate::entity;
/// The database representation of a movie media folder
#[sea_orm::model]
#[derive(Debug, Clone, DeriveEntityModel)]
#[sea_orm(table_name = "flix_movies")]
pub struct Model {
/// The movie's ID
#[sea_orm(primary_key, auto_increment = false)]
pub id: MovieId,
/// The movie's parent
#[sea_orm(indexed)]
pub parent_id: Option<CollectionId>,
/// The movie's library
pub library_id: LibraryId,
/// The movie's directory
pub directory: PathBytes,
/// The movie's media path
pub relative_media_path: String,
/// The movie's poster path
pub relative_poster_path: Option<String>,
/// This movie's parent
#[sea_orm(
belongs_to,
from = "parent_id",
to = "id",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub parent: HasOne<super::collections::Entity>,
/// The library this movie belongs to
#[sea_orm(
belongs_to,
from = "library_id",
to = "id",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub library: HasOne<super::libraries::Entity>,
/// The info for this movie
#[sea_orm(
belongs_to,
relation_enum = "Info",
from = "id",
to = "id",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub info: HasOne<entity::info::movies::Entity>,
/// The watched info for this movie
#[sea_orm(has_many, relation_enum = "Watched", from = "id", to = "id")]
pub watched: HasMany<entity::watched::movies::Entity>,
}
impl ActiveModelBehavior for ActiveModel {}
}
/// Show entity
pub mod shows {
use flix_model::id::{CollectionId, LibraryId, ShowId};
use seamantic::model::path::PathBytes;
use sea_orm::entity::prelude::*;
use crate::entity;
/// The database representation of a show media folder
#[sea_orm::model]
#[derive(Debug, Clone, DeriveEntityModel)]
#[sea_orm(table_name = "flix_shows")]
pub struct Model {
/// The show's ID
#[sea_orm(primary_key, auto_increment = false)]
pub id: ShowId,
/// The show's parent
#[sea_orm(indexed)]
pub parent_id: Option<CollectionId>,
/// The show's library
pub library_id: LibraryId,
/// The show's directory
pub directory: PathBytes,
/// The show's poster path
pub relative_poster_path: Option<String>,
/// This show's parent
#[sea_orm(
belongs_to,
from = "parent_id",
to = "id",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub parent: HasOne<super::collections::Entity>,
/// The library this show belongs to
#[sea_orm(
belongs_to,
from = "library_id",
to = "id",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub library: HasOne<super::libraries::Entity>,
/// The info for this show
#[sea_orm(
belongs_to,
relation_enum = "Info",
from = "id",
to = "id",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub info: HasOne<entity::info::shows::Entity>,
/// Seasons that are part of this show
#[sea_orm(has_many)]
pub seasons: HasMany<super::seasons::Entity>,
/// Episodes that are part of this show
#[sea_orm(has_many)]
pub episodes: HasMany<super::episodes::Entity>,
/// The watched info for this show
#[sea_orm(has_many, relation_enum = "Watched", from = "id", to = "id")]
pub watched: HasMany<entity::watched::shows::Entity>,
}
impl ActiveModelBehavior for ActiveModel {}
}
/// Season entity
pub mod seasons {
use flix_model::id::{LibraryId, ShowId};
use flix_model::numbers::SeasonNumber;
use seamantic::model::path::PathBytes;
use sea_orm::entity::prelude::*;
use crate::entity;
/// The database representation of a season media folder
#[sea_orm::model]
#[derive(Debug, Clone, DeriveEntityModel)]
#[sea_orm(table_name = "flix_seasons")]
pub struct Model {
/// The season's show's ID
#[sea_orm(primary_key, auto_increment = false)]
pub show_id: ShowId,
/// The season's number
#[sea_orm(primary_key, auto_increment = false)]
pub season_number: SeasonNumber,
/// The season's library
pub library_id: LibraryId,
/// The season's directory
pub directory: PathBytes,
/// The season's poster path
pub relative_poster_path: Option<String>,
/// This season's show
#[sea_orm(
belongs_to,
from = "show_id",
to = "id",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub show: HasOne<super::shows::Entity>,
/// The library this season belongs to
#[sea_orm(
belongs_to,
from = "library_id",
to = "id",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub library: HasOne<super::libraries::Entity>,
/// The info for this season
#[sea_orm(
belongs_to,
relation_enum = "Info",
from = "(show_id, season_number)",
to = "(show_id, season_number)",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub info: HasOne<entity::info::seasons::Entity>,
/// Episodes that are part of this show
#[sea_orm(has_many)]
pub episodes: HasMany<super::episodes::Entity>,
/// The watched info for this season
#[sea_orm(
has_many,
relation_enum = "Watched",
from = "(show_id, season_number)",
to = "(show_id, season_number)"
)]
pub watched: HasMany<entity::watched::seasons::Entity>,
}
impl ActiveModelBehavior for ActiveModel {}
}
/// Episode entity
pub mod episodes {
use flix_model::id::{LibraryId, ShowId};
use flix_model::numbers::{EpisodeNumber, SeasonNumber};
use seamantic::model::path::PathBytes;
use sea_orm::entity::prelude::*;
use crate::entity;
/// The database representation of a episode media folder
#[sea_orm::model]
#[derive(Debug, Clone, DeriveEntityModel)]
#[sea_orm(table_name = "flix_episodes")]
pub struct Model {
/// The episode's show's ID
#[sea_orm(primary_key, auto_increment = false)]
pub show_id: ShowId,
/// The episode's season's number
#[sea_orm(primary_key, auto_increment = false)]
pub season_number: SeasonNumber,
/// The episode's number
#[sea_orm(primary_key, auto_increment = false)]
pub episode_number: EpisodeNumber,
/// The number of additional contained episodes
pub count: u8,
/// The episode's library
pub library_id: LibraryId,
/// The episode's directory
pub directory: PathBytes,
/// The episode's media path
pub relative_media_path: String,
/// The episode's poster path
pub relative_poster_path: Option<String>,
/// This episode's show
#[sea_orm(
belongs_to,
from = "show_id",
to = "id",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub show: HasOne<super::shows::Entity>,
/// This episode's season
#[sea_orm(
belongs_to,
from = "(show_id, season_number)",
to = "(show_id, season_number)",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub season: HasOne<super::seasons::Entity>,
/// The library this episode belongs to
#[sea_orm(
belongs_to,
from = "library_id",
to = "id",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub library: HasOne<super::libraries::Entity>,
/// The info for this episode
#[sea_orm(
belongs_to,
relation_enum = "Info",
from = "(show_id, season_number, episode_number)",
to = "(show_id, season_number, episode_number)",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub info: HasOne<entity::info::episodes::Entity>,
/// The watched info for this episode
#[sea_orm(
has_many,
relation_enum = "Watched",
from = "(show_id, season_number, episode_number)",
to = "(show_id, season_number, episode_number)"
)]
pub watched: HasMany<entity::watched::episodes::Entity>,
}
impl ActiveModelBehavior for ActiveModel {}
}
/// Macros for creating content entities
#[cfg(test)]
pub mod test {
macro_rules! make_content_library {
($db:expr, $id:expr) => {
$crate::entity::content::libraries::ActiveModel {
id: Set(::flix_model::id::LibraryId::from_raw($id)),
directory: Set(::std::path::PathBuf::new().into()),
last_scan: Set(None),
}
.insert($db)
.await
.expect("insert");
};
}
pub(crate) use make_content_library;
macro_rules! make_content_collection {
($db:expr, $lid:expr, $id:expr, $pid:expr) => {
$crate::entity::info::test::make_info_collection!($db, $id);
$crate::entity::content::collections::ActiveModel {
id: Set(::flix_model::id::CollectionId::from_raw($id)),
parent_id: Set($pid.map(::flix_model::id::CollectionId::from_raw)),
library_id: Set(::flix_model::id::LibraryId::from_raw($lid)),
directory: Set(::std::path::PathBuf::new().into()),
relative_poster_path: Set(::core::option::Option::None),
}
.insert($db)
.await
.expect("insert");
};
}
pub(crate) use make_content_collection;
macro_rules! make_content_movie {
($db:expr, $lid:expr, $id:expr, $pid:expr) => {
$crate::entity::info::test::make_info_movie!($db, $id);
$crate::entity::content::movies::ActiveModel {
id: Set(::flix_model::id::MovieId::from_raw($id)),
parent_id: Set($pid.map(::flix_model::id::CollectionId::from_raw)),
library_id: Set(::flix_model::id::LibraryId::from_raw($lid)),
directory: Set(::std::path::PathBuf::new().into()),
relative_media_path: Set(::std::string::String::new()),
relative_poster_path: Set(::core::option::Option::None),
}
.insert($db)
.await
.expect("insert");
};
}
pub(crate) use make_content_movie;
macro_rules! make_content_show {
($db:expr, $lid:expr, $id:expr, $pid:expr) => {
$crate::entity::info::test::make_info_show!($db, $id);
$crate::entity::content::shows::ActiveModel {
id: Set(::flix_model::id::ShowId::from_raw($id)),
parent_id: Set($pid.map(::flix_model::id::CollectionId::from_raw)),
library_id: Set(::flix_model::id::LibraryId::from_raw($lid)),
directory: Set(::std::path::PathBuf::new().into()),
relative_poster_path: Set(::core::option::Option::None),
}
.insert($db)
.await
.expect("insert");
};
}
pub(crate) use make_content_show;
macro_rules! make_content_season {
($db:expr, $lid:expr, $show:expr, $season:expr) => {
$crate::entity::info::test::make_info_season!($db, $show, $season);
$crate::entity::content::seasons::ActiveModel {
show_id: Set(::flix_model::id::ShowId::from_raw($show)),
season_number: Set(::flix_model::numbers::SeasonNumber::new($season)),
library_id: Set(::flix_model::id::LibraryId::from_raw($lid)),
directory: Set(::std::path::PathBuf::new().into()),
relative_poster_path: Set(::core::option::Option::None),
}
.insert($db)
.await
.expect("insert");
};
}
pub(crate) use make_content_season;
macro_rules! make_content_episode {
($db:expr, $lid:expr, $show:expr, $season:expr, $episode:expr) => {
make_content_episode!(@make, $db, $lid, $show, $season, $episode, 0);
};
($db:expr, $lid:literal, $show:literal, $season:literal, $episode:literal, >1) => {
make_content_episode!(@make, $db, $lid, $show, $season, $episode, 1);
};
(@make, $db:expr, $lid:expr, $show:expr, $season:expr, $episode:expr, $count:literal) => {
$crate::entity::info::test::make_info_episode!($db, $show, $season, $episode);
$crate::entity::content::episodes::ActiveModel {
show_id: Set(::flix_model::id::ShowId::from_raw($show)),
season_number: Set(::flix_model::numbers::SeasonNumber::new($season)),
episode_number: Set(::flix_model::numbers::EpisodeNumber::new($episode)),
count: Set($count),
library_id: Set(::flix_model::id::LibraryId::from_raw($lid)),
directory: Set(::std::path::PathBuf::new().into()),
relative_media_path: Set(::std::string::String::new()),
relative_poster_path: Set(::core::option::Option::None),
}
.insert($db)
.await
.expect("insert");
};
}
pub(crate) use make_content_episode;
}
#[cfg(test)]
mod tests {
use std::path::Path;
use flix_model::id::{CollectionId, LibraryId, MovieId, ShowId};
use chrono::NaiveDate;
use sea_orm::ActiveValue::{NotSet, Set};
use sea_orm::entity::prelude::*;
use sea_orm::sqlx::error::ErrorKind;
use crate::entity::content::test::{
make_content_collection, make_content_episode, make_content_library, make_content_movie,
make_content_season, make_content_show,
};
use crate::entity::info::test::{
make_info_collection, make_info_episode, make_info_movie, make_info_season, make_info_show,
};
use crate::tests::new_initialized_memory_db;
use super::super::tests::get_error_kind;
use super::super::tests::{noneable, notsettable};
#[tokio::test]
async fn use_test_macros() {
let db = new_initialized_memory_db().await;
make_content_library!(&db, 1);
make_content_collection!(&db, 1, 1, None);
make_content_movie!(&db, 1, 1, None);
make_content_show!(&db, 1, 1, None);
make_content_season!(&db, 1, 1, 1);
make_content_episode!(&db, 1, 1, 1, 1);
}
#[tokio::test]
async fn test_round_trip_libraries() {
let db = new_initialized_memory_db().await;
macro_rules! assert_library {
($db:expr, $id:literal, Success $(; $($skip:ident),+)?) => {
let model = assert_library!(@insert, $db, $id $(; $($skip),+)?)
.expect("insert");
assert_eq!(model.id, LibraryId::from_raw($id));
assert_eq!(model.directory, Path::new(concat!("L Directory ", $id)).to_owned().into());
assert_eq!(model.last_scan, noneable!(last_scan, NaiveDate::from_yo_opt($id, 1).expect("from_yo_opt").and_hms_opt(0, 0, 0).expect("and_hms_opt").and_utc() $(, $($skip),+)?));
};
($db:expr, $id:literal, $error:ident $(; $($skip:ident),+)?) => {
let model = assert_library!(@insert, $db, $id $(; $($skip),+)?)
.expect_err("insert");
assert_eq!(get_error_kind(model).expect("get_error_kind"), ErrorKind::$error);
};
(@insert, $db:expr, $id:literal $(; $($skip:ident),+)?) => {
super::libraries::ActiveModel {
id: notsettable!(id, LibraryId::from_raw($id) $(, $($skip),+)?),
directory: notsettable!(directory, Path::new(concat!("L Directory ", $id)).to_owned().into() $(, $($skip),+)?),
last_scan: notsettable!(last_scan, Some(NaiveDate::from_yo_opt($id, 1).expect("from_yo_opt").and_hms_opt(0, 0, 0).expect("and_hms_opt").and_utc()) $(, $($skip),+)?),
}.insert($db).await
};
}
assert_library!(&db, 1, Success);
assert_library!(&db, 1, UniqueViolation);
assert_library!(&db, 2, Success);
assert_library!(&db, 3, Success; id);
assert_library!(&db, 4, NotNullViolation; directory);
assert_library!(&db, 5, Success; last_scan);
}
#[tokio::test]
async fn test_round_trip_collections() {
let db = new_initialized_memory_db().await;
macro_rules! assert_collection {
($db:expr, $id:literal, $pid:expr, $lid:literal, Success $(; $($skip:ident),+)?) => {
let model = assert_collection!(@insert, $db, $id, $pid, $lid $(; $($skip),+)?)
.expect("insert");
assert_eq!(model.id, CollectionId::from_raw($id));
assert_eq!(model.parent_id, $pid.map(CollectionId::from_raw));
assert_eq!(model.library_id, LibraryId::from_raw($lid));
assert_eq!(model.directory, Path::new(concat!("C Directory ", $id)).to_owned().into());
assert_eq!(model.relative_poster_path, noneable!(relative_poster_path, concat!("C Poster ", $id).to_owned() $(, $($skip),+)?));
};
($db:expr, $id:literal, $pid:expr, $lid:literal, $error:ident $(; $($skip:ident),+)?) => {
let model = assert_collection!(@insert, $db, $id, $pid, $lid $(; $($skip),+)?)
.expect_err("insert");
assert_eq!(get_error_kind(model).expect("get_error_kind"), ErrorKind::$error);
};
(@insert, $db:expr, $id:literal, $pid:expr, $lid:literal $(; $($skip:ident),+)?) => {
super::collections::ActiveModel {
id: notsettable!(id, CollectionId::from_raw($id) $(, $($skip),+)?),
parent_id: notsettable!(parent_id, $pid.map(CollectionId::from_raw) $(, $($skip),+)?),
library_id: notsettable!(library_id, LibraryId::from_raw($lid) $(, $($skip),+)?),
directory: notsettable!(directory, Path::new(concat!("C Directory ", $id)).to_owned().into() $(, $($skip),+)?),
relative_poster_path: notsettable!(relative_poster_path, Some(concat!("C Poster ", $id).to_owned()) $(, $($skip),+)?),
}.insert($db).await
};
}
make_content_library!(&db, 1);
assert_collection!(&db, 1, None, 1, ForeignKeyViolation);
make_info_collection!(&db, 1);
assert_collection!(&db, 1, None, 1, Success);
make_info_collection!(&db, 2);
assert_collection!(&db, 2, None, 2, ForeignKeyViolation);
make_content_library!(&db, 2);
assert_collection!(&db, 2, None, 2, Success);
assert_collection!(&db, 1, None, 1, UniqueViolation);
make_info_collection!(&db, 3);
make_info_collection!(&db, 4);
make_info_collection!(&db, 5);
make_info_collection!(&db, 6);
make_info_collection!(&db, 7);
make_info_collection!(&db, 8);
assert_collection!(&db, 3, None, 1, Success; id);
assert_collection!(&db, 4, None, 1, Success; parent_id);
assert_collection!(&db, 5, None, 1, NotNullViolation; library_id);
assert_collection!(&db, 6, None, 1, NotNullViolation; directory);
assert_collection!(&db, 7, None, 1, Success; relative_poster_path);
}
#[tokio::test]
async fn test_round_trip_movies() {
let db = new_initialized_memory_db().await;
macro_rules! assert_movie {
($db:expr, $id:literal, $pid:expr, $lid:literal, Success $(; $($skip:ident),+)?) => {
let model = assert_movie!(@insert, $db, $id, $pid, $lid $(; $($skip),+)?)
.expect("insert");
assert_eq!(model.id, MovieId::from_raw($id));
assert_eq!(model.parent_id, $pid.map(CollectionId::from_raw));
assert_eq!(model.library_id, LibraryId::from_raw($lid));
assert_eq!(model.directory, Path::new(concat!("M Directory ", $id)).to_owned().into());
assert_eq!(model.relative_media_path, concat!("M Media ", $id));
assert_eq!(model.relative_poster_path, noneable!(relative_poster_path, concat!("M Poster ", $id).to_owned() $(, $($skip),+)?));
};
($db:expr, $id:literal, $pid:expr, $lid:literal, $error:ident $(; $($skip:ident),+)?) => {
let model = assert_movie!(@insert, $db, $id, $pid, $lid $(; $($skip),+)?)
.expect_err("insert");
assert_eq!(get_error_kind(model).expect("get_error_kind"), ErrorKind::$error);
};
(@insert, $db:expr, $id:literal, $pid:expr, $lid:literal $(; $($skip:ident),+)?) => {
super::movies::ActiveModel {
id: notsettable!(id, MovieId::from_raw($id) $(, $($skip),+)?),
parent_id: notsettable!(parent_id, $pid.map(CollectionId::from_raw) $(, $($skip),+)?),
library_id: notsettable!(library_id, LibraryId::from_raw($lid) $(, $($skip),+)?),
directory: notsettable!(directory, Path::new(concat!("M Directory ", $id)).to_owned().into() $(, $($skip),+)?),
relative_media_path: notsettable!(relative_media_path, concat!("M Media ", $id).to_owned() $(, $($skip),+)?),
relative_poster_path: notsettable!(relative_poster_path, Some(concat!("M Poster ", $id).to_owned()) $(, $($skip),+)?),
}.insert($db).await
};
}
make_content_library!(&db, 1);
assert_movie!(&db, 1, None, 1, ForeignKeyViolation);
make_info_movie!(&db, 1);
assert_movie!(&db, 1, Some(1), 1, ForeignKeyViolation);
make_content_collection!(&db, 1, 1, None);
assert_movie!(&db, 1, Some(1), 1, Success);
assert_movie!(&db, 2, None, 2, ForeignKeyViolation);
make_info_movie!(&db, 2);
assert_movie!(&db, 2, None, 2, ForeignKeyViolation);
make_content_library!(&db, 2);
assert_movie!(&db, 2, None, 2, Success);
assert_movie!(&db, 1, None, 1, UniqueViolation);
make_info_movie!(&db, 3);
make_info_movie!(&db, 4);
make_info_movie!(&db, 5);
make_info_movie!(&db, 6);
make_info_movie!(&db, 7);
make_info_movie!(&db, 8);
make_info_movie!(&db, 9);
assert_movie!(&db, 3, None, 1, Success; id);
assert_movie!(&db, 4, None, 1, Success; parent_id);
assert_movie!(&db, 5, None, 1, NotNullViolation; library_id);
assert_movie!(&db, 6, None, 1, NotNullViolation; directory);
assert_movie!(&db, 7, None, 1, NotNullViolation; relative_media_path);
assert_movie!(&db, 8, None, 1, Success; relative_poster_path);
}
#[tokio::test]
async fn test_round_trip_shows() {
let db = new_initialized_memory_db().await;
macro_rules! assert_show {
($db:expr, $id:literal, $pid:expr, $lid:literal, Success $(; $($skip:ident),+)?) => {
let model = assert_show!(@insert, $db, $id, $pid, $lid $(; $($skip),+)?)
.expect("insert");
assert_eq!(model.id, ShowId::from_raw($id));
assert_eq!(model.parent_id, $pid.map(CollectionId::from_raw));
assert_eq!(model.library_id, LibraryId::from_raw($lid));
assert_eq!(model.directory, Path::new(concat!("S Directory ", $id)).to_owned().into());
assert_eq!(model.relative_poster_path, noneable!(relative_poster_path, concat!("S Poster ", $id).to_owned() $(, $($skip),+)?));
};
($db:expr, $id:literal, $pid:expr, $lid:literal, $error:ident $(; $($skip:ident),+)?) => {
let model = assert_show!(@insert, $db, $id, $pid, $lid $(; $($skip),+)?)
.expect_err("insert");
assert_eq!(get_error_kind(model).expect("get_error_kind"), ErrorKind::$error);
};
(@insert, $db:expr, $id:literal, $pid:expr, $lid:literal $(; $($skip:ident),+)?) => {
super::shows::ActiveModel {
id: notsettable!(id, ShowId::from_raw($id) $(, $($skip),+)?),
parent_id: notsettable!(parent_id, $pid.map(CollectionId::from_raw) $(, $($skip),+)?),
library_id: notsettable!(library_id, LibraryId::from_raw($lid) $(, $($skip),+)?),
directory: notsettable!(directory, Path::new(concat!("S Directory ", $id)).to_owned().into() $(, $($skip),+)?),
relative_poster_path: notsettable!(relative_poster_path, Some(concat!("S Poster ", $id).to_owned()) $(, $($skip),+)?),
}.insert($db).await
};
}
make_content_library!(&db, 1);
assert_show!(&db, 1, None, 1, ForeignKeyViolation);
make_info_show!(&db, 1);
assert_show!(&db, 1, Some(1), 1, ForeignKeyViolation);
make_content_collection!(&db, 1, 1, None);
assert_show!(&db, 1, Some(1), 1, Success);
assert_show!(&db, 2, None, 2, ForeignKeyViolation);
make_info_show!(&db, 2);
assert_show!(&db, 2, None, 2, ForeignKeyViolation);
make_content_library!(&db, 2);
assert_show!(&db, 2, None, 2, Success);
assert_show!(&db, 1, None, 1, UniqueViolation);
make_info_show!(&db, 3);
make_info_show!(&db, 4);
make_info_show!(&db, 5);
make_info_show!(&db, 6);
make_info_show!(&db, 7);
make_info_show!(&db, 8);
assert_show!(&db, 3, None, 1, Success; id);
assert_show!(&db, 4, None, 1, Success; parent_id);
assert_show!(&db, 5, None, 1, NotNullViolation; library_id);
assert_show!(&db, 6, None, 1, NotNullViolation; directory);
assert_show!(&db, 7, None, 1, Success; relative_poster_path);
}
#[tokio::test]
async fn test_round_trip_seasons() {
let db = new_initialized_memory_db().await;
macro_rules! assert_season {
($db:expr, $id:literal, $season:literal, $lid:literal, Success $(; $($skip:ident),+)?) => {
let model = assert_season!(@insert, $db, $id, $season, $lid $(; $($skip),+)?)
.expect("insert");
assert_eq!(model.show_id, ShowId::from_raw($id));
assert_eq!(model.season_number, ::flix_model::numbers::SeasonNumber::new($season));
assert_eq!(model.library_id, LibraryId::from_raw($lid));
assert_eq!(model.directory, Path::new(concat!("SS Directory ", $id, ",", $season)).to_owned().into());
assert_eq!(model.relative_poster_path, noneable!(relative_poster_path, concat!("SS Poster ", $id, ",", $season).to_owned() $(, $($skip),+)?));
};
($db:expr, $id:literal, $season:literal, $lid:literal, $error:ident $(; $($skip:ident),+)?) => {
let model = assert_season!(@insert, $db, $id, $season, $lid $(; $($skip),+)?)
.expect_err("insert");
assert_eq!(get_error_kind(model).expect("get_error_kind"), ErrorKind::$error);
};
(@insert, $db:expr, $id:literal, $season:literal, $lid:literal $(; $($skip:ident),+)?) => {
super::seasons::ActiveModel {
show_id: notsettable!(show_id, ShowId::from_raw($id) $(, $($skip),+)?),
season_number: notsettable!(season_number, ::flix_model::numbers::SeasonNumber::new($season) $(, $($skip),+)?),
library_id: notsettable!(library_id, LibraryId::from_raw($lid) $(, $($skip),+)?),
directory: notsettable!(directory, Path::new(concat!("SS Directory ", $id, ",", $season)).to_owned().into() $(, $($skip),+)?),
relative_poster_path: notsettable!(relative_poster_path, Some(concat!("SS Poster ", $id, ",", $season).to_owned()) $(, $($skip),+)?),
}.insert($db).await
};
}
make_content_library!(&db, 1);
make_content_show!(&db, 1, 1, None);
assert_season!(&db, 1, 1, 1, ForeignKeyViolation);
make_info_season!(&db, 1, 1);
assert_season!(&db, 1, 1, 1, Success);
assert_season!(&db, 1, 1, 1, UniqueViolation);
make_info_season!(&db, 1, 3);
make_info_season!(&db, 1, 4);
make_info_season!(&db, 1, 5);
make_info_season!(&db, 1, 6);
make_info_season!(&db, 1, 7);
make_info_season!(&db, 1, 8);
assert_season!(&db, 1, 3, 1, NotNullViolation; show_id);
assert_season!(&db, 1, 4, 1, NotNullViolation; season_number);
assert_season!(&db, 1, 5, 1, NotNullViolation; library_id);
assert_season!(&db, 1, 6, 1, NotNullViolation; directory);
assert_season!(&db, 1, 7, 1, Success; relative_poster_path);
}
#[tokio::test]
async fn test_round_trip_episodes() {
let db = new_initialized_memory_db().await;
macro_rules! assert_episode {
($db:expr, $id:literal, $season:literal, $episode:literal, $lid:literal, Success $(; $($skip:ident),+)?) => {
let model = assert_episode!(@insert, $db, $id, $season, $episode, $lid $(; $($skip),+)?)
.expect("insert");
assert_eq!(model.show_id, ShowId::from_raw($id));
assert_eq!(model.season_number, ::flix_model::numbers::SeasonNumber::new($season));
assert_eq!(model.episode_number, ::flix_model::numbers::EpisodeNumber::new($episode));
assert_eq!(model.library_id, LibraryId::from_raw($lid));
assert_eq!(model.directory, Path::new(concat!("SS Directory ", $id, ",", $season, $episode)).to_owned().into());
assert_eq!(model.relative_media_path, concat!("SS Media ", $id, ",", $season, $episode));
assert_eq!(model.relative_poster_path, noneable!(relative_poster_path, concat!("SS Poster ", $id, ",", $season, $episode).to_owned() $(, $($skip),+)?));
};
($db:expr, $id:literal, $season:literal, $episode:literal, $lid:literal, $error:ident $(; $($skip:ident),+)?) => {
let model = assert_episode!(@insert, $db, $id, $season, $episode, $lid $(; $($skip),+)?)
.expect_err("insert");
assert_eq!(get_error_kind(model).expect("get_error_kind"), ErrorKind::$error);
};
(@insert, $db:expr, $id:literal, $season:literal, $episode:literal, $lid:literal $(; $($skip:ident),+)?) => {
super::episodes::ActiveModel {
show_id: notsettable!(show_id, ShowId::from_raw($id) $(, $($skip),+)?),
season_number: notsettable!(season_number, ::flix_model::numbers::SeasonNumber::new($season) $(, $($skip),+)?),
episode_number: notsettable!(episode_number, ::flix_model::numbers::EpisodeNumber::new($episode) $(, $($skip),+)?),
count: notsettable!(count, 0 $(, $($skip),+)?),
library_id: notsettable!(library_id, LibraryId::from_raw($lid) $(, $($skip),+)?),
directory: notsettable!(directory, Path::new(concat!("SS Directory ", $id, ",", $season, $episode)).to_owned().into() $(, $($skip),+)?),
relative_media_path: notsettable!(relative_media_path, concat!("SS Media ", $id, ",", $season, $episode).to_owned() $(, $($skip),+)?),
relative_poster_path: notsettable!(relative_poster_path, Some(concat!("SS Poster ", $id, ",", $season, $episode).to_owned()) $(, $($skip),+)?),
}.insert($db).await
};
}
make_content_library!(&db, 1);
make_content_show!(&db, 1, 1, None);
make_content_season!(&db, 1, 1, 1);
assert_episode!(&db, 1, 1, 1, 1, ForeignKeyViolation);
make_info_episode!(&db, 1, 1, 1);
assert_episode!(&db, 1, 1, 1, 1, Success);
assert_episode!(&db, 1, 1, 1, 1, UniqueViolation);
make_info_episode!(&db, 1, 1, 3);
make_info_episode!(&db, 1, 1, 4);
make_info_episode!(&db, 1, 1, 5);
make_info_episode!(&db, 1, 1, 6);
make_info_episode!(&db, 1, 1, 7);
make_info_episode!(&db, 1, 1, 8);
make_info_episode!(&db, 1, 1, 9);
make_info_episode!(&db, 1, 1, 10);
assert_episode!(&db, 1, 1, 3, 1, NotNullViolation; show_id);
assert_episode!(&db, 1, 1, 4, 1, NotNullViolation; season_number);
assert_episode!(&db, 1, 1, 5, 1, NotNullViolation; episode_number);
assert_episode!(&db, 1, 1, 6, 1, NotNullViolation; library_id);
assert_episode!(&db, 1, 1, 7, 1, NotNullViolation; directory);
assert_episode!(&db, 1, 1, 8, 1, NotNullViolation; relative_media_path);
assert_episode!(&db, 1, 1, 9, 1, Success; relative_poster_path);
}
}
+592
View File
@@ -0,0 +1,592 @@
//! This module contains entities for storing media information such as
//! titles and overviews
/// Collection entity
pub mod collections {
use flix_model::id::CollectionId;
use sea_orm::entity::prelude::*;
/// The database representation of a flix collection
#[sea_orm::model]
#[derive(Debug, Clone, DeriveEntityModel)]
#[sea_orm(table_name = "flix_info_collections")]
pub struct Model {
/// The collection's ID
#[sea_orm(primary_key, auto_increment = false)]
pub id: CollectionId,
/// The collection's title
pub title: String,
/// The collection's overview
pub overview: String,
/// The sortable title
#[sea_orm(indexed)]
pub sort_title: String,
/// The filesystem-safe slug
#[sea_orm(indexed, unique)]
pub fs_slug: String,
/// The url-safe slug
#[sea_orm(indexed, unique)]
pub web_slug: String,
}
impl ActiveModelBehavior for ActiveModel {}
}
/// Movie entity
pub mod movies {
use flix_model::id::MovieId;
use chrono::NaiveDate;
use sea_orm::entity::prelude::*;
/// The database representation of a flix movie
#[sea_orm::model]
#[derive(Debug, Clone, DeriveEntityModel)]
#[sea_orm(table_name = "flix_info_movies")]
pub struct Model {
/// The movie's ID
#[sea_orm(primary_key, auto_increment = false)]
pub id: MovieId,
/// The movie's title
pub title: String,
/// The movie's tagline
pub tagline: String,
/// The movie's overview
pub overview: String,
/// The movie's release date
#[sea_orm(indexed)]
pub date: NaiveDate,
/// The sortable title
#[sea_orm(indexed)]
pub sort_title: String,
/// The filesystem-safe slug
#[sea_orm(indexed, unique)]
pub fs_slug: String,
/// The url-safe slug
#[sea_orm(indexed, unique)]
pub web_slug: String,
}
impl ActiveModelBehavior for ActiveModel {}
}
/// Show entity
pub mod shows {
use flix_model::id::ShowId;
use chrono::NaiveDate;
use sea_orm::entity::prelude::*;
/// The database representation of a flix show
#[sea_orm::model]
#[derive(Debug, Clone, DeriveEntityModel)]
#[sea_orm(table_name = "flix_info_shows")]
pub struct Model {
/// The show's ID
#[sea_orm(primary_key, auto_increment = false)]
pub id: ShowId,
/// The show's title
pub title: String,
/// The show's tagline
pub tagline: String,
/// The show's overview
pub overview: String,
/// The show's air date
#[sea_orm(indexed)]
pub date: NaiveDate,
/// The sortable title
#[sea_orm(indexed)]
pub sort_title: String,
/// The filesystem-safe slug
#[sea_orm(indexed, unique)]
pub fs_slug: String,
/// The url-safe slug
#[sea_orm(indexed, unique)]
pub web_slug: String,
/// Seasons that are part of this show
#[sea_orm(has_many)]
pub seasons: HasMany<super::seasons::Entity>,
/// Episodes that are part of this show
#[sea_orm(has_many)]
pub episodes: HasMany<super::episodes::Entity>,
}
impl ActiveModelBehavior for ActiveModel {}
}
/// Season entity
pub mod seasons {
use flix_model::id::ShowId;
use flix_model::numbers::SeasonNumber;
use chrono::NaiveDate;
use sea_orm::entity::prelude::*;
/// The database representation of a flix season
#[sea_orm::model]
#[derive(Debug, Clone, DeriveEntityModel)]
#[sea_orm(table_name = "flix_info_seasons")]
pub struct Model {
/// The season's show's ID
#[sea_orm(primary_key, auto_increment = false)]
pub show_id: ShowId,
/// The season's number
#[sea_orm(primary_key, auto_increment = false)]
pub season_number: SeasonNumber,
/// The season's title
pub title: String,
/// The season's overview
pub overview: String,
/// The season's air date
#[sea_orm(indexed)]
pub date: NaiveDate,
/// The show this season belongs to
#[sea_orm(
belongs_to,
from = "show_id",
to = "id",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub show: HasOne<super::shows::Entity>,
/// Episodes that are part of this season
#[sea_orm(has_many)]
pub episodes: HasMany<super::episodes::Entity>,
}
impl ActiveModelBehavior for ActiveModel {}
}
/// Episode entity
pub mod episodes {
use flix_model::id::ShowId;
use flix_model::numbers::{EpisodeNumber, SeasonNumber};
use chrono::NaiveDate;
use sea_orm::entity::prelude::*;
/// The database representation of a flix episode
#[sea_orm::model]
#[derive(Debug, Clone, DeriveEntityModel)]
#[sea_orm(table_name = "flix_info_episodes")]
pub struct Model {
/// The episode's show's ID
#[sea_orm(primary_key, auto_increment = false)]
pub show_id: ShowId,
/// The episode's season's number
#[sea_orm(primary_key, auto_increment = false)]
pub season_number: SeasonNumber,
/// The episode's number
#[sea_orm(primary_key, auto_increment = false)]
pub episode_number: EpisodeNumber,
/// The episode's title
pub title: String,
/// The episode's overview
pub overview: String,
/// The episode's air date
#[sea_orm(indexed)]
pub date: NaiveDate,
/// The show this episode belongs to
#[sea_orm(
belongs_to,
from = "show_id",
to = "id",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub show: HasOne<super::shows::Entity>,
/// The season this episode belongs to
#[sea_orm(
belongs_to,
from = "(show_id, season_number)",
to = "(show_id, season_number)",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub season: HasOne<super::seasons::Entity>,
}
impl ActiveModelBehavior for ActiveModel {}
}
/// Macros for creating info entities
#[cfg(test)]
pub mod test {
macro_rules! make_info_collection {
($db:expr, $id:expr) => {
$crate::entity::info::collections::ActiveModel {
id: Set(::flix_model::id::CollectionId::from_raw($id)),
title: Set(::std::string::String::new()),
overview: Set(::std::string::String::new()),
sort_title: Set(::std::string::String::new()),
fs_slug: Set(format!("C FS {}", $id)),
web_slug: Set(format!("C Web {}", $id)),
}
.insert($db)
.await
.expect("insert");
};
}
pub(crate) use make_info_collection;
macro_rules! make_info_movie {
($db:expr, $id:expr) => {
$crate::entity::info::movies::ActiveModel {
id: Set(::flix_model::id::MovieId::from_raw($id)),
title: Set(::std::string::String::new()),
tagline: Set(::std::string::String::new()),
overview: Set(::std::string::String::new()),
date: Set(::chrono::NaiveDate::from_yo_opt(1, 1).expect("from_yo_opt")),
sort_title: Set(::std::string::String::new()),
fs_slug: Set(format!("M FS {}", $id)),
web_slug: Set(format!("M Web {}", $id)),
}
.insert($db)
.await
.expect("insert");
};
}
pub(crate) use make_info_movie;
macro_rules! make_info_show {
($db:expr, $id:expr) => {
$crate::entity::info::shows::ActiveModel {
id: Set(::flix_model::id::ShowId::from_raw($id)),
title: Set(::std::string::String::new()),
tagline: Set(::std::string::String::new()),
overview: Set(::std::string::String::new()),
date: Set(::chrono::NaiveDate::from_yo_opt(1, 1).expect("from_yo_opt")),
sort_title: Set(::std::string::String::new()),
fs_slug: Set(format!("S FS {}", $id)),
web_slug: Set(format!("S Web {}", $id)),
}
.insert($db)
.await
.expect("insert");
};
}
pub(crate) use make_info_show;
macro_rules! make_info_season {
($db:expr, $show:expr, $season:expr) => {
$crate::entity::info::seasons::ActiveModel {
show_id: Set(::flix_model::id::ShowId::from_raw($show)),
season_number: Set(::flix_model::numbers::SeasonNumber::new($season)),
title: Set(::std::string::String::new()),
overview: Set(::std::string::String::new()),
date: Set(::chrono::NaiveDate::from_yo_opt(1, 1).expect("from_yo_opt")),
}
.insert($db)
.await
.expect("insert");
};
}
pub(crate) use make_info_season;
macro_rules! make_info_episode {
($db:expr, $show:expr, $season:expr, $episode:expr) => {
$crate::entity::info::episodes::ActiveModel {
show_id: Set(::flix_model::id::ShowId::from_raw($show)),
season_number: Set(::flix_model::numbers::SeasonNumber::new($season)),
episode_number: Set(::flix_model::numbers::EpisodeNumber::new($episode)),
title: Set(::std::string::String::new()),
overview: Set(::std::string::String::new()),
date: Set(::chrono::NaiveDate::from_yo_opt(1, 1).expect("from_yo_opt")),
}
.insert($db)
.await
.expect("insert");
};
}
pub(crate) use make_info_episode;
}
#[cfg(test)]
mod tests {
use flix_model::id::{CollectionId, MovieId, ShowId};
use chrono::NaiveDate;
use sea_orm::ActiveValue::{NotSet, Set};
use sea_orm::entity::prelude::*;
use sea_orm::sqlx::error::ErrorKind;
use crate::tests::new_initialized_memory_db;
use super::super::tests::get_error_kind;
use super::super::tests::notsettable;
use super::test::{
make_info_collection, make_info_episode, make_info_movie, make_info_season, make_info_show,
};
#[tokio::test]
async fn use_test_macros() {
let db = new_initialized_memory_db().await;
make_info_collection!(&db, 1);
make_info_movie!(&db, 1);
make_info_show!(&db, 1);
make_info_season!(&db, 1, 1);
make_info_episode!(&db, 1, 1, 1);
}
#[tokio::test]
async fn test_round_trip_collections() {
let db = new_initialized_memory_db().await;
macro_rules! assert_collection {
($db:expr, $id:literal, Success $(; $($skip:ident),+)?) => {
let model = assert_collection!(@insert, $db, $id $(; $($skip),+)?)
.expect("insert");
assert_eq!(model.id, CollectionId::from_raw($id));
assert_eq!(model.title, concat!("C Title ", $id));
assert_eq!(model.overview, concat!("C Overview ", $id));
};
($db:expr, $id:literal, $error:ident $(; $($skip:ident),+)?) => {
let model = assert_collection!(@insert, $db, $id $(; $($skip),+)?)
.expect_err("insert");
assert_eq!(get_error_kind(model).expect("get_error_kind"), ErrorKind::$error);
};
(@insert, $db:expr, $id:literal $(; $($skip:ident),+)?) => {
super::collections::ActiveModel {
id: notsettable!(id, CollectionId::from_raw($id) $(, $($skip),+)?),
title: notsettable!(title, concat!("C Title ", $id).to_string() $(, $($skip),+)?),
overview: notsettable!(overview, concat!("C Overview ", $id).to_string() $(, $($skip),+)?),
sort_title: notsettable!(sort_title, concat!("C Sort Title ", $id).to_string() $(, $($skip),+)?),
fs_slug: notsettable!(fs_slug, concat!("C FS Slug ", $id).to_string() $(, $($skip),+)?),
web_slug: notsettable!(web_slug, concat!("C Web Slug ", $id).to_string() $(, $($skip),+)?),
}.insert($db).await
};
}
assert_collection!(&db, 1, Success);
assert_collection!(&db, 1, UniqueViolation);
assert_collection!(&db, 2, Success);
assert_collection!(&db, 3, Success; id);
assert_collection!(&db, 4, NotNullViolation; title);
assert_collection!(&db, 5, NotNullViolation; overview);
assert_collection!(&db, 6, NotNullViolation; sort_title);
assert_collection!(&db, 7, NotNullViolation; fs_slug);
assert_collection!(&db, 8, NotNullViolation; web_slug);
}
#[tokio::test]
async fn test_round_trip_movies() {
let db = new_initialized_memory_db().await;
macro_rules! assert_movie {
($db:expr, $id:literal, Success $(; $($skip:ident),+)?) => {
let model = assert_movie!(@insert, $db, $id $(; $($skip),+)?)
.expect("insert");
assert_eq!(model.id, MovieId::from_raw($id));
assert_eq!(model.title, concat!("M Title ", $id));
assert_eq!(model.tagline, concat!("M Tagline ", $id));
assert_eq!(model.overview, concat!("M Overview ", $id));
assert_eq!(model.date, NaiveDate::from_yo_opt($id, 1).expect("from_yo_opt"));
};
($db:expr, $id:literal, $error:ident $(; $($skip:ident),+)?) => {
let model = assert_movie!(@insert, $db, $id $(; $($skip),+)?)
.expect_err("insert");
assert_eq!(get_error_kind(model).expect("get_error_kind"), ErrorKind::$error);
};
(@insert, $db:expr, $id:literal $(; $($skip:ident),+)?) => {
super::movies::ActiveModel {
id: notsettable!(id, MovieId::from_raw($id) $(, $($skip),+)?),
title: notsettable!(title, concat!("M Title ", $id).to_string() $(, $($skip),+)?),
tagline: notsettable!(tagline, concat!("M Tagline ", $id).to_string() $(, $($skip),+)?),
overview: notsettable!(overview, concat!("M Overview ", $id).to_string() $(, $($skip),+)?),
date: notsettable!(date, NaiveDate::from_yo_opt($id, 1).expect("from_yo_opt") $(, $($skip),+)?),
sort_title: notsettable!(sort_title, concat!("M Sort Title ", $id).to_string() $(, $($skip),+)?),
fs_slug: notsettable!(fs_slug, concat!("M FS Slug ", $id).to_string() $(, $($skip),+)?),
web_slug: notsettable!(web_slug, concat!("M Web Slug ", $id).to_string() $(, $($skip),+)?),
}.insert($db).await
};
}
assert_movie!(&db, 1, Success);
assert_movie!(&db, 1, UniqueViolation);
assert_movie!(&db, 2, Success);
assert_movie!(&db, 3, Success; id);
assert_movie!(&db, 4, NotNullViolation; title);
assert_movie!(&db, 5, NotNullViolation; tagline);
assert_movie!(&db, 6, NotNullViolation; overview);
assert_movie!(&db, 7, NotNullViolation; date);
assert_movie!(&db, 8, NotNullViolation; sort_title);
assert_movie!(&db, 9, NotNullViolation; fs_slug);
assert_movie!(&db, 10, NotNullViolation; web_slug);
}
#[tokio::test]
async fn test_round_trip_shows() {
let db = new_initialized_memory_db().await;
macro_rules! assert_show {
($db:expr, $id:literal, Success $(; $($skip:ident),+)?) => {
let model = assert_show!(@insert, $db, $id $(; $($skip),+)?)
.expect("insert");
assert_eq!(model.id, ShowId::from_raw($id));
assert_eq!(model.title, concat!("S Title ", $id));
assert_eq!(model.tagline, concat!("S Tagline ", $id));
assert_eq!(model.overview, concat!("S Overview ", $id));
assert_eq!(model.date, NaiveDate::from_yo_opt($id, 1).expect("from_yo_opt"));
};
($db:expr, $id:literal, $error:ident $(; $($skip:ident),+)?) => {
let model = assert_show!(@insert, $db, $id $(; $($skip),+)?)
.expect_err("insert");
assert_eq!(
get_error_kind(model).expect("get_error_kind"),
ErrorKind::$error
);
};
(@insert, $db:expr, $id:literal $(; $($skip:ident),+)?) => {
super::shows::ActiveModel {
id: notsettable!(id, ShowId::from_raw($id) $(, $($skip),+)?),
title: notsettable!(title, concat!("S Title ", $id).to_string() $(, $($skip),+)?),
tagline: notsettable!(tagline, concat!("S Tagline ", $id).to_string() $(, $($skip),+)?),
overview: notsettable!(overview, concat!("S Overview ", $id).to_string() $(, $($skip),+)?),
date: notsettable!(date, NaiveDate::from_yo_opt($id, 1).expect("from_yo_opt") $(, $($skip),+)?),
sort_title: notsettable!(sort_title, concat!("S Sort Title ", $id).to_string() $(, $($skip),+)?),
fs_slug: notsettable!(fs_slug, concat!("S FS Slug ", $id).to_string() $(, $($skip),+)?),
web_slug: notsettable!(web_slug, concat!("S Web Slug ", $id).to_string() $(, $($skip),+)?),
}.insert($db).await
};
}
assert_show!(&db, 1, Success);
assert_show!(&db, 1, UniqueViolation);
assert_show!(&db, 2, Success);
assert_show!(&db, 3, Success; id);
assert_show!(&db, 4, NotNullViolation; title);
assert_show!(&db, 5, NotNullViolation; tagline);
assert_show!(&db, 6, NotNullViolation; overview);
assert_show!(&db, 7, NotNullViolation; date);
assert_show!(&db, 8, NotNullViolation; sort_title);
assert_show!(&db, 9, NotNullViolation; fs_slug);
assert_show!(&db, 10, NotNullViolation; web_slug);
}
#[tokio::test]
async fn test_round_trip_seasons() {
let db = new_initialized_memory_db().await;
macro_rules! assert_season {
($db:expr, $show:literal, $season:literal, Success $(; $($skip:ident),+)?) => {
let model = assert_season!(@insert, $db, $show, $season $(; $($skip),+)?)
.expect("insert");
assert_eq!(model.show_id, ShowId::from_raw($show));
assert_eq!(model.season_number, ::flix_model::numbers::SeasonNumber::new($season));
assert_eq!(model.title, concat!("SS Title ", $show, ",", $season));
assert_eq!(model.overview, concat!("SS Overview ", $show, ",", $season));
assert_eq!(model.date, NaiveDate::from_yo_opt($show + $season, 1).expect("from_yo_opt"));
};
($db:expr, $show:literal, $season:literal, $error:ident $(; $($skip:ident),+)?) => {
let model = assert_season!(@insert, $db, $show, $season $(; $($skip),+)?)
.expect_err("insert");
assert_eq!(
get_error_kind(model).expect("get_error_kind"),
ErrorKind::$error
);
};
(@insert, $db:expr, $show:literal, $season:literal $(; $($skip:ident),+)?) => {
super::seasons::ActiveModel {
show_id: notsettable!(show_id, ShowId::from_raw($show) $(, $($skip),+)?),
season_number: notsettable!(season_number, ::flix_model::numbers::SeasonNumber::new($season) $(, $($skip),+)?),
title: notsettable!(title, concat!("SS Title ", $show, ",", $season).to_string() $(, $($skip),+)?),
overview: notsettable!(overview, concat!("SS Overview ", $show, ",", $season).to_string() $(, $($skip),+)?),
date: notsettable!(date, NaiveDate::from_yo_opt($show + $season, 1).expect("from_yo_opt") $(, $($skip),+)?),
}.insert($db).await
};
}
assert_season!(&db, 1, 1, ForeignKeyViolation);
make_info_show!(&db, 1);
make_info_show!(&db, 2);
assert_season!(&db, 1, 1, Success);
assert_season!(&db, 1, 1, UniqueViolation);
assert_season!(&db, 2, 1, Success);
assert_season!(&db, 1, 2, Success);
assert_season!(&db, 1, 3, NotNullViolation; show_id);
assert_season!(&db, 1, 4, NotNullViolation; season_number);
assert_season!(&db, 1, 5, NotNullViolation; title);
assert_season!(&db, 1, 6, NotNullViolation; overview);
assert_season!(&db, 1, 7, NotNullViolation; date);
}
#[tokio::test]
async fn test_round_trip_episodes() {
let db = new_initialized_memory_db().await;
macro_rules! assert_episode {
($db:expr, $show:literal, $season:literal, $episode:literal, Success $(; $($skip:ident),+)?) => {
let model = assert_episode!(@insert, $db, $show, $season, $episode $(; $($skip),+)?)
.expect("insert");
assert_eq!(model.show_id, ShowId::from_raw($show));
assert_eq!(model.season_number, ::flix_model::numbers::SeasonNumber::new($season));
assert_eq!(model.episode_number, ::flix_model::numbers::EpisodeNumber::new($episode));
assert_eq!(model.title, concat!("SSE Title ", $show, ",", $season, ",", $episode));
assert_eq!(model.overview, concat!("SSE Overview ", $show, ",", $season, ",", $episode));
assert_eq!(model.date, NaiveDate::from_yo_opt($show + $season, 1).expect("from_yo_opt"));
};
($db:expr, $show:literal, $season:literal, $episode:literal, $error:ident $(; $($skip:ident),+)?) => {
let model = assert_episode!(@insert, $db, $show, $season, $episode $(; $($skip),+)?)
.expect_err("insert");
assert_eq!(
get_error_kind(model).expect("get_error_kind"),
ErrorKind::$error
);
};
(@insert, $db:expr, $show:literal, $season:literal, $episode:literal $(; $($skip:ident),+)?) => {
super::episodes::ActiveModel {
show_id: notsettable!(show_id, ShowId::from_raw($show) $(, $($skip),+)?),
season_number: notsettable!(season_number, ::flix_model::numbers::SeasonNumber::new($season) $(, $($skip),+)?),
episode_number: notsettable!(episode_number, ::flix_model::numbers::EpisodeNumber::new($episode) $(, $($skip),+)?),
title: notsettable!(title, concat!("SSE Title ", $show, ",", $season, ",", $episode).to_string() $(, $($skip),+)?),
overview: notsettable!(overview, concat!("SSE Overview ", $show, ",", $season, ",", $episode).to_string() $(, $($skip),+)?),
date: notsettable!(date, NaiveDate::from_yo_opt($show + $season, 1).expect("from_yo_opt") $(, $($skip),+)?),
}.insert($db).await
};
}
assert_episode!(&db, 1, 1, 1, ForeignKeyViolation);
make_info_show!(&db, 1);
make_info_show!(&db, 2);
assert_episode!(&db, 1, 1, 1, ForeignKeyViolation);
make_info_season!(&db, 1, 1);
make_info_season!(&db, 1, 2);
make_info_season!(&db, 2, 1);
assert_episode!(&db, 1, 1, 1, Success);
assert_episode!(&db, 1, 1, 1, UniqueViolation);
assert_episode!(&db, 2, 1, 1, Success);
assert_episode!(&db, 1, 2, 1, Success);
assert_episode!(&db, 1, 1, 2, Success);
assert_episode!(&db, 1, 1, 3, NotNullViolation; show_id);
assert_episode!(&db, 1, 1, 4, NotNullViolation; season_number);
assert_episode!(&db, 1, 1, 4, NotNullViolation; episode_number);
assert_episode!(&db, 1, 1, 5, NotNullViolation; title);
assert_episode!(&db, 1, 1, 6, NotNullViolation; overview);
assert_episode!(&db, 1, 1, 7, NotNullViolation; date);
}
}
File diff suppressed because it is too large Load Diff
+677
View File
@@ -0,0 +1,677 @@
//! This module contains entities for storing dynamic data from TMDB
/// Collection entity
pub mod collections {
use flix_model::id::CollectionId as FlixId;
use flix_tmdb::model::id::CollectionId;
use chrono::{DateTime, Utc};
use sea_orm::entity::prelude::*;
use crate::entity;
/// The database representation of a tmdb collection
#[sea_orm::model]
#[derive(Debug, Clone, DeriveEntityModel)]
#[sea_orm(table_name = "flix_tmdb_collections")]
pub struct Model {
/// The collection's TMDB ID
#[sea_orm(primary_key, auto_increment = false)]
pub tmdb_id: CollectionId,
/// The collection's ID
#[sea_orm(unique)]
pub flix_id: FlixId,
/// The date of the last update
pub last_update: DateTime<Utc>,
/// The number of movies in the collection
pub movie_count: u16,
/// The info for this collection
#[sea_orm(
belongs_to,
from = "flix_id",
to = "id",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub info: HasOne<entity::info::collections::Entity>,
/// Movies that are in this collection
#[sea_orm(has_many)]
pub movies: HasMany<super::movies::Entity>,
}
impl ActiveModelBehavior for ActiveModel {}
}
/// Movie entity
pub mod movies {
use flix_model::id::MovieId as FlixId;
use flix_tmdb::model::id::{CollectionId, MovieId};
use seamantic::model::duration::Seconds;
use chrono::{DateTime, Utc};
use sea_orm::entity::prelude::*;
use crate::entity;
/// The database representation of a tmdb movie
#[sea_orm::model]
#[derive(Debug, Clone, DeriveEntityModel)]
#[sea_orm(table_name = "flix_tmdb_movies")]
pub struct Model {
/// The movie's TMDB ID
#[sea_orm(primary_key, auto_increment = false)]
pub tmdb_id: MovieId,
/// The movie's ID
#[sea_orm(unique)]
pub flix_id: FlixId,
/// The date of the last update
pub last_update: DateTime<Utc>,
/// The movie's runtime in seconds
pub runtime: Seconds,
/// The TMDB ID of the collection this movie belongs to
#[sea_orm(indexed)]
pub collection_id: Option<CollectionId>,
/// The collection this movie belongs to
#[sea_orm(
belongs_to,
from = "collection_id",
to = "tmdb_id",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub collection: HasOne<super::collections::Entity>,
/// The info for this movie
#[sea_orm(
belongs_to,
from = "flix_id",
to = "id",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub info: HasOne<entity::info::movies::Entity>,
}
impl ActiveModelBehavior for ActiveModel {}
}
/// Show entity
pub mod shows {
use flix_model::id::ShowId as FlixId;
use flix_tmdb::model::id::ShowId;
use chrono::{DateTime, Utc};
use sea_orm::entity::prelude::*;
use crate::entity;
/// The database representation of a tmdb show
#[sea_orm::model]
#[derive(Debug, Clone, DeriveEntityModel)]
#[sea_orm(table_name = "flix_tmdb_shows")]
pub struct Model {
/// The show's TMDB ID
#[sea_orm(primary_key, auto_increment = false)]
pub tmdb_id: ShowId,
/// The show's ID
#[sea_orm(unique)]
pub flix_id: FlixId,
/// The movie's runtime in seconds
pub last_update: DateTime<Utc>,
/// The number of seasons the show has
pub number_of_seasons: u32,
/// The info for this show
#[sea_orm(
belongs_to,
from = "flix_id",
to = "id",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub info: HasOne<entity::info::shows::Entity>,
/// Seasons that are part of this show
#[sea_orm(has_many)]
pub seasons: HasMany<super::seasons::Entity>,
/// Episodes that are part of this show
#[sea_orm(has_many)]
pub episodes: HasMany<super::episodes::Entity>,
}
impl ActiveModelBehavior for ActiveModel {}
}
/// Season entity
pub mod seasons {
use flix_model::id::ShowId as FlixId;
use flix_model::numbers::SeasonNumber;
use flix_tmdb::model::id::ShowId;
use chrono::{DateTime, Utc};
use sea_orm::entity::prelude::*;
use crate::entity;
/// The database representation of a tmdb season
#[sea_orm::model]
#[derive(Debug, Clone, DeriveEntityModel)]
#[sea_orm(table_name = "flix_tmdb_seasons")]
pub struct Model {
/// The season's show's TMDB ID
#[sea_orm(primary_key, auto_increment = false)]
pub tmdb_show: ShowId,
/// The season's TMDB season number
#[sea_orm(primary_key, auto_increment = false)]
pub tmdb_season: SeasonNumber,
/// The season's show's ID
#[sea_orm(unique_key = "flix")]
pub flix_show: FlixId,
/// The season's number
#[sea_orm(unique_key = "flix")]
pub flix_season: SeasonNumber,
/// The date of the last update
pub last_update: DateTime<Utc>,
/// The show this season belongs to
#[sea_orm(
belongs_to,
from = "tmdb_show",
to = "tmdb_id",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub show: HasOne<super::shows::Entity>,
/// The info for this season
#[sea_orm(
belongs_to,
from = "(flix_show, flix_season)",
to = "(show_id, season_number)",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub info: HasOne<entity::info::seasons::Entity>,
/// Episodes that are part of this season
#[sea_orm(has_many)]
pub episodes: HasMany<super::episodes::Entity>,
}
impl ActiveModelBehavior for ActiveModel {}
}
/// Season entity
pub mod episodes {
use flix_model::id::ShowId as FlixId;
use flix_model::numbers::{EpisodeNumber, SeasonNumber};
use flix_tmdb::model::id::ShowId;
use seamantic::model::duration::Seconds;
use chrono::{DateTime, Utc};
use sea_orm::entity::prelude::*;
use crate::entity;
/// The database representation of a tmdb episode
#[sea_orm::model]
#[derive(Debug, Clone, DeriveEntityModel)]
#[sea_orm(table_name = "flix_tmdb_episodes")]
pub struct Model {
/// The episode's show's TMDB ID
#[sea_orm(primary_key, auto_increment = false)]
pub tmdb_show: ShowId,
/// The episode's season's TMDB season number
#[sea_orm(primary_key, auto_increment = false)]
pub tmdb_season: SeasonNumber,
/// The episode's TMDB episode number
#[sea_orm(primary_key, auto_increment = false)]
pub tmdb_episode: EpisodeNumber,
/// The episode's show's ID
#[sea_orm(unique_key = "flix")]
pub flix_show: FlixId,
/// The episode's season's number
#[sea_orm(unique_key = "flix")]
pub flix_season: SeasonNumber,
/// The episode's number
#[sea_orm(unique_key = "flix")]
pub flix_episode: EpisodeNumber,
/// The date of the last update
pub last_update: DateTime<Utc>,
/// The episode's runtime in seconds
pub runtime: Seconds,
/// The show this episode belongs to
#[sea_orm(
belongs_to,
from = "tmdb_show",
to = "tmdb_id",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub show: HasOne<super::shows::Entity>,
/// The season this episode belongs to
#[sea_orm(
belongs_to,
from = "(tmdb_show, tmdb_season)",
to = "(tmdb_show, tmdb_season)",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub season: HasOne<super::seasons::Entity>,
/// The info for this episode
#[sea_orm(
belongs_to,
from = "(flix_show, flix_season, flix_episode)",
to = "(show_id, season_number, episode_number)",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub info: HasOne<entity::info::episodes::Entity>,
}
impl ActiveModelBehavior for ActiveModel {}
}
/// Macros for creating tmdb entities
#[cfg(test)]
pub mod test {
macro_rules! make_tmdb_collection {
($db:expr, $id:expr, $flix_id:expr) => {
$crate::entity::tmdb::collections::ActiveModel {
tmdb_id: Set(::flix_tmdb::model::id::CollectionId::from_raw($id)),
flix_id: Set(::flix_model::id::CollectionId::from_raw($flix_id)),
last_update: Set(::chrono::Utc::now()),
movie_count: Set(::core::default::Default::default()),
}
.insert($db)
.await
.expect("insert");
};
}
pub(crate) use make_tmdb_collection;
macro_rules! make_tmdb_movie {
($db:expr, $id:expr, $flix_id:expr) => {
$crate::entity::tmdb::movies::ActiveModel {
tmdb_id: Set(::flix_tmdb::model::id::MovieId::from_raw($id)),
flix_id: Set(::flix_model::id::MovieId::from_raw($flix_id)),
last_update: Set(::chrono::Utc::now()),
runtime: Set(::core::default::Default::default()),
collection_id: Set(None),
}
.insert($db)
.await
.expect("insert");
};
}
pub(crate) use make_tmdb_movie;
macro_rules! make_tmdb_show {
($db:expr, $id:expr, $flix_id:expr) => {
$crate::entity::tmdb::shows::ActiveModel {
tmdb_id: Set(::flix_tmdb::model::id::ShowId::from_raw($id)),
flix_id: Set(::flix_model::id::ShowId::from_raw($flix_id)),
last_update: Set(::chrono::Utc::now()),
number_of_seasons: Set(::core::default::Default::default()),
}
.insert($db)
.await
.expect("insert");
};
}
pub(crate) use make_tmdb_show;
macro_rules! make_tmdb_season {
($db:expr, $show:expr, $season:expr, $flix_show:expr, $flix_season:expr) => {
$crate::entity::tmdb::seasons::ActiveModel {
tmdb_show: Set(::flix_tmdb::model::id::ShowId::from_raw($show)),
tmdb_season: Set(::flix_model::numbers::SeasonNumber::new($season)),
flix_show: Set(::flix_model::id::ShowId::from_raw($flix_show)),
flix_season: Set(::flix_model::numbers::SeasonNumber::new($flix_season)),
last_update: Set(::chrono::Utc::now()),
}
.insert($db)
.await
.expect("insert");
};
}
pub(crate) use make_tmdb_season;
macro_rules! make_tmdb_episode {
($db:expr, $show:expr, $season:expr, $episode:expr, $flix_show:expr, $flix_season:expr, $flix_episode:expr) => {
$crate::entity::tmdb::episodes::ActiveModel {
tmdb_show: Set(::flix_tmdb::model::id::ShowId::from_raw($show)),
tmdb_season: Set(::flix_model::numbers::SeasonNumber::new($season)),
tmdb_episode: Set(::flix_model::numbers::EpisodeNumber::new($episode)),
flix_show: Set(::flix_model::id::ShowId::from_raw($flix_show)),
flix_season: Set(::flix_model::numbers::SeasonNumber::new($flix_season)),
flix_episode: Set(::flix_model::numbers::EpisodeNumber::new($flix_episode)),
last_update: Set(::chrono::Utc::now()),
runtime: Set(::core::default::Default::default()),
}
.insert($db)
.await
.expect("insert");
};
}
pub(crate) use make_tmdb_episode;
}
#[cfg(test)]
mod tests {
use core::time::Duration;
use flix_model::id::{CollectionId, MovieId, ShowId};
use flix_tmdb::model::id::{
CollectionId as TmdbCollectionId, MovieId as TmdbMovieId, ShowId as TmdbShowId,
};
use chrono::NaiveDate;
use sea_orm::ActiveValue::{NotSet, Set};
use sea_orm::entity::prelude::*;
use sea_orm::sqlx::error::ErrorKind;
use crate::entity::info::test::{
make_info_collection, make_info_episode, make_info_movie, make_info_season, make_info_show,
};
use crate::tests::new_initialized_memory_db;
use super::super::tests::get_error_kind;
use super::super::tests::notsettable;
use super::test::{
make_tmdb_collection, make_tmdb_episode, make_tmdb_movie, make_tmdb_season, make_tmdb_show,
};
#[tokio::test]
async fn use_test_macros() {
let db = new_initialized_memory_db().await;
make_info_collection!(&db, 1);
make_info_movie!(&db, 1);
make_info_show!(&db, 1);
make_info_season!(&db, 1, 1);
make_info_episode!(&db, 1, 1, 1);
make_tmdb_collection!(&db, 1, 1);
make_tmdb_movie!(&db, 1, 1);
make_tmdb_show!(&db, 1, 1);
make_tmdb_season!(&db, 1, 1, 1, 1);
make_tmdb_episode!(&db, 1, 1, 1, 1, 1, 1);
}
#[tokio::test]
async fn test_round_trip_collections() {
let db = new_initialized_memory_db().await;
macro_rules! assert_collection {
($db:expr, $id:literal, $tid:literal, Success $(; $($skip:ident),+)?) => {
let model = assert_collection!(@insert, $db, $id, $tid $(; $($skip),+)?)
.expect("insert");
assert_eq!(model.tmdb_id, TmdbCollectionId::from_raw($tid));
assert_eq!(model.flix_id, CollectionId::from_raw($id));
assert_eq!(model.last_update, NaiveDate::from_yo_opt($id, 1).expect("from_yo_opt").and_hms_opt(0, 0, 0).expect("and_hms_opt").and_utc());
assert_eq!(model.movie_count, $id);
};
($db:expr, $id:literal, $tid:literal, $error:ident $(; $($skip:ident),+)?) => {
let model = assert_collection!(@insert, $db, $id, $tid $(; $($skip),+)?)
.expect_err("insert");
assert_eq!(get_error_kind(model).expect("get_error_kind"), ErrorKind::$error);
};
(@insert, $db:expr, $id:literal, $tid:literal $(; $($skip:ident),+)?) => {
super::collections::ActiveModel {
tmdb_id: notsettable!(tmdb_id, TmdbCollectionId::from_raw($tid) $(, $($skip),+)?),
flix_id: notsettable!(flix_id, CollectionId::from_raw($id) $(, $($skip),+)?),
last_update: notsettable!(last_update, NaiveDate::from_yo_opt($id, 1).expect("from_yo_opt").and_hms_opt(0, 0, 0).expect("and_hms_opt").and_utc() $(, $($skip),+)?),
movie_count: notsettable!(movie_count, $id $(, $($skip),+)?),
}.insert($db).await
};
}
assert_collection!(&db, 1, 1, ForeignKeyViolation);
make_info_collection!(&db, 1);
assert_collection!(&db, 1, 1, Success);
assert_collection!(&db, 1, 1, UniqueViolation);
assert_collection!(&db, 1, 2, UniqueViolation);
assert_collection!(&db, 2, 1, UniqueViolation);
make_info_collection!(&db, 2);
assert_collection!(&db, 2, 2, Success);
make_info_collection!(&db, 3);
assert_collection!(&db, 3, 3, Success; tmdb_id);
assert_collection!(&db, 4, 4, NotNullViolation; flix_id);
assert_collection!(&db, 5, 5, NotNullViolation; last_update);
assert_collection!(&db, 6, 6, NotNullViolation; movie_count);
}
#[tokio::test]
async fn test_round_trip_movies() {
let db = new_initialized_memory_db().await;
macro_rules! assert_movie {
($db:expr, $id:literal, $tid:literal, $cid:expr, Success $(; $($skip:ident),+)?) => {
let model = assert_movie!(@insert, $db, $id, $tid, $cid $(; $($skip),+)?)
.expect("insert");
assert_eq!(model.tmdb_id, TmdbMovieId::from_raw($tid));
assert_eq!(model.flix_id, MovieId::from_raw($id));
assert_eq!(model.last_update, NaiveDate::from_yo_opt($id, 1).expect("from_yo_opt").and_hms_opt(0, 0, 0).expect("and_hms_opt").and_utc());
assert_eq!(model.runtime, Duration::from_secs($tid).into());
assert_eq!(model.collection_id, $cid.map(TmdbCollectionId::from_raw));
};
($db:expr, $id:literal, $tid:literal, $cid:expr, $error:ident $(; $($skip:ident),+)?) => {
let model = assert_movie!(@insert, $db, $id, $tid, $cid $(; $($skip),+)?)
.expect_err("insert");
assert_eq!(get_error_kind(model).expect("get_error_kind"), ErrorKind::$error);
};
(@insert, $db:expr, $id:literal, $tid:literal, $cid:expr $(; $($skip:ident),+)?) => {
super::movies::ActiveModel {
tmdb_id: notsettable!(tmdb_id, TmdbMovieId::from_raw($tid) $(, $($skip),+)?),
flix_id: notsettable!(flix_id, MovieId::from_raw($id) $(, $($skip),+)?),
last_update: notsettable!(last_update, NaiveDate::from_yo_opt($id, 1).expect("from_yo_opt").and_hms_opt(0, 0, 0).expect("and_hms_opt").and_utc() $(, $($skip),+)?),
runtime: notsettable!(runtime, Duration::from_secs($tid).into() $(, $($skip),+)?),
collection_id: notsettable!(collection_id, $cid.map(TmdbCollectionId::from_raw) $(, $($skip),+)?),
}.insert($db).await
};
}
assert_movie!(&db, 1, 1, None, ForeignKeyViolation);
make_info_movie!(&db, 1);
assert_movie!(&db, 1, 1, None, Success);
assert_movie!(&db, 1, 1, None, UniqueViolation);
make_info_movie!(&db, 2);
assert_movie!(&db, 2, 2, Some(2), ForeignKeyViolation);
make_info_collection!(&db, 2);
make_tmdb_collection!(&db, 2, 2);
assert_movie!(&db, 2, 2, Some(2), Success);
assert_movie!(&db, 1, 2, None, UniqueViolation);
assert_movie!(&db, 2, 1, None, UniqueViolation);
make_info_movie!(&db, 3);
assert_movie!(&db, 3, 3, None, Success; tmdb_id);
assert_movie!(&db, 4, 4, None, NotNullViolation; flix_id);
assert_movie!(&db, 5, 5, None, NotNullViolation; last_update);
assert_movie!(&db, 6, 6, None, NotNullViolation; runtime);
assert_movie!(&db, 7, 7, None, ForeignKeyViolation; collection_id);
}
#[tokio::test]
async fn test_round_trip_shows() {
let db = new_initialized_memory_db().await;
macro_rules! assert_show {
($db:expr, $id:literal, $tid:literal, Success $(; $($skip:ident),+)?) => {
let model = assert_show!(@insert, $db, $id, $tid $(; $($skip),+)?)
.expect("insert");
assert_eq!(model.tmdb_id, TmdbShowId::from_raw($tid));
assert_eq!(model.flix_id, ShowId::from_raw($id));
assert_eq!(model.last_update, NaiveDate::from_yo_opt($tid, 1).expect("from_yo_opt").and_hms_opt(0, 0, 0).expect("and_hms_opt").and_utc());
assert_eq!(model.number_of_seasons, $id);
};
($db:expr, $id:literal, $tid:literal, $error:ident $(; $($skip:ident),+)?) => {
let model = assert_show!(@insert, $db, $id, $tid $(; $($skip),+)?)
.expect_err("insert");
assert_eq!(
get_error_kind(model).expect("get_error_kind"),
ErrorKind::$error
);
};
(@insert, $db:expr, $id:literal, $tid:literal $(; $($skip:ident),+)?) => {
super::shows::ActiveModel {
tmdb_id: notsettable!(tmdb_id, TmdbShowId::from_raw($tid) $(, $($skip),+)?),
flix_id: notsettable!(flix_id, ShowId::from_raw($id) $(, $($skip),+)?),
last_update: notsettable!(last_update, NaiveDate::from_yo_opt($tid, 1).expect("from_yo_opt").and_hms_opt(0, 0, 0).expect("and_hms_opt").and_utc() $(, $($skip),+)?),
number_of_seasons: notsettable!(number_of_seasons, $id $(, $($skip),+)?),
}.insert($db).await
};
}
assert_show!(&db, 1, 1, ForeignKeyViolation);
make_info_show!(&db, 1);
assert_show!(&db, 1, 1, Success);
assert_show!(&db, 1, 1, UniqueViolation);
assert_show!(&db, 1, 2, UniqueViolation);
assert_show!(&db, 2, 1, UniqueViolation);
make_info_show!(&db, 2);
assert_show!(&db, 2, 2, Success);
make_info_show!(&db, 3);
assert_show!(&db, 3, 3, Success; tmdb_id);
assert_show!(&db, 4, 4, NotNullViolation; flix_id);
assert_show!(&db, 5, 5, NotNullViolation; last_update);
assert_show!(&db, 6, 6, NotNullViolation; number_of_seasons);
}
#[tokio::test]
async fn test_round_trip_seasons() {
let db = new_initialized_memory_db().await;
macro_rules! assert_season {
($db:expr, $show:literal, $season:literal, $tshow:literal, $tseason:literal, Success $(; $($skip:ident),+)?) => {
let model = assert_season!(@insert, $db, $show, $season, $tshow, $tseason $(; $($skip),+)?)
.expect("insert");
assert_eq!(model.tmdb_show, TmdbShowId::from_raw($tshow));
assert_eq!(model.tmdb_season, ::flix_model::numbers::SeasonNumber::new($tseason));
assert_eq!(model.flix_show, ShowId::from_raw($show));
assert_eq!(model.flix_season, ::flix_model::numbers::SeasonNumber::new($season));
assert_eq!(model.last_update, NaiveDate::from_yo_opt($tshow, 1).expect("from_yo_opt").and_hms_opt(0, 0, 0).expect("and_hms_opt").and_utc());
};
($db:expr, $show:literal, $season:literal, $tshow:literal, $tseason:literal, $error:ident $(; $($skip:ident),+)?) => {
let model = assert_season!(@insert, $db, $show, $season, $tshow, $tseason $(; $($skip),+)?)
.expect_err("insert");
assert_eq!(
get_error_kind(model).expect("get_error_kind"),
ErrorKind::$error
);
};
(@insert, $db:expr, $show:literal, $season:literal, $tshow:literal, $tseason:literal $(; $($skip:ident),+)?) => {
super::seasons::ActiveModel {
tmdb_show: notsettable!(tmdb_show, TmdbShowId::from_raw($tshow) $(, $($skip),+)?),
tmdb_season: notsettable!(tmdb_season, ::flix_model::numbers::SeasonNumber::new($tseason) $(, $($skip),+)?),
flix_show: notsettable!(flix_show, ShowId::from_raw($show) $(, $($skip),+)?),
flix_season: notsettable!(flix_season, ::flix_model::numbers::SeasonNumber::new($season) $(, $($skip),+)?),
last_update: notsettable!(last_update, NaiveDate::from_yo_opt($tshow, 1).expect("from_yo_opt").and_hms_opt(0, 0, 0).expect("and_hms_opt").and_utc() $(, $($skip),+)?),
}.insert($db).await
};
}
make_info_show!(&db, 1);
make_tmdb_show!(&db, 1, 1);
assert_season!(&db, 1, 1, 1, 1, ForeignKeyViolation);
make_info_season!(&db, 1, 1);
assert_season!(&db, 1, 1, 1, 1, Success);
assert_season!(&db, 1, 1, 1, 1, UniqueViolation);
assert_season!(&db, 1, 1, 2, 1, UniqueViolation);
assert_season!(&db, 2, 1, 1, 1, UniqueViolation);
make_info_season!(&db, 1, 2);
assert_season!(&db, 1, 2, 1, 2, Success);
assert_season!(&db, 1, 3, 1, 3, NotNullViolation; tmdb_show);
assert_season!(&db, 1, 4, 1, 4, NotNullViolation; tmdb_season);
assert_season!(&db, 1, 5, 1, 5, NotNullViolation; flix_show);
assert_season!(&db, 1, 6, 1, 6, NotNullViolation; flix_season);
assert_season!(&db, 1, 7, 1, 7, NotNullViolation; last_update);
}
#[tokio::test]
async fn test_round_trip_episodes() {
let db = new_initialized_memory_db().await;
macro_rules! assert_episode {
($db:expr, $show:literal, $season:literal, $episode:literal, $tshow:literal, $tseason:literal, $tepisode:literal, Success $(; $($skip:ident),+)?) => {
let model = assert_episode!(@insert, $db, $show, $season, $episode, $tshow, $tseason, $tepisode $(; $($skip),+)?)
.expect("insert");
assert_eq!(model.tmdb_show, TmdbShowId::from_raw($tshow));
assert_eq!(model.tmdb_season, ::flix_model::numbers::SeasonNumber::new($tseason));
assert_eq!(model.tmdb_episode, ::flix_model::numbers::EpisodeNumber::new($tepisode));
assert_eq!(model.flix_show, ShowId::from_raw($show));
assert_eq!(model.flix_season, ::flix_model::numbers::SeasonNumber::new($season));
assert_eq!(model.flix_episode, ::flix_model::numbers::EpisodeNumber::new($episode));
assert_eq!(model.last_update, NaiveDate::from_yo_opt($tshow, 1).expect("from_yo_opt").and_hms_opt(0, 0, 0).expect("and_hms_opt").and_utc());
assert_eq!(model.runtime, Duration::from_secs($tshow).into());
};
($db:expr, $show:literal, $season:literal, $episode:literal, $tshow:literal, $tseason:literal, $tepisode:literal, $error:ident $(; $($skip:ident),+)?) => {
let model = assert_episode!(@insert, $db, $show, $season, $episode, $tshow, $tseason, $tepisode $(; $($skip),+)?)
.expect_err("insert");
assert_eq!(
get_error_kind(model).expect("get_error_kind"),
ErrorKind::$error
);
};
(@insert, $db:expr, $show:literal, $season:literal, $episode:literal, $tshow:literal, $tseason:literal, $tepisode:literal $(; $($skip:ident),+)?) => {
super::episodes::ActiveModel {
tmdb_show: notsettable!(tmdb_show, TmdbShowId::from_raw($tshow) $(, $($skip),+)?),
tmdb_season: notsettable!(tmdb_season, ::flix_model::numbers::SeasonNumber::new($tseason) $(, $($skip),+)?),
tmdb_episode: notsettable!(tmdb_episode, ::flix_model::numbers::EpisodeNumber::new($tepisode) $(, $($skip),+)?),
flix_show: notsettable!(flix_show, ShowId::from_raw($show) $(, $($skip),+)?),
flix_season: notsettable!(flix_season, ::flix_model::numbers::SeasonNumber::new($season) $(, $($skip),+)?),
flix_episode: notsettable!(flix_episode, ::flix_model::numbers::EpisodeNumber::new($episode) $(, $($skip),+)?),
last_update: notsettable!(last_update, NaiveDate::from_yo_opt($tshow, 1).expect("from_yo_opt").and_hms_opt(0, 0, 0).expect("and_hms_opt").and_utc() $(, $($skip),+)?),
runtime: notsettable!(runtime, Duration::from_secs($tshow).into() $(, $($skip),+)?),
}.insert($db).await
};
}
make_info_show!(&db, 1);
make_info_season!(&db, 1, 1);
make_tmdb_show!(&db, 1, 1);
make_tmdb_season!(&db, 1, 1, 1, 1);
assert_episode!(&db, 1, 1, 1, 1, 1, 1, ForeignKeyViolation);
make_info_episode!(&db, 1, 1, 1);
assert_episode!(&db, 1, 1, 1, 1, 1, 1, Success);
assert_episode!(&db, 1, 1, 1, 1, 1, 1, UniqueViolation);
assert_episode!(&db, 1, 1, 1, 1, 2, 1, UniqueViolation);
assert_episode!(&db, 1, 1, 1, 2, 1, 1, UniqueViolation);
assert_episode!(&db, 1, 2, 1, 1, 1, 1, UniqueViolation);
assert_episode!(&db, 2, 1, 1, 1, 1, 1, UniqueViolation);
make_info_episode!(&db, 1, 1, 2);
assert_episode!(&db, 1, 1, 2, 1, 1, 2, Success);
assert_episode!(&db, 1, 1, 3, 1, 1, 3, NotNullViolation; tmdb_show);
assert_episode!(&db, 1, 1, 3, 1, 1, 4, NotNullViolation; tmdb_season);
assert_episode!(&db, 1, 1, 3, 1, 1, 5, NotNullViolation; tmdb_episode);
assert_episode!(&db, 1, 1, 3, 1, 1, 6, NotNullViolation; flix_show);
assert_episode!(&db, 1, 1, 3, 1, 1, 7, NotNullViolation; flix_season);
assert_episode!(&db, 1, 1, 3, 1, 1, 8, NotNullViolation; flix_episode);
assert_episode!(&db, 1, 1, 3, 1, 1, 9, NotNullViolation; last_update);
assert_episode!(&db, 1, 1, 3, 1, 1, 10, NotNullViolation; runtime);
}
}
+579
View File
@@ -0,0 +1,579 @@
//! This module contains entities for storing watched information
/// Collection entity
pub mod collections {
use flix_model::id::{CollectionId, RawId};
use chrono::{DateTime, Utc};
use sea_orm::entity::prelude::*;
use crate::entity;
/// The database representation of a watched movie
#[sea_orm::model]
#[derive(Debug, Clone, DeriveEntityModel)]
#[sea_orm(table_name = "flix_watched_collections")]
pub struct Model {
/// The collection's ID
#[sea_orm(primary_key, auto_increment = false)]
pub id: CollectionId,
/// The user's ID
#[sea_orm(primary_key, auto_increment = false)]
pub user_id: RawId,
/// The date this collection was watched
pub watched_date: DateTime<Utc>,
/// The info for this collection
#[sea_orm(
belongs_to,
relation_enum = "Info",
from = "id",
to = "id",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub info: HasOne<entity::info::collections::Entity>,
/// The content for this collection
#[sea_orm(belongs_to, relation_enum = "Content", from = "id", to = "id", skip_fk)]
pub content: HasOne<entity::content::collections::Entity>,
}
impl ActiveModelBehavior for ActiveModel {}
}
/// Movie entity
pub mod movies {
use flix_model::id::{MovieId, RawId};
use chrono::{DateTime, Utc};
use sea_orm::entity::prelude::*;
use crate::entity;
/// The database representation of a watched movie
#[sea_orm::model]
#[derive(Debug, Clone, DeriveEntityModel)]
#[sea_orm(table_name = "flix_watched_movies")]
pub struct Model {
/// The movie's ID
#[sea_orm(primary_key, auto_increment = false)]
pub id: MovieId,
/// The user's ID
#[sea_orm(primary_key, auto_increment = false)]
pub user_id: RawId,
/// The date this movie was watched
pub watched_date: DateTime<Utc>,
/// The info for this movie
#[sea_orm(
belongs_to,
from = "id",
to = "id",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub info: HasOne<entity::info::movies::Entity>,
/// The content for this movie
#[sea_orm(belongs_to, relation_enum = "Content", from = "id", to = "id", skip_fk)]
pub content: HasOne<entity::content::movies::Entity>,
}
impl ActiveModelBehavior for ActiveModel {}
}
/// Show entity
pub mod shows {
use flix_model::id::{RawId, ShowId};
use chrono::{DateTime, Utc};
use sea_orm::entity::prelude::*;
use crate::entity;
/// The database representation of a watched movie
#[sea_orm::model]
#[derive(Debug, Clone, DeriveEntityModel)]
#[sea_orm(table_name = "flix_watched_shows")]
pub struct Model {
/// The show's ID
#[sea_orm(primary_key, auto_increment = false)]
pub id: ShowId,
/// The user's ID
#[sea_orm(primary_key, auto_increment = false)]
pub user_id: RawId,
/// The date this show was watched
pub watched_date: DateTime<Utc>,
/// The info for this show
#[sea_orm(
belongs_to,
relation_enum = "Info",
from = "id",
to = "id",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub info: HasOne<entity::info::shows::Entity>,
/// The content for this show
#[sea_orm(belongs_to, relation_enum = "Content", from = "id", to = "id", skip_fk)]
pub content: HasOne<entity::content::shows::Entity>,
}
impl ActiveModelBehavior for ActiveModel {}
}
/// Season entity
pub mod seasons {
use flix_model::id::{RawId, ShowId};
use flix_model::numbers::SeasonNumber;
use chrono::{DateTime, Utc};
use sea_orm::entity::prelude::*;
use crate::entity;
/// The database representation of a watched movie
#[sea_orm::model]
#[derive(Debug, Clone, DeriveEntityModel)]
#[sea_orm(table_name = "flix_watched_seasons")]
pub struct Model {
/// The season's show's ID
#[sea_orm(primary_key, auto_increment = false)]
pub show_id: ShowId,
/// The season's number
#[sea_orm(primary_key, auto_increment = false)]
pub season_number: SeasonNumber,
/// The user's ID
#[sea_orm(primary_key, auto_increment = false)]
pub user_id: RawId,
/// The date this season was watched
pub watched_date: DateTime<Utc>,
/// The info for this season
#[sea_orm(
belongs_to,
relation_enum = "Info",
from = "(show_id, season_number)",
to = "(show_id, season_number)",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub info: HasOne<entity::info::seasons::Entity>,
/// The content for this season
#[sea_orm(
belongs_to,
relation_enum = "Content",
from = "(show_id, season_number)",
to = "(show_id, season_number)",
skip_fk
)]
pub content: HasOne<entity::content::seasons::Entity>,
}
impl ActiveModelBehavior for ActiveModel {}
}
/// Episode entity
pub mod episodes {
use flix_model::id::{RawId, ShowId};
use flix_model::numbers::{EpisodeNumber, SeasonNumber};
use chrono::{DateTime, Utc};
use sea_orm::entity::prelude::*;
use crate::entity;
/// The database representation of a watched movie
#[sea_orm::model]
#[derive(Debug, Clone, DeriveEntityModel)]
#[sea_orm(table_name = "flix_watched_episodes")]
pub struct Model {
/// The episode's show's ID
#[sea_orm(primary_key, auto_increment = false)]
pub show_id: ShowId,
/// The episode's season's number
#[sea_orm(primary_key, auto_increment = false)]
pub season_number: SeasonNumber,
/// The episode's number
#[sea_orm(primary_key, auto_increment = false)]
pub episode_number: EpisodeNumber,
/// The user's ID
#[sea_orm(primary_key, auto_increment = false)]
pub user_id: RawId,
/// The date this episode was watched
pub watched_date: DateTime<Utc>,
/// The info for this episode
#[sea_orm(
belongs_to,
relation_enum = "Info",
from = "(show_id, season_number, episode_number)",
to = "(show_id, season_number, episode_number)",
on_update = "Cascade",
on_delete = "Cascade"
)]
pub info: HasOne<entity::info::episodes::Entity>,
/// The content for this episode
#[sea_orm(
belongs_to,
relation_enum = "Content",
from = "(show_id, season_number, episode_number)",
to = "(show_id, season_number, episode_number)",
skip_fk
)]
pub content: HasOne<entity::content::episodes::Entity>,
}
impl ActiveModelBehavior for ActiveModel {}
}
/// Macros for creating watched entities
#[cfg(test)]
pub mod test {
macro_rules! make_watched_movie {
($db:expr, $id:expr, $user:expr) => {
$crate::entity::watched::movies::ActiveModel {
id: Set(::flix_model::id::MovieId::from_raw($id)),
user_id: Set($user),
watched_date: Set(::chrono::Utc::now()),
}
.insert($db)
.await
.expect("insert");
};
}
pub(crate) use make_watched_movie;
macro_rules! make_watched_episode {
($db:expr, $show:expr, $season:expr, $episode:expr, $user:expr) => {
$crate::entity::watched::episodes::ActiveModel {
show_id: Set(::flix_model::id::ShowId::from_raw($show)),
season_number: Set(::flix_model::numbers::SeasonNumber::new($season)),
episode_number: Set(::flix_model::numbers::EpisodeNumber::new($episode)),
user_id: Set($user),
watched_date: Set(::chrono::Utc::now()),
}
.insert($db)
.await
.expect("insert");
};
}
pub(crate) use make_watched_episode;
}
#[cfg(test)]
mod tests {
use flix_model::id::{MovieId, ShowId};
use chrono::NaiveDate;
use sea_orm::ActiveValue::{NotSet, Set};
use sea_orm::Condition;
use sea_orm::entity::prelude::*;
use sea_orm::sqlx::error::ErrorKind;
use crate::entity::content::test::{
make_content_collection, make_content_episode, make_content_library, make_content_movie,
make_content_season, make_content_show,
};
use crate::entity::info::test::{
make_info_episode, make_info_movie, make_info_season, make_info_show,
};
use crate::tests::new_initialized_memory_db;
use super::super::tests::get_error_kind;
use super::super::tests::notsettable;
use super::test::{make_watched_episode, make_watched_movie};
#[tokio::test]
async fn use_test_macros() {
let db = new_initialized_memory_db().await;
make_info_movie!(&db, 1);
make_info_show!(&db, 1);
make_info_season!(&db, 1, 1);
make_info_episode!(&db, 1, 1, 1);
make_watched_movie!(&db, 1, 1);
make_watched_episode!(&db, 1, 1, 1, 1);
}
#[tokio::test]
async fn test_round_trip_movies() {
let db = new_initialized_memory_db().await;
macro_rules! assert_movie {
($db:expr, $id:literal, $uid:literal, Success $(; $($skip:ident),+)?) => {
let model = assert_movie!(@insert, $db, $id, $uid $(; $($skip),+)?)
.expect("insert");
assert_eq!(model.id, MovieId::from_raw($id));
assert_eq!(model.user_id, $uid);
assert_eq!(model.watched_date, NaiveDate::from_yo_opt($uid, 1).expect("from_yo_opt").and_hms_opt(0, 0, 0).expect("and_hms_opt").and_utc());
};
($db:expr, $id:literal, $uid:literal, $error:ident $(; $($skip:ident),+)?) => {
let model = assert_movie!(@insert, $db, $id, $uid $(; $($skip),+)?)
.expect_err("insert");
assert_eq!(get_error_kind(model).expect("get_error_kind"), ErrorKind::$error);
};
(@insert, $db:expr, $id:literal, $uid:literal $(; $($skip:ident),+)?) => {
super::movies::ActiveModel {
id: notsettable!(id, MovieId::from_raw($id) $(, $($skip),+)?),
user_id: notsettable!(user_id, $uid $(, $($skip),+)?),
watched_date: notsettable!(watched_date, NaiveDate::from_yo_opt($uid, 1).expect("from_yo_opt").and_hms_opt(0, 0, 0).expect("and_hms_opt").and_utc() $(, $($skip),+)?),
}.insert($db).await
};
}
assert_movie!(&db, 1, 1, ForeignKeyViolation);
make_info_movie!(&db, 1);
assert_movie!(&db, 1, 1, Success);
assert_movie!(&db, 1, 2, Success);
assert_movie!(&db, 1, 1, UniqueViolation);
make_info_movie!(&db, 2);
assert_movie!(&db, 2, 1, Success);
assert_movie!(&db, 2, 2, Success);
assert_movie!(&db, 3, 1, NotNullViolation; id);
assert_movie!(&db, 4, 1, NotNullViolation; user_id);
assert_movie!(&db, 5, 1, NotNullViolation; watched_date);
}
#[tokio::test]
async fn test_round_trip_episodes() {
let db = new_initialized_memory_db().await;
macro_rules! assert_episode {
($db:expr, $show:literal, $season:literal, $episode:literal, $uid:literal, Success $(; $($skip:ident),+)?) => {
let model = assert_episode!(@insert, $db, $show, $season, $episode, $uid $(; $($skip),+)?)
.expect("insert");
assert_eq!(model.show_id, ShowId::from_raw($show));
assert_eq!(model.season_number, ::flix_model::numbers::SeasonNumber::new($season));
assert_eq!(model.episode_number, ::flix_model::numbers::EpisodeNumber::new($episode));
assert_eq!(model.user_id, $uid);
assert_eq!(model.watched_date, NaiveDate::from_yo_opt($uid, 1).expect("from_yo_opt").and_hms_opt(0, 0, 0).expect("and_hms_opt").and_utc());
};
($db:expr, $show:literal, $season:literal, $episode:literal, $uid:literal, $error:ident $(; $($skip:ident),+)?) => {
let model = assert_episode!(@insert, $db, $show, $season, $episode, $uid $(; $($skip),+)?)
.expect_err("insert");
assert_eq!(get_error_kind(model).expect("get_error_kind"), ErrorKind::$error);
};
(@insert, $db:expr, $show:literal, $season:literal, $episode:literal, $uid:literal $(; $($skip:ident),+)?) => {
super::episodes::ActiveModel {
show_id: notsettable!(show_id, ShowId::from_raw($show) $(, $($skip),+)?),
season_number: notsettable!(season_number, ::flix_model::numbers::SeasonNumber::new($season) $(, $($skip),+)?),
episode_number: notsettable!(episode_number, ::flix_model::numbers::EpisodeNumber::new($episode) $(, $($skip),+)?),
user_id: notsettable!(user_id, $uid $(, $($skip),+)?),
watched_date: notsettable!(watched_date, NaiveDate::from_yo_opt($uid, 1).expect("from_yo_opt").and_hms_opt(0, 0, 0).expect("and_hms_opt").and_utc() $(, $($skip),+)?),
}.insert($db).await
};
}
make_info_show!(&db, 1);
make_info_season!(&db, 1, 1);
make_info_show!(&db, 2);
make_info_season!(&db, 2, 1);
assert_episode!(&db, 1, 1, 1, 1, ForeignKeyViolation);
assert_episode!(&db, 2, 1, 1, 1, ForeignKeyViolation);
make_info_episode!(&db, 1, 1, 1);
make_info_episode!(&db, 2, 1, 1);
assert_episode!(&db, 1, 1, 1, 1, Success);
assert_episode!(&db, 1, 1, 1, 2, Success);
assert_episode!(&db, 2, 1, 1, 1, Success);
assert_episode!(&db, 1, 1, 1, 1, UniqueViolation);
assert_episode!(&db, 3, 1, 1, 1, NotNullViolation; show_id);
assert_episode!(&db, 4, 1, 1, 1, NotNullViolation; season_number);
assert_episode!(&db, 5, 1, 1, 1, NotNullViolation; episode_number);
assert_episode!(&db, 6, 1, 1, 1, NotNullViolation; user_id);
assert_episode!(&db, 7, 1, 1, 1, NotNullViolation; watched_date);
}
#[tokio::test]
async fn test_query_seasons() {
let db = new_initialized_memory_db().await;
macro_rules! assert_season {
($db:expr, $show:literal, $season:literal, $uid:literal, Watched) => {
assert_season!(@find, $db, $show, $season, $uid)
.ok_or(())
.expect("is none");
};
($db:expr, $show:literal, $season:literal, $uid:literal, Unwatched) => {
assert_season!(@find, $db, $show, $season, $uid)
.ok_or(())
.expect_err("is some");
};
(@find, $db:expr, $show:literal, $season:literal, $uid:literal) => {
super::seasons::Entity::find()
.filter(
Condition::all()
.add(super::seasons::Column::ShowId.eq($show))
.add(super::seasons::Column::SeasonNumber.eq($season))
.add(super::seasons::Column::UserId.eq($uid)),
)
.one(&db)
.await
.expect("find.filter.one")
};
}
make_content_library!(&db, 1);
make_content_show!(&db, 1, 1, None);
make_content_season!(&db, 1, 1, 1);
assert_season!(&db, 1, 1, 1, Unwatched);
make_content_episode!(&db, 1, 1, 1, 1);
assert_season!(&db, 1, 1, 1, Unwatched);
make_watched_episode!(&db, 1, 1, 1, 1);
assert_season!(&db, 1, 1, 1, Watched);
assert_season!(&db, 1, 1, 2, Unwatched);
make_content_episode!(&db, 1, 1, 1, 2);
assert_season!(&db, 1, 1, 1, Unwatched);
make_content_season!(&db, 1, 1, 2);
make_content_episode!(&db, 1, 1, 2, 1);
make_content_episode!(&db, 1, 1, 2, 2, >1);
make_info_episode!(&db, 1, 2, 3);
make_content_episode!(&db, 1, 1, 2, 4);
assert_season!(&db, 1, 2, 1, Unwatched);
assert_season!(&db, 1, 2, 2, Unwatched);
assert_season!(&db, 1, 2, 3, Unwatched);
make_watched_episode!(&db, 1, 2, 1, 1);
make_watched_episode!(&db, 1, 2, 1, 2);
make_watched_episode!(&db, 1, 2, 2, 3);
assert_season!(&db, 1, 2, 1, Unwatched);
assert_season!(&db, 1, 2, 2, Unwatched);
assert_season!(&db, 1, 2, 3, Unwatched);
make_watched_episode!(&db, 1, 2, 2, 1);
make_watched_episode!(&db, 1, 2, 2, 2);
make_watched_episode!(&db, 1, 2, 1, 3);
assert_season!(&db, 1, 2, 1, Unwatched);
assert_season!(&db, 1, 2, 2, Unwatched);
assert_season!(&db, 1, 2, 3, Unwatched);
make_watched_episode!(&db, 1, 2, 4, 1);
assert_season!(&db, 1, 2, 1, Watched);
assert_season!(&db, 1, 2, 2, Unwatched);
assert_season!(&db, 1, 2, 3, Unwatched);
}
#[tokio::test]
async fn test_query_shows() {
let db = new_initialized_memory_db().await;
macro_rules! assert_show {
($db:expr, $show:literal, $uid:literal, Watched) => {
assert_show!(@find, $db, $show, $uid)
.ok_or(())
.expect("is none");
};
($db:expr, $show:literal, $uid:literal, Unwatched) => {
assert_show!(@find, $db, $show, $uid)
.ok_or(())
.expect_err("is some");
};
(@find, $db:expr, $show:literal, $uid:literal) => {
super::shows::Entity::find()
.filter(
Condition::all()
.add(super::shows::Column::Id.eq($show))
.add(super::shows::Column::UserId.eq($uid)),
)
.one(&db)
.await
.expect("find.filter.one")
};
}
make_content_library!(&db, 1);
make_content_show!(&db, 1, 1, None);
assert_show!(&db, 1, 1, Unwatched);
make_content_season!(&db, 1, 1, 1);
assert_show!(&db, 1, 1, Unwatched);
make_content_episode!(&db, 1, 1, 1, 1);
assert_show!(&db, 1, 1, Unwatched);
make_watched_episode!(&db, 1, 1, 1, 1);
assert_show!(&db, 1, 1, Watched);
assert_show!(&db, 1, 2, Unwatched);
make_content_episode!(&db, 1, 1, 1, 2);
assert_show!(&db, 1, 1, Unwatched);
assert_show!(&db, 1, 2, Unwatched);
make_watched_episode!(&db, 1, 1, 2, 1);
make_content_season!(&db, 1, 1, 2);
assert_show!(&db, 1, 1, Unwatched);
assert_show!(&db, 1, 2, Unwatched);
make_content_episode!(&db, 1, 1, 2, 1);
assert_show!(&db, 1, 1, Unwatched);
assert_show!(&db, 1, 2, Unwatched);
make_watched_episode!(&db, 1, 2, 1, 1);
assert_show!(&db, 1, 1, Watched);
assert_show!(&db, 1, 2, Unwatched);
}
#[tokio::test]
async fn test_query_collections() {
let db = new_initialized_memory_db().await;
macro_rules! assert_collection {
($db:expr, $id:literal, $uid:literal, Watched) => {
assert_collection!(@find, $db, $id, $uid)
.ok_or(())
.expect("is none");
};
($db:expr, $id:literal, $uid:literal, Unwatched) => {
assert_collection!(@find, $db, $id, $uid)
.ok_or(())
.expect_err("is some");
};
(@find, $db:expr, $id:literal, $uid:literal) => {
super::collections::Entity::find()
.filter(
Condition::all()
.add(super::collections::Column::Id.eq($id))
.add(super::collections::Column::UserId.eq($uid)),
)
.one(&db)
.await
.expect("find.filter.one")
};
}
make_content_library!(&db, 1);
make_content_collection!(&db, 1, 1, None);
assert_collection!(&db, 1, 1, Unwatched);
make_content_movie!(&db, 1, 1, Some(1));
assert_collection!(&db, 1, 1, Unwatched);
make_info_movie!(&db, 9999);
make_watched_movie!(&db, 9999, 1);
assert_collection!(&db, 1, 1, Unwatched);
make_watched_movie!(&db, 1, 1);
assert_collection!(&db, 1, 1, Watched);
make_content_collection!(&db, 1, 2, Some(1));
assert_collection!(&db, 1, 1, Watched);
assert_collection!(&db, 2, 1, Unwatched);
make_content_movie!(&db, 1, 2, Some(2));
assert_collection!(&db, 1, 1, Unwatched);
assert_collection!(&db, 2, 1, Unwatched);
make_watched_movie!(&db, 2, 1);
assert_collection!(&db, 1, 1, Watched);
assert_collection!(&db, 2, 1, Watched);
make_content_show!(&db, 1, 1, Some(2));
assert_collection!(&db, 1, 1, Unwatched);
assert_collection!(&db, 2, 1, Unwatched);
make_content_season!(&db, 1, 1, 1);
make_content_episode!(&db, 1, 1, 1, 1);
make_watched_episode!(&db, 1, 1, 1, 1);
assert_collection!(&db, 1, 1, Watched);
assert_collection!(&db, 2, 1, Watched);
}
}
+26
View File
@@ -0,0 +1,26 @@
//! flix-db provides types for storing persistent data about media
#![cfg_attr(docsrs, feature(doc_cfg))]
pub mod connection;
pub mod entity;
pub mod migration;
#[cfg(test)]
mod tests {
use sea_orm::{ConnectOptions, Database, DatabaseConnection};
use crate::connection::Connection;
pub async fn new_initialized_memory_db() -> DatabaseConnection {
let options = ConnectOptions::new("sqlite::memory:");
let db = Database::connect(options)
.await
.expect("Database::connect()");
let connection = Connection::try_from(db)
.await
.expect("Connection::try_from");
connection.take()
}
}
+34
View File
@@ -0,0 +1,34 @@
//! Adds watched views:
//! - Collections
//! - Shows
//! - Seasons
use sea_orm::{DbErr, DeriveMigrationName};
use sea_orm_migration::async_trait;
use sea_orm_migration::{MigrationTrait, SchemaManager};
mod collections;
mod seasons;
mod shows;
#[derive(DeriveMigrationName)]
pub(super) struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
seasons::up(manager).await?;
shows::up(manager).await?;
collections::up(manager).await?;
Ok(())
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
collections::down(manager).await?;
shows::down(manager).await?;
seasons::down(manager).await?;
Ok(())
}
}
@@ -0,0 +1,104 @@
use sea_orm::prelude::*;
use sea_orm::sea_query::Table;
use sea_orm::{ConnectionTrait, DbBackend, Statement};
use sea_orm_migration::prelude::*;
pub async fn up(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table("flix_watched_collections").to_owned())
.await?;
manager
.get_connection()
.execute_raw(Statement::from_string(
DbBackend::Sqlite,
r#"
CREATE VIEW flix_watched_collections AS
WITH RECURSIVE
watched_items AS (
SELECT
w.id,
w.user_id,
w.watched_date,
'movie' AS type
FROM flix_watched_movies w
UNION ALL
SELECT
w.id,
w.user_id,
w.watched_date,
'show' AS type
FROM flix_watched_shows w
),
collection_items AS (
SELECT
m.parent_id,
m.id,
'movie' AS type
FROM flix_movies m
WHERE m.parent_id IS NOT NULL
UNION ALL
SELECT
s.parent_id,
s.id,
'show' AS type
FROM flix_shows s
WHERE s.parent_id IS NOT NULL
UNION ALL
SELECT
c.parent_id,
ci.id,
ci.type
FROM collection_items ci
JOIN flix_collections c
ON c.id = ci.parent_id
)
SELECT
ci.parent_id AS id,
wi.user_id,
MAX(wi.watched_date) AS watched_date
FROM collection_items ci
JOIN watched_items wi
ON wi.id = ci.id
AND wi.type = ci.type
WHERE NOT EXISTS (
SELECT 1
FROM collection_items ci2
WHERE ci2.parent_id = ci.parent_id
AND NOT EXISTS (
SELECT 1
FROM watched_items wi2
WHERE wi2.id = ci2.id
AND wi2.type = ci2.type
AND wi2.user_id = wi.user_id
)
)
GROUP BY ci.parent_id, wi.user_id
;
"#,
))
.await?;
Ok(())
}
pub async fn down(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
manager
.get_connection()
.execute_raw(Statement::from_string(
DbBackend::Sqlite,
r#"
DROP VIEW flix_watched_collections
;
"#,
))
.await?;
Ok(())
}
@@ -0,0 +1,59 @@
use sea_orm::prelude::*;
use sea_orm::sea_query::Table;
use sea_orm::{ConnectionTrait, DbBackend, Statement};
use sea_orm_migration::prelude::*;
pub async fn up(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table("flix_watched_seasons").to_owned())
.await?;
manager
.get_connection()
.execute_raw(Statement::from_string(
DbBackend::Sqlite,
r#"
CREATE VIEW flix_watched_seasons AS
SELECT
w.show_id,
w.season_number,
w.user_id,
MAX(w.watched_date) AS watched_date
FROM flix_watched_episodes w
WHERE NOT EXISTS (
SELECT 1
FROM flix_episodes e
WHERE e.show_id = w.show_id
AND e.season_number = w.season_number
AND NOT EXISTS (
SELECT 1
FROM flix_watched_episodes wc
WHERE wc.show_id = e.show_id
AND wc.season_number = e.season_number
AND wc.episode_number = e.episode_number
AND wc.user_id = w.user_id
)
)
GROUP BY w.show_id, w.season_number, w.user_id
;
"#,
))
.await?;
Ok(())
}
pub async fn down(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
manager
.get_connection()
.execute_raw(Statement::from_string(
DbBackend::Sqlite,
r#"
DROP VIEW flix_watched_seasons
;
"#,
))
.await?;
Ok(())
}
+56
View File
@@ -0,0 +1,56 @@
use sea_orm::prelude::*;
use sea_orm::sea_query::Table;
use sea_orm::{ConnectionTrait, DbBackend, Statement};
use sea_orm_migration::prelude::*;
pub async fn up(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table("flix_watched_shows").to_owned())
.await?;
manager
.get_connection()
.execute_raw(Statement::from_string(
DbBackend::Sqlite,
r#"
CREATE VIEW flix_watched_shows AS
SELECT
w.show_id as id,
w.user_id,
MAX(w.watched_date) AS watched_date
FROM flix_watched_seasons w
WHERE NOT EXISTS (
SELECT 1
FROM flix_seasons s
WHERE s.show_id = w.show_id
AND NOT EXISTS (
SELECT 1
FROM flix_watched_seasons wc
WHERE wc.show_id = s.show_id
AND wc.season_number = s.season_number
AND wc.user_id = w.user_id
)
)
GROUP BY w.show_id, w.user_id
;
"#,
))
.await?;
Ok(())
}
pub async fn down(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
manager
.get_connection()
.execute_raw(Statement::from_string(
DbBackend::Sqlite,
r#"
DROP VIEW flix_watched_shows
;
"#,
))
.await?;
Ok(())
}
+6
View File
@@ -0,0 +1,6 @@
//! Migrations for maintaining the database schema
seamantic::migrations! {
"seaql_migrations_flix";
m_000001,
}
+19 -17
View File
@@ -1,26 +1,28 @@
[package] [package]
name = "flix" name = "flix"
version = "0.0.8" version = "0.0.16"
categories = []
description = "Types for storing persistent data about media"
repository = "https://github.com/QuantumShade/flix"
authors.workspace = true
edition.workspace = true edition.workspace = true
license-file.workspace = true
rust-version.workspace = true rust-version.workspace = true
description = "Mechanisms for interacting with flix media"
repository = "https://github.com/QuantumShade/flix"
license-file.workspace = true
categories = []
[lints] [package.metadata.docs.rs]
workspace = true all-features = true
rustdoc-args = ["--cfg", "docsrs"]
[dependencies]
flix-db = { workspace = true }
flix-fs = { workspace = true, optional = true }
flix-model = { workspace = true }
flix-tmdb = { workspace = true, optional = true }
[features] [features]
default = [] default = []
tmdb = ["dep:flix-tmdb"] fs = ["dep:flix-fs"]
serde = ["flix-model/serde"]
tmdb = ["dep:flix-tmdb", "flix-db/tmdb"]
[dependencies] [lints]
flix-tmdb = { workspace = true, optional = true } workspace = true
chrono = { workspace = true, features = ["serde"] }
serde = { workspace = true, features = ["std", "derive"] }
thiserror = { workspace = true }
+1 -1
View File
@@ -2,4 +2,4 @@
[![Crates Version](https://img.shields.io/crates/v/flix.svg)](https://crates.io/crates/flix) [![Crates Version](https://img.shields.io/crates/v/flix.svg)](https://crates.io/crates/flix)
A library providing types for storing persistent data about media A library for interacting with flix media
+12 -3
View File
@@ -1,4 +1,13 @@
//! flix provides types for storing persistent data about media //! flix provides mechanisms for interacting with flix media
/// flix types #![cfg_attr(docsrs, feature(doc_cfg))]
pub mod model;
pub use flix_db as db;
pub use flix_model as model;
#[cfg(feature = "fs")]
#[cfg_attr(docsrs, doc(cfg(feature = "fs")))]
pub use flix_fs as fs;
#[cfg(feature = "tmdb")]
#[cfg_attr(docsrs, doc(cfg(feature = "tmdb")))]
pub use flix_tmdb as tmdb;
-30
View File
@@ -1,30 +0,0 @@
#[cfg(feature = "tmdb")]
use flix_tmdb::model::CollectionId;
/// A Collection container
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct Collection {
/// Generic collection data
pub collection: GenericCollection,
/// TMDB collection data
#[cfg(feature = "tmdb")]
pub tmdb: Option<TmdbCollection>,
}
/// The generic collection data
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct GenericCollection {
/// The collection's title
pub title: String,
/// The collection's overview
pub overview: String,
}
/// The TMDB collection data
#[cfg(feature = "tmdb")]
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TmdbCollection {
/// The collection's TMDB ID
pub id: CollectionId,
}
-73
View File
@@ -1,73 +0,0 @@
#[cfg(feature = "tmdb")]
use flix_tmdb::model::ShowId;
use chrono::NaiveDate;
/// An Episode container
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct Episode {
/// The generic episode data
pub episode: GenericEpisode,
/// The TMDB episode data
#[cfg(feature = "tmdb")]
pub tmdb: Option<TmdbEpisode>,
}
/// A wrapper for handling single and multi-episode entries
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
pub enum EpisodeNumber {
/// The entry contains a single episode
Single {
/// The episode's number
number: u32,
},
/// The entry contains multiple episodes
Multiple {
/// The list of episode numbers
numbers: Vec<u32>,
},
}
impl EpisodeNumber {
/// Get the primary episode number of this episode
pub fn primary_episode_number(&self) -> Option<u32> {
match self {
EpisodeNumber::Single { number } => Some(*number),
EpisodeNumber::Multiple { numbers } => numbers.first().copied(),
}
}
/// Get additional episode numbers of this episode
pub fn additional_episode_numbers(&self) -> Vec<u32> {
match self {
EpisodeNumber::Single { number: _ } => vec![],
EpisodeNumber::Multiple { numbers } => numbers.iter().skip(1).copied().collect(),
}
}
}
/// The generic episode data
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct GenericEpisode {
/// The episode's number(s)
#[serde(flatten)]
pub number: EpisodeNumber,
/// The episode's season's number
pub season: u32,
/// The episode's title
pub title: String,
/// The episode's overview
pub overview: String,
/// The episode's air date
pub air_date: NaiveDate,
}
/// The TMDB show data
#[cfg(feature = "tmdb")]
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TmdbEpisode {
/// The episodes's show's TMDB ID
pub show_id: ShowId,
}
-13
View File
@@ -1,13 +0,0 @@
mod collection;
mod episode;
mod movie;
mod season;
mod show;
mod verse;
pub use collection::*;
pub use episode::*;
pub use movie::*;
pub use season::*;
pub use show::*;
pub use verse::*;
-38
View File
@@ -1,38 +0,0 @@
#[cfg(feature = "tmdb")]
use flix_tmdb::model::{MovieGenreId, MovieId};
use chrono::NaiveDate;
/// A Movie container
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct Movie {
/// The generic movie data
pub movie: GenericMovie,
/// The TMDB movie data
#[cfg(feature = "tmdb")]
pub tmdb: Option<TmdbMovie>,
}
/// The generic movie data
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct GenericMovie {
/// The movie's title
pub title: String,
/// The movie's overview
pub overview: String,
/// The movie's genres
pub genres: Vec<String>,
/// The movie's release date
pub release_date: NaiveDate,
}
/// The TMDB movie data
#[cfg(feature = "tmdb")]
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TmdbMovie {
/// The movie's TMDB ID
pub id: MovieId,
/// The list of genre TMDB IDs that the movie is associated with
pub genres: Vec<MovieGenreId>,
}
-36
View File
@@ -1,36 +0,0 @@
#[cfg(feature = "tmdb")]
use flix_tmdb::model::ShowId;
use chrono::NaiveDate;
/// A Season container
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct Season {
/// The generic season data
pub season: GenericSeason,
/// The TMDB season data
#[cfg(feature = "tmdb")]
pub tmdb: Option<TmdbSeason>,
}
/// The generic season data
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct GenericSeason {
/// The season's number
pub number: u32,
/// The season's title
pub title: String,
/// The season's overview
pub overview: String,
/// The season's air date
pub air_date: NaiveDate,
}
/// The TMDB show data
#[cfg(feature = "tmdb")]
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TmdbSeason {
/// The season's show's TMDB ID
pub show_id: ShowId,
}
-38
View File
@@ -1,38 +0,0 @@
#[cfg(feature = "tmdb")]
use flix_tmdb::model::{ShowGenreId, ShowId};
use chrono::NaiveDate;
/// A Show container
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct Show {
/// The generic show data
pub show: GenericShow,
/// The TMDB show data
#[cfg(feature = "tmdb")]
pub tmdb: Option<TmdbShow>,
}
/// The generic show data
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct GenericShow {
/// The show's title
pub title: String,
/// The show's overview
pub overview: String,
/// The show's genres
pub genres: Vec<String>,
/// The show's air date
pub air_date: NaiveDate,
}
/// The TMDB show data
#[cfg(feature = "tmdb")]
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TmdbShow {
/// The show's TMDB ID
pub id: ShowId,
/// The list of genre TMDB IDs that the movie is associated with
pub genres: Vec<ShowGenreId>,
}
-40
View File
@@ -1,40 +0,0 @@
#[cfg(feature = "tmdb")]
use flix_tmdb::model::{CollectionId, MovieId, ShowId};
/// A Verse container
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct Verse {
/// The generic verse data
pub verse: GenericVerse,
/// The TMDB verse data
#[cfg(feature = "tmdb")]
pub tmdb: Option<TmdbVerse>,
}
/// The generic verse data
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct GenericVerse {
/// The verse's title
pub title: String,
/// The verse's overview
pub overview: String,
}
/// The TMDB verse data
#[cfg(feature = "tmdb")]
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TmdbVerse {
/// The list of collection TMDB IDs in the verse
#[serde(default)]
pub collections: Vec<CollectionId>,
/// The list of movie TMDB IDs in the verse
#[serde(default)]
pub movies: Vec<MovieId>,
/// The list of show TMDB IDs in the verse
#[serde(default)]
pub shows: Vec<ShowId>,
/// The list of sub-verse names
#[serde(default)]
pub verses: Vec<String>,
}
+24
View File
@@ -0,0 +1,24 @@
[package]
name = "flix-fs"
version = "0.0.16"
edition.workspace = true
rust-version.workspace = true
description = "Filesystem scanner for flix media"
repository = "https://github.com/QuantumShade/flix"
license-file.workspace = true
categories = []
[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]
[dependencies]
async-stream = { workspace = true }
flix-model = { workspace = true }
regex = { workspace = true, features = ["perf", "std"] }
thiserror = { workspace = true }
tokio = { workspace = true }
tokio-stream = { workspace = true, features = ["fs"] }
[lints]
workspace = true
+5
View File
@@ -0,0 +1,5 @@
# flix-fs
[![Crates Version](https://img.shields.io/crates/v/flix-fs.svg)](https://crates.io/crates/flix-fs)
A library providing filesystem scanners for flix media
+39
View File
@@ -0,0 +1,39 @@
use std::io;
/// The error type for filesystem scanning operations.
#[derive(Debug, thiserror::Error)]
pub enum Error {
/// fs::read_dir failed
#[error("fs::read_dir: {0}")]
ReadDir(io::Error),
/// fs::read_dir::next_entry failed
#[error("fs::read_dir::next_entry: {0}")]
ReadDirEntry(io::Error),
/// fs::read_dir::file_type failed
#[error("fs::read_dir::file_type: {0}")]
FileType(io::Error),
/// There is an unexpected file in the directory
#[error("unexpected file")]
UnexpectedFile,
/// There is an unexpected folder in the directory
#[error("unexpected folder")]
UnexpectedFolder,
/// There is an unexpected non-file item in the directory
#[error("unexpected non-file")]
UnexpectedNonFile,
/// There are multiple media files in the directory
#[error("duplicate media file")]
DuplicateMediaFile,
/// There are multiple poster files in the directory
#[error("duplicate poster file")]
DuplicatePosterFile,
/// The directory contains incomplete flix media
#[error("incomplete")]
Incomplete,
/// Some data is inconsistent with the folder structure
#[error("inconsistent")]
Inconsistent,
}
+23
View File
@@ -0,0 +1,23 @@
use std::path::PathBuf;
use crate::Error;
/// An item returned by scanner streams
#[derive(Debug)]
pub struct Item<T> {
/// The path of the item
pub path: PathBuf,
/// The event relating to the item
pub event: Result<T, Error>,
}
impl<T> Item<T> {
/// Helper function for mapping the inner event [Result]
#[inline]
pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Item<U> {
Item {
path: self.path,
event: self.event.map(op),
}
}
}
+14
View File
@@ -0,0 +1,14 @@
//! flix-fs provides filesystem scanners for flix media
#![cfg_attr(docsrs, feature(doc_cfg))]
mod macros;
mod error;
pub use error::Error;
mod item;
pub use item::Item;
pub mod scanner;
+13
View File
@@ -0,0 +1,13 @@
macro_rules! is_media_extension {
() => {
Some("mp4" | "mkv")
};
}
pub(super) use is_media_extension;
macro_rules! is_image_extension {
() => {
Some("png" | "jpg")
};
}
pub(super) use is_image_extension;
+283
View File
@@ -0,0 +1,283 @@
//! The collection scanner will scan a folder and its children
use core::pin::Pin;
use std::ffi::OsStr;
use std::path::Path;
use flix_model::id::{CollectionId, MovieId, ShowId};
use flix_model::numbers::{EpisodeNumbers, SeasonNumber};
use async_stream::stream;
use tokio::fs;
use tokio_stream::Stream;
use tokio_stream::wrappers::ReadDirStream;
use crate::Error;
use crate::macros::is_image_extension;
use crate::scanner::{generic, movie, show};
/// A collection item
pub type Item = crate::Item<Scanner>;
/// The scanner for collections
pub enum Scanner {
/// A scanned collection
Collection {
/// The ID of the parent collection (if any)
parent: Option<CollectionId>,
/// The ID of the collection
id: CollectionId,
/// The file name of the poster file
poster_file_name: Option<String>,
},
/// A scanned movie
Movie {
/// The ID of the parent collection (if any)
parent: Option<CollectionId>,
/// The ID of the movie
id: MovieId,
/// The file name of the media file
media_file_name: String,
/// The file name of the poster file
poster_file_name: Option<String>,
},
/// A scanned show
Show {
/// The ID of the parent collection (if any)
parent: Option<CollectionId>,
/// The ID of the show
id: ShowId,
/// The file name of the poster file
poster_file_name: Option<String>,
},
/// A scanned episode
Season {
/// The ID of the show this season belongs to
show: ShowId,
/// The number of this season
season: SeasonNumber,
/// The file name of the poster file
poster_file_name: Option<String>,
},
/// A scanned episode
Episode {
/// The ID of the show this episode belongs to
show: ShowId,
/// The season this episode belongs to
season: SeasonNumber,
/// The number(s) of this episode
episode: EpisodeNumbers,
/// The file name of the media file
media_file_name: String,
/// The file name of the poster file
poster_file_name: Option<String>,
},
}
impl From<movie::Scanner> for Scanner {
fn from(value: movie::Scanner) -> Self {
match value {
movie::Scanner::Movie {
parent,
id,
media_file_name,
poster_file_name,
} => Self::Movie {
parent,
id,
media_file_name,
poster_file_name,
},
}
}
}
impl From<show::Scanner> for Scanner {
fn from(value: show::Scanner) -> Self {
match value {
show::Scanner::Show {
parent,
id,
poster_file_name,
} => Self::Show {
parent,
id,
poster_file_name,
},
show::Scanner::Season {
show,
season,
poster_file_name,
} => Self::Season {
show,
season,
poster_file_name,
},
show::Scanner::Episode {
show,
season,
episode,
media_file_name,
poster_file_name,
} => Self::Episode {
show,
season,
episode,
media_file_name,
poster_file_name,
},
}
}
}
impl From<generic::Scanner> for Scanner {
fn from(value: generic::Scanner) -> Self {
match value {
generic::Scanner::Collection {
parent,
id,
poster_file_name,
} => Self::Collection {
parent,
id,
poster_file_name,
},
generic::Scanner::Movie {
parent,
id,
media_file_name,
poster_file_name,
} => Self::Movie {
parent,
id,
media_file_name,
poster_file_name,
},
generic::Scanner::Show {
parent,
id,
poster_file_name,
} => Self::Show {
parent,
id,
poster_file_name,
},
generic::Scanner::Season {
show,
season,
poster_file_name,
} => Self::Season {
show,
season,
poster_file_name,
},
generic::Scanner::Episode {
show,
season,
episode,
media_file_name,
poster_file_name,
} => Self::Episode {
show,
season,
episode,
media_file_name,
poster_file_name,
},
}
}
}
impl Scanner {
/// Scan a folder for a collection
pub fn scan_collection(
path: &Path,
parent: Option<CollectionId>,
id: CollectionId,
) -> Pin<Box<impl Stream<Item = Item>>> {
Box::pin(stream!({
let dirs = match fs::read_dir(path).await {
Ok(dirs) => dirs,
Err(err) => {
yield Item {
path: path.to_owned(),
event: Err(Error::ReadDir(err)),
};
return;
}
};
let mut poster_file_name = None;
let mut subdirs_to_scan = Vec::new();
for await dir in ReadDirStream::new(dirs) {
match dir {
Ok(dir) => {
let path = dir.path();
let filetype = match dir.file_type().await {
Ok(filetype) => filetype,
Err(err) => {
yield Item {
path,
event: Err(Error::FileType(err)),
};
continue;
}
};
if filetype.is_dir() {
subdirs_to_scan.push(path);
continue;
}
match path.extension().and_then(OsStr::to_str) {
is_image_extension!() => {
if poster_file_name.is_some() {
yield Item {
path,
event: Err(Error::DuplicatePosterFile),
};
continue;
}
poster_file_name = path
.file_name()
.and_then(|s| s.to_str())
.map(ToOwned::to_owned);
}
Some(_) | None => {
yield Item {
path,
event: Err(Error::UnexpectedFile),
};
}
}
}
Err(err) => {
yield Item {
path: path.to_owned(),
event: Err(Error::ReadDirEntry(err)),
}
}
}
}
yield Item {
path: path.to_owned(),
event: Ok(Self::Collection {
parent,
id,
poster_file_name,
}),
};
for subdir in subdirs_to_scan {
for await event in generic::Scanner::scan_detect_folder(&subdir, Some(id)) {
yield event.map(|e| e.into());
}
}
}))
}
}
+148
View File
@@ -0,0 +1,148 @@
//! The episode scanner will scan a folder and exit
use std::ffi::OsStr;
use std::path::Path;
use flix_model::id::ShowId;
use flix_model::numbers::{EpisodeNumbers, SeasonNumber};
use async_stream::stream;
use tokio::fs;
use tokio_stream::Stream;
use tokio_stream::wrappers::ReadDirStream;
use crate::Error;
use crate::macros::{is_image_extension, is_media_extension};
/// An episode item
pub type Item = crate::Item<Scanner>;
/// The scanner for epispdes
pub enum Scanner {
/// A scanned episode
Episode {
/// The ID of the show this episode belongs to
show: ShowId,
/// The season this episode belongs to
season: SeasonNumber,
/// The number(s) of this episode
episode: EpisodeNumbers,
/// The file name of the media file
media_file_name: String,
/// The file name of the poster file
poster_file_name: Option<String>,
},
}
impl Scanner {
/// Scan a folder for an episode
pub fn scan_episode(
path: &Path,
show: ShowId,
season: SeasonNumber,
episode: EpisodeNumbers,
) -> impl Stream<Item = Item> {
stream!({
let dirs = match fs::read_dir(path).await {
Ok(dirs) => dirs,
Err(err) => {
yield Item {
path: path.to_owned(),
event: Err(Error::ReadDir(err)),
};
return;
}
};
let mut media_file_name = None;
let mut poster_file_name = None;
for await dir in ReadDirStream::new(dirs) {
match dir {
Ok(dir) => {
let path = dir.path();
let filetype = match dir.file_type().await {
Ok(filetype) => filetype,
Err(err) => {
yield Item {
path,
event: Err(Error::FileType(err)),
};
continue;
}
};
if !filetype.is_file() {
yield Item {
path,
event: Err(Error::UnexpectedNonFile),
};
continue;
}
match path.extension().and_then(OsStr::to_str) {
is_media_extension!() => {
if media_file_name.is_some() {
yield Item {
path,
event: Err(Error::DuplicateMediaFile),
};
continue;
}
media_file_name = path
.file_name()
.and_then(|s| s.to_str())
.map(ToOwned::to_owned);
continue;
}
is_image_extension!() => {
if poster_file_name.is_some() {
yield Item {
path,
event: Err(Error::DuplicatePosterFile),
};
continue;
}
poster_file_name = path
.file_name()
.and_then(|s| s.to_str())
.map(ToOwned::to_owned);
}
Some(_) | None => {
yield Item {
path,
event: Err(Error::UnexpectedFile),
};
}
}
}
Err(err) => {
yield Item {
path: path.to_owned(),
event: Err(Error::ReadDirEntry(err)),
}
}
}
}
let Some(media_file_name) = media_file_name else {
yield Item {
path: path.to_owned(),
event: Err(Error::Incomplete),
};
return;
};
yield Item {
path: path.to_owned(),
event: Ok(Self::Episode {
show,
season,
episode,
media_file_name,
poster_file_name,
}),
};
})
}
}
+333
View File
@@ -0,0 +1,333 @@
//! The generic scanner will scan a directory and automatically
//! detect the type of media, deferring to the correct scanner.
use std::ffi::OsStr;
use std::path::Path;
use std::sync::OnceLock;
use flix_model::id::{CollectionId, MovieId, RawId, ShowId};
use flix_model::numbers::{EpisodeNumbers, SeasonNumber};
use async_stream::stream;
use regex::Regex;
use tokio::fs;
use tokio_stream::Stream;
use tokio_stream::wrappers::ReadDirStream;
use crate::Error;
use crate::scanner::{collection, movie, show};
static MEDIA_FOLDER_REGEX: OnceLock<Regex> = OnceLock::new();
static SEASON_FOLDER_REGEX: OnceLock<Regex> = OnceLock::new();
/// A collection item
pub type Item = crate::Item<Scanner>;
/// The scanner for collections
pub enum Scanner {
/// A scanned collection
Collection {
/// The ID of the parent collection (if any)
parent: Option<CollectionId>,
/// The ID of the collection
id: CollectionId,
/// The file name of the poster file
poster_file_name: Option<String>,
},
/// A scanned movie
Movie {
/// The ID of the parent collection (if any)
parent: Option<CollectionId>,
/// The ID of the movie
id: MovieId,
/// The file name of the media file
media_file_name: String,
/// The file name of the poster file
poster_file_name: Option<String>,
},
/// A scanned show
Show {
/// The ID of the parent collection (if any)
parent: Option<CollectionId>,
/// The ID of the show
id: ShowId,
/// The file name of the poster file
poster_file_name: Option<String>,
},
/// A scanned episode
Season {
/// The ID of the show this season belongs to
show: ShowId,
/// The season this episode belongs to
season: SeasonNumber,
/// The file name of the poster file
poster_file_name: Option<String>,
},
/// A scanned episode
Episode {
/// The ID of the show this episode belongs to
show: ShowId,
/// The season this episode belongs to
season: SeasonNumber,
/// The number(s) of this episode
episode: EpisodeNumbers,
/// The file name of the media file
media_file_name: String,
/// The file name of the poster file
poster_file_name: Option<String>,
},
}
impl From<collection::Scanner> for Scanner {
fn from(value: collection::Scanner) -> Self {
match value {
collection::Scanner::Collection {
parent,
id,
poster_file_name,
} => Self::Collection {
parent,
id,
poster_file_name,
},
collection::Scanner::Movie {
parent,
id,
media_file_name,
poster_file_name,
} => Self::Movie {
parent,
id,
media_file_name,
poster_file_name,
},
collection::Scanner::Show {
parent,
id,
poster_file_name,
} => Self::Show {
parent,
id,
poster_file_name,
},
collection::Scanner::Season {
show,
season,
poster_file_name,
} => Self::Season {
show,
season,
poster_file_name,
},
collection::Scanner::Episode {
show,
season,
episode,
media_file_name,
poster_file_name,
} => Self::Episode {
show,
season,
episode,
media_file_name,
poster_file_name,
},
}
}
}
impl From<movie::Scanner> for Scanner {
fn from(value: movie::Scanner) -> Self {
match value {
movie::Scanner::Movie {
parent,
id,
media_file_name,
poster_file_name,
} => Self::Movie {
parent,
id,
media_file_name,
poster_file_name,
},
}
}
}
impl From<show::Scanner> for Scanner {
fn from(value: show::Scanner) -> Self {
match value {
show::Scanner::Show {
parent,
id,
poster_file_name,
} => Self::Show {
parent,
id,
poster_file_name,
},
show::Scanner::Season {
show,
season,
poster_file_name,
} => Self::Season {
show,
season,
poster_file_name,
},
show::Scanner::Episode {
show,
season,
episode,
media_file_name,
poster_file_name,
} => Self::Episode {
show,
season,
episode,
media_file_name,
poster_file_name,
},
}
}
}
impl Scanner {
/// Detect the type of a folder and call the correct scanner. Use
/// this only for detecting possibly ambiguous media:
/// - Collections
/// - Movies
/// - Shows
pub fn scan_detect_folder(
path: &Path,
parent: Option<CollectionId>,
) -> impl Stream<Item = Item> {
enum MediaType {
Collection,
Movie,
Show,
}
let media_folder_re = MEDIA_FOLDER_REGEX.get_or_init(|| {
Regex::new(r"^[[[:alnum:]]' -]+ \([[:digit:]]+\) \[[[:digit:]]+\]$")
.unwrap_or_else(|err| panic!("regex is invalid: {err}"))
});
let season_folder_re = SEASON_FOLDER_REGEX.get_or_init(|| {
Regex::new(r"^S[[:digit:]]+$").unwrap_or_else(|err| panic!("regex is invalid: {err}"))
});
stream!({
let Some(dir_name) = path.file_name().and_then(OsStr::to_str) else {
yield Item {
path: path.to_owned(),
event: Err(Error::UnexpectedFolder),
};
return;
};
let Some(Ok(id)) = dir_name
.split_once('[')
.and_then(|(_, s)| s.split_once(']'))
.map(|(s, _)| s.parse::<RawId>())
else {
yield Item {
path: path.to_owned(),
event: Err(Error::UnexpectedFolder),
};
return;
};
let media_type: MediaType;
if media_folder_re.is_match(dir_name) {
let dirs = match fs::read_dir(path).await {
Ok(dirs) => dirs,
Err(err) => {
yield Item {
path: path.to_owned(),
event: Err(Error::ReadDir(err)),
};
return;
}
};
let mut is_show = false;
for await dir in ReadDirStream::new(dirs) {
match dir {
Ok(dir) => {
let path = dir.path();
let filetype = match dir.file_type().await {
Ok(filetype) => filetype,
Err(err) => {
yield Item {
path,
event: Err(Error::FileType(err)),
};
continue;
}
};
if !filetype.is_dir() {
continue;
}
let Some(folder_name) = path.file_name().and_then(OsStr::to_str) else {
yield Item {
path,
event: Err(Error::UnexpectedFolder),
};
continue;
};
if season_folder_re.is_match(folder_name) {
is_show = true;
break;
}
}
Err(err) => {
yield Item {
path: path.to_owned(),
event: Err(Error::ReadDirEntry(err)),
};
}
}
}
if is_show {
media_type = MediaType::Show;
} else {
media_type = MediaType::Movie;
}
} else {
media_type = MediaType::Collection;
}
match media_type {
MediaType::Collection => {
for await event in collection::Scanner::scan_collection(
path,
parent,
CollectionId::from_raw(id),
) {
yield event.map(|e| e.into());
}
}
MediaType::Movie => {
for await event in
movie::Scanner::scan_movie(path, parent, MovieId::from_raw(id))
{
yield event.map(|e| e.into());
}
}
MediaType::Show => {
for await event in show::Scanner::scan_show(path, parent, ShowId::from_raw(id))
{
yield event.map(|e| e.into());
}
}
}
})
}
}
+83
View File
@@ -0,0 +1,83 @@
//! The library scanner will scan an entire directory using the generic
//! scanner
use std::ffi::OsStr;
use std::path::Path;
use async_stream::stream;
use tokio::fs;
use tokio_stream::Stream;
use tokio_stream::wrappers::ReadDirStream;
use crate::Error;
use crate::scanner::generic;
/// A library item
pub type Item = crate::Item<generic::Scanner>;
/// The scanner for collections
pub enum Scanner {}
impl Scanner {
/// Scan a folder for a library
pub fn scan_library(path: &Path) -> impl Stream<Item = Item> {
stream!({
let dirs = match fs::read_dir(path).await {
Ok(dirs) => dirs,
Err(err) => {
yield Item {
path: path.to_owned(),
event: Err(Error::ReadDir(err)),
};
return;
}
};
let mut subdirs_to_scan = Vec::new();
for await dir in ReadDirStream::new(dirs) {
match dir {
Ok(dir) => {
let filetype = match dir.file_type().await {
Ok(filetype) => filetype,
Err(err) => {
yield Item {
path: path.to_owned(),
event: Err(Error::FileType(err)),
};
continue;
}
};
let path = dir.path();
if filetype.is_dir() {
subdirs_to_scan.push(path);
continue;
}
match path.extension().and_then(OsStr::to_str) {
Some(_) | None => {
yield Item {
path: path.to_owned(),
event: Err(Error::UnexpectedFile),
};
}
}
}
Err(err) => {
yield Item {
path: path.to_owned(),
event: Err(Error::ReadDirEntry(err)),
}
}
}
}
for subdir in subdirs_to_scan {
for await event in generic::Scanner::scan_detect_folder(&subdir, None) {
yield event;
}
}
})
}
}
+16
View File
@@ -0,0 +1,16 @@
//! This module contains all of the filesystem scanner modules
//!
//! The most common scanner to use is [generic::Scanner] which will
//! automatically detect and use the appropriate scanner.
pub mod library;
pub mod generic;
pub mod collection;
pub mod movie;
pub mod episode;
pub mod season;
pub mod show;
+143
View File
@@ -0,0 +1,143 @@
//! The movie scanner will scan a folder and exit
use std::ffi::OsStr;
use std::path::Path;
use flix_model::id::{CollectionId, MovieId};
use async_stream::stream;
use tokio::fs;
use tokio_stream::Stream;
use tokio_stream::wrappers::ReadDirStream;
use crate::Error;
use crate::macros::{is_image_extension, is_media_extension};
/// An movie item
pub type Item = crate::Item<Scanner>;
/// The scanner for movies
pub enum Scanner {
/// A scanned movie
Movie {
/// The ID of the parent collection (if any)
parent: Option<CollectionId>,
/// The ID of the movie
id: MovieId,
/// The file name of the media file
media_file_name: String,
/// The file name of the poster file
poster_file_name: Option<String>,
},
}
impl Scanner {
/// Scan a folder for a movie
pub fn scan_movie(
path: &Path,
parent: Option<CollectionId>,
id: MovieId,
) -> impl Stream<Item = Item> {
stream!({
let dirs = match fs::read_dir(path).await {
Ok(dirs) => dirs,
Err(err) => {
yield Item {
path: path.to_owned(),
event: Err(Error::ReadDir(err)),
};
return;
}
};
let mut media_file_name = None;
let mut poster_file_name = None;
for await dir in ReadDirStream::new(dirs) {
match dir {
Ok(dir) => {
let path = dir.path();
let filetype = match dir.file_type().await {
Ok(filetype) => filetype,
Err(err) => {
yield Item {
path,
event: Err(Error::FileType(err)),
};
continue;
}
};
if !filetype.is_file() {
yield Item {
path,
event: Err(Error::UnexpectedNonFile),
};
continue;
}
match path.extension().and_then(OsStr::to_str) {
is_media_extension!() => {
if media_file_name.is_some() {
yield Item {
path,
event: Err(Error::DuplicateMediaFile),
};
continue;
}
media_file_name = path
.file_name()
.and_then(|s| s.to_str())
.map(ToOwned::to_owned);
continue;
}
is_image_extension!() => {
if poster_file_name.is_some() {
yield Item {
path,
event: Err(Error::DuplicatePosterFile),
};
continue;
}
poster_file_name = path
.file_name()
.and_then(|s| s.to_str())
.map(ToOwned::to_owned);
}
Some(_) | None => {
yield Item {
path,
event: Err(Error::UnexpectedFile),
};
}
}
}
Err(err) => {
yield Item {
path: path.to_owned(),
event: Err(Error::ReadDirEntry(err)),
}
}
}
}
let Some(media_file_name) = media_file_name else {
yield Item {
path: path.to_owned(),
event: Err(Error::Incomplete),
};
return;
};
yield Item {
path: path.to_owned(),
event: Ok(Self::Movie {
parent,
id,
media_file_name,
poster_file_name,
}),
};
})
}
}
+219
View File
@@ -0,0 +1,219 @@
//! The episode scanner will scan a folder and its children
use std::ffi::OsStr;
use std::path::Path;
use flix_model::id::ShowId;
use flix_model::numbers::{EpisodeNumber, EpisodeNumbers, SeasonNumber};
use async_stream::stream;
use tokio::fs;
use tokio_stream::Stream;
use tokio_stream::wrappers::ReadDirStream;
use crate::Error;
use crate::macros::is_image_extension;
use crate::scanner::episode;
/// A season item
pub type Item = crate::Item<Scanner>;
/// The scanner for seasons
pub enum Scanner {
/// A scanned episode
Season {
/// The ID of the show this season belongs to
show: ShowId,
/// The season this episode belongs to
season: SeasonNumber,
/// The file name of the poster file
poster_file_name: Option<String>,
},
/// A scanned episode
Episode {
/// The ID of the show this episode belongs to
show: ShowId,
/// The season this episode belongs to
season: SeasonNumber,
/// The number(s) of this episode
episode: EpisodeNumbers,
/// The file name of the media file
media_file_name: String,
/// The file name of the poster file
poster_file_name: Option<String>,
},
}
impl From<episode::Scanner> for Scanner {
fn from(value: episode::Scanner) -> Self {
match value {
episode::Scanner::Episode {
show,
season,
episode,
media_file_name,
poster_file_name,
} => Self::Episode {
show,
season,
episode,
media_file_name,
poster_file_name,
},
}
}
}
impl Scanner {
/// Scan a folder for a season and its episodes
pub fn scan_season(
path: &Path,
show: ShowId,
season: SeasonNumber,
) -> impl Stream<Item = Item> {
stream!({
let dirs = match fs::read_dir(path).await {
Ok(dirs) => dirs,
Err(err) => {
yield Item {
path: path.to_owned(),
event: Err(Error::ReadDir(err)),
};
return;
}
};
let mut poster_file_name = None;
let mut episode_dirs_to_scan = Vec::new();
for await dir in ReadDirStream::new(dirs) {
match dir {
Ok(dir) => {
let path = dir.path();
let filetype = match dir.file_type().await {
Ok(filetype) => filetype,
Err(err) => {
yield Item {
path,
event: Err(Error::FileType(err)),
};
continue;
}
};
if filetype.is_dir() {
episode_dirs_to_scan.push(path);
continue;
}
match path.extension().and_then(OsStr::to_str) {
is_image_extension!() => {
if poster_file_name.is_some() {
yield Item {
path,
event: Err(Error::DuplicatePosterFile),
};
continue;
}
poster_file_name = path
.file_name()
.and_then(|s| s.to_str())
.map(ToOwned::to_owned);
}
Some(_) | None => {
yield Item {
path,
event: Err(Error::UnexpectedFile),
};
}
}
}
Err(err) => {
yield Item {
path: path.to_owned(),
event: Err(Error::ReadDirEntry(err)),
}
}
}
}
yield Item {
path: path.to_owned(),
event: Ok(Self::Season {
show,
season,
poster_file_name,
}),
};
for episode_dir in episode_dirs_to_scan {
let Some(episode_dir_name) = episode_dir.file_name().and_then(OsStr::to_str) else {
yield Item {
path: episode_dir,
event: Err(Error::UnexpectedFolder),
};
continue;
};
let Some((_, s_e_str)) = episode_dir_name.split_once('S') else {
yield Item {
path: episode_dir,
event: Err(Error::UnexpectedFolder),
};
continue;
};
let Some((s_str, e_str)) = s_e_str.split_once('E') else {
yield Item {
path: episode_dir,
event: Err(Error::UnexpectedFolder),
};
continue;
};
let Ok(season_number) = s_str.parse::<SeasonNumber>() else {
yield Item {
path: episode_dir,
event: Err(Error::UnexpectedFolder),
};
continue;
};
if season_number != season {
yield Item {
path: episode_dir,
event: Err(Error::Inconsistent),
};
continue;
}
let Ok(episode_numbers) = e_str
.split('E')
.map(|s| s.parse::<EpisodeNumber>())
.collect::<Result<Vec<_>, _>>()
else {
yield Item {
path: episode_dir,
event: Err(Error::UnexpectedFolder),
};
continue;
};
let Ok(episode_numbers) = EpisodeNumbers::try_from(episode_numbers.as_ref()) else {
yield Item {
path: episode_dir,
event: Err(Error::UnexpectedFolder),
};
continue;
};
for await event in episode::Scanner::scan_episode(
&episode_dir,
show,
season_number,
episode_numbers,
) {
yield event.map(|e| e.into());
}
}
})
}
}
+194
View File
@@ -0,0 +1,194 @@
//! The show scanner will scan a folder and its children
use std::ffi::OsStr;
use std::path::Path;
use flix_model::id::{CollectionId, ShowId};
use flix_model::numbers::{EpisodeNumbers, SeasonNumber};
use async_stream::stream;
use tokio::fs;
use tokio_stream::Stream;
use tokio_stream::wrappers::ReadDirStream;
use crate::Error;
use crate::macros::is_image_extension;
use crate::scanner::season;
/// A show item
pub type Item = crate::Item<Scanner>;
/// The scanner for shows
pub enum Scanner {
/// A scanned show
Show {
/// The ID of the parent collection (if any)
parent: Option<CollectionId>,
/// The ID of the show
id: ShowId,
/// The file name of the poster file
poster_file_name: Option<String>,
},
/// A scanned episode
Season {
/// The ID of the show this season belongs to
show: ShowId,
/// The season this episode belongs to
season: SeasonNumber,
/// The file name of the poster file
poster_file_name: Option<String>,
},
/// A scanned episode
Episode {
/// The ID of the show this episode belongs to
show: ShowId,
/// The season this episode belongs to
season: SeasonNumber,
/// The number(s) of this episode
episode: EpisodeNumbers,
/// The file name of the media file
media_file_name: String,
/// The file name of the poster file
poster_file_name: Option<String>,
},
}
impl From<season::Scanner> for Scanner {
fn from(value: season::Scanner) -> Self {
match value {
season::Scanner::Season {
show,
season,
poster_file_name,
} => Self::Season {
show,
season,
poster_file_name,
},
season::Scanner::Episode {
show,
season,
episode,
media_file_name,
poster_file_name,
} => Self::Episode {
show,
season,
episode,
media_file_name,
poster_file_name,
},
}
}
}
impl Scanner {
/// Scan a folder for a show and its seasons/episodes
pub fn scan_show(
path: &Path,
parent: Option<CollectionId>,
id: ShowId,
) -> impl Stream<Item = Item> {
stream!({
let dirs = match fs::read_dir(path).await {
Ok(dirs) => dirs,
Err(err) => {
yield Item {
path: path.to_owned(),
event: Err(Error::ReadDir(err)),
};
return;
}
};
let mut poster_file_name = None;
let mut season_dirs_to_scan = Vec::new();
for await dir in ReadDirStream::new(dirs) {
match dir {
Ok(dir) => {
let path = dir.path();
let filetype = match dir.file_type().await {
Ok(filetype) => filetype,
Err(err) => {
yield Item {
path,
event: Err(Error::FileType(err)),
};
continue;
}
};
if filetype.is_dir() {
season_dirs_to_scan.push(path);
continue;
}
match path.extension().and_then(OsStr::to_str) {
is_image_extension!() => {
if poster_file_name.is_some() {
yield Item {
path,
event: Err(Error::DuplicatePosterFile),
};
continue;
}
poster_file_name = path
.file_name()
.and_then(|s| s.to_str())
.map(ToOwned::to_owned);
}
Some(_) | None => {
yield Item {
path,
event: Err(Error::UnexpectedFile),
};
}
}
}
Err(err) => {
yield Item {
path: path.to_owned(),
event: Err(Error::ReadDirEntry(err)),
}
}
}
}
yield Item {
path: path.to_owned(),
event: Ok(Self::Show {
parent,
id,
poster_file_name,
}),
};
for season_dir in season_dirs_to_scan {
let Some(season_dir_name) = season_dir.file_name().and_then(OsStr::to_str) else {
yield Item {
path: season_dir,
event: Err(Error::UnexpectedFolder),
};
continue;
};
let Some(Ok(season_number)) = season_dir_name
.split_once('S')
.map(|(_, s)| s.parse::<SeasonNumber>())
else {
yield Item {
path: season_dir,
event: Err(Error::UnexpectedFolder),
};
continue;
};
for await event in season::Scanner::scan_season(&season_dir, id, season_number) {
yield event.map(|e| e.into());
}
}
})
}
}
+26
View File
@@ -0,0 +1,26 @@
[package]
name = "flix-model"
version = "0.0.16"
edition.workspace = true
rust-version.workspace = true
description = "Core types for flix data"
repository = "https://github.com/QuantumShade/flix"
license-file.workspace = true
categories = []
[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]
[dependencies]
itertools = { workspace = true }
seamantic = { workspace = true }
serde = { workspace = true, features = ["derive", "std"], optional = true }
thiserror = { workspace = true }
[features]
default = []
serde = ["dep:serde"]
[lints]
workspace = true
+5
View File
@@ -0,0 +1,5 @@
# flix-model
[![Crates Version](https://img.shields.io/crates/v/flix-model.svg)](https://crates.io/crates/flix-model)
A library providing core types for flix data
+26
View File
@@ -0,0 +1,26 @@
//! This module contains types relating to flix media IDs
use seamantic::model::id::Id;
/// Type alias for the raw ID representation
pub use seamantic::model::id::SeaOrmRepr as RawId;
#[doc(hidden)]
pub enum Library {}
/// Type alias for a library ID
pub type LibraryId = Id<Library>;
#[doc(hidden)]
pub enum Collection {}
/// Type alias for a collection ID
pub type CollectionId = Id<Collection>;
#[doc(hidden)]
pub enum Movie {}
/// Type alias for a movie ID
pub type MovieId = Id<Movie>;
#[doc(hidden)]
pub enum Show {}
/// Type alias for a show ID
pub type ShowId = Id<Show>;
+7
View File
@@ -0,0 +1,7 @@
//! flix-model provides core types for flix data
#![cfg_attr(docsrs, feature(doc_cfg))]
pub mod id;
pub mod numbers;
pub mod text;
+143
View File
@@ -0,0 +1,143 @@
//! This module contains season and episode numbers and related errors
use core::fmt;
use core::ops::RangeInclusive;
use core::str::FromStr;
use std::collections::HashSet;
use seamantic::sea_orm;
/// Newtype for representing season numbers
#[derive(
Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, sea_orm::DeriveValueType,
)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
#[repr(transparent)]
pub struct SeasonNumber(u32);
impl SeasonNumber {
/// Create a `SeasonNumber` from an integer
pub fn new(value: u32) -> Self {
Self(value)
}
}
impl fmt::Display for SeasonNumber {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
impl FromStr for SeasonNumber {
type Err = <u32 as FromStr>::Err;
fn from_str(s: &str) -> Result<Self, Self::Err> {
u32::from_str(s).map(Self)
}
}
/// Newtype for representing episode numbers
#[derive(
Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, sea_orm::DeriveValueType,
)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
#[repr(transparent)]
pub struct EpisodeNumber(u32);
impl EpisodeNumber {
/// Create an `EpisodeNumber` from an integer
pub fn new(value: u32) -> Self {
Self(value)
}
/// Get the underlying value
pub fn into_inner(self) -> u32 {
self.0
}
}
impl fmt::Display for EpisodeNumber {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
impl FromStr for EpisodeNumber {
type Err = <u32 as FromStr>::Err;
fn from_str(s: &str) -> Result<Self, Self::Err> {
u32::from_str(s).map(Self)
}
}
/// Potential errors when building EpisodeNumbers
#[derive(Debug, thiserror::Error)]
pub enum Error {
/// There are no episodes
#[error("zero episodes")]
Zero,
/// There are gaps in the episodes
#[error("noncontiguous episodes")]
Noncontiguous,
}
/// A wrapper for handling single and multi-episode entries
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct EpisodeNumbers(RangeInclusive<EpisodeNumber>);
impl TryFrom<&[EpisodeNumber]> for EpisodeNumbers {
type Error = Error;
fn try_from(value: &[EpisodeNumber]) -> Result<Self, Self::Error> {
match value {
[] => Err(Error::Zero),
[n] => Ok(Self(*n..=*n)),
_ => {
// min and max will always exist
let min = value.iter().copied().min().unwrap_or_default();
let max = value.iter().copied().max().unwrap_or_default();
let len = value.len();
if usize::try_from(max.0.saturating_sub(min.0).saturating_add(1)) != Ok(len) {
return Err(Error::Noncontiguous);
}
let set: HashSet<_> = value.iter().copied().collect();
if set.len() != len {
return Err(Error::Noncontiguous);
}
Ok(Self(min..=max))
}
}
}
}
impl EpisodeNumbers {
/// Create an [EpisodeNumbers] from a starting number and a count.
/// `count` should be zero for single episodes.
pub fn new(start: EpisodeNumber, count: u8) -> Self {
Self(start..=EpisodeNumber(start.0.saturating_add(count.into())))
}
/// Get the range of episodes
pub fn as_range(&self) -> &RangeInclusive<EpisodeNumber> {
&self.0
}
/// Render this [EpisodeNumbers] as a range. If only one episode is
/// is present it renders as `01`, if multiple it renders as `01-02`
pub fn range_string(&self) -> String {
let start = self.0.start();
let end = self.0.end();
if start == end {
format!("{:02}", start)
} else {
format!("{:02}-{:02}", start, end)
}
}
}
+165
View File
@@ -0,0 +1,165 @@
//! This module contains helper functions for normalizing media titles
use core::iter::Peekable;
use itertools::Itertools;
/// # Panics
///
/// Panics if `input` is not ASCII.
fn split_normalized_words(input: &str) -> impl Iterator<Item = String> {
if !input.is_ascii() {
panic!("Input is not ASCII: {input}");
}
input.split_ascii_whitespace().map(|s| {
let chars = s
.chars()
.filter(|c| c.is_ascii_alphanumeric() || *c == '-')
.map(|c| c.to_ascii_lowercase());
if s.len() > 4
&& s.len().is_multiple_of(2)
&& chars.clone().tuples().all(|(l, r)| l != '.' && r == '.')
{
// Collapse acronym
chars.tuples().map(|(l, _)| l).collect()
} else {
chars.collect()
}
})
}
fn split_leading_article<I: Iterator<Item = String>>(iter: I) -> (Option<String>, Peekable<I>) {
let mut iter = iter.peekable();
match iter.peek().map(String::as_str) {
Some("a" | "an" | "the") => (iter.next(), iter),
_ => (None, iter),
}
}
/// Convert a media title to be sortable and searchable
///
/// use flix_model::text::make_sortable_title;
///
/// assert_eq!(make_sortable_title("The Matrix"), "matrix, the");
/// assert_eq!(make_sortable_title("Marvel's Agents of S.H.I.E.L.D."), "marvels agents of shield");
/// assert_eq!(make_sortable_title("Avatar: The Last Airbender"), "avatar the last airbender");
///
/// # Panics
///
/// Panics if `input` is not ASCII.
pub fn make_sortable_title(title: &str) -> String {
let words = split_normalized_words(title);
let (article, words) = split_leading_article(words);
let output = Itertools::intersperse(words, " ".to_string());
if let Some(article) = article {
output.chain([", ".to_string(), article]).collect()
} else {
output.collect()
}
}
/// Convert a media title to a folder name representable on filesystems
///
/// use flix_model::text::make_fs_slug;
///
/// assert_eq!(make_fs_slug("The Matrix"), "matrix");
/// assert_eq!(make_fs_slug("Marvel's Agents of S.H.I.E.L.D."), "marvels agents of shield");
/// assert_eq!(make_fs_slug("Avatar: The Last Airbender"), "avatar the last airbender");
///
/// # Panics
///
/// Panics if `input` is not ASCII.
pub fn make_fs_slug(title: &str) -> String {
let words = split_normalized_words(title);
let (_, words) = split_leading_article(words);
Itertools::intersperse(words, " ".to_string()).collect()
}
/// Convert a media title and year to a folder name representable on filesystems
///
/// use flix_model::text::make_fs_slug_year;
///
/// assert_eq!(make_fs_slug_year("The Matrix", 1999), "matrix (1999)");
/// assert_eq!(make_fs_slug_year("Marvel's Agents of S.H.I.E.L.D.", 2013), "marvels agents of shield (2013)");
/// assert_eq!(make_fs_slug_year("Avatar: The Last Airbender", 2005), "avatar the last airbender (2005)");
///
/// # Panics
///
/// Panics if `input` is not ASCII.
pub fn make_fs_slug_year(title: &str, year: i32) -> String {
let words = split_normalized_words(title);
let (_, words) = split_leading_article(words);
Itertools::intersperse(words, " ".to_string())
.chain([format!(" ({year})")])
.collect()
}
/// Normalize a filesystem name
///
/// use flix_model::text::normalize_fs_name;
///
/// assert_eq!(normalize_fs_name("Matrix (1999)"), "matrix (1999)");
/// assert_eq!(normalize_fs_name("Marvel's Agents of SHIELD (2013)"), "marvels agents of shield (2013)");
/// assert_eq!(normalize_fs_name("Avatar The Last Airbender (2005)"), "avatar the last airbender (2005)");
pub fn normalize_fs_name(input: &str) -> String {
let chars = input.split_ascii_whitespace().map(|s| {
let chars = s
.chars()
.filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '(' || *c == ')')
.map(|c| c.to_ascii_lowercase());
if s.len() > 4
&& s.len().is_multiple_of(2)
&& chars.clone().tuples().all(|(l, r)| l != '.' && r == '.')
{
// Collapse acronym
chars.tuples().map(|(l, _)| l).collect()
} else {
chars.collect()
}
});
Itertools::intersperse(chars, " ".to_string()).collect()
}
/// Convert a media title to a url compatible string
///
/// use flix_model::text::make_web_slug;
///
/// assert_eq!(make_web_slug("The Matrix"), "matrix");
/// assert_eq!(make_web_slug("Marvel's Agents of S.H.I.E.L.D."), "marvels-agents-of-shield");
/// assert_eq!(make_web_slug("Avatar: The Last Airbender"), "avatar-the-last-airbender");
///
/// # Panics
///
/// Panics if `input` is not ASCII.
pub fn make_web_slug(title: &str) -> String {
let words = split_normalized_words(title);
let (_, words) = split_leading_article(words);
Itertools::intersperse(words, "-".to_string()).collect()
}
/// Convert a media title and year to a url compatible string
///
/// use flix_model::text::make_web_slug_year;
///
/// assert_eq!(make_web_slug_year("The Matrix", 1999), "matrix-1999");
/// assert_eq!(make_web_slug_year("Marvel's Agents of S.H.I.E.L.D.", 2013), "marvels-agents-of-shield-2013");
/// assert_eq!(make_web_slug_year("Avatar: The Last Airbender", 2005), "avatar-the-last-airbender-2005");
///
/// # Panics
///
/// Panics if `input` is not ASCII.
pub fn make_web_slug_year(title: &str, year: i32) -> String {
let words = split_normalized_words(title);
let (_, words) = split_leading_article(words);
Itertools::intersperse(words, "-".to_string())
.chain([format!("-{year}")])
.collect()
}
+22 -10
View File
@@ -1,23 +1,35 @@
[package] [package]
name = "flix-tmdb" name = "flix-tmdb"
version = "0.0.8" version = "0.0.16"
edition.workspace = true
categories = [] rust-version.workspace = true
description = "Clients and models for fetching data from TMDB" description = "Clients and models for fetching data from TMDB"
repository = "https://github.com/QuantumShade/flix" repository = "https://github.com/QuantumShade/flix"
authors.workspace = true
edition.workspace = true
license-file.workspace = true license-file.workspace = true
rust-version.workspace = true categories = []
[lints] [package.metadata.docs.rs]
workspace = true all-features = true
rustdoc-args = ["--cfg", "docsrs"]
[dependencies] [dependencies]
chrono = { workspace = true, features = ["serde"] } chrono = { workspace = true, features = ["serde"] }
reqwest = { workspace = true, features = ["json", "rustls-tls"] } flix-model = { workspace = true, features = ["serde"] }
governor = { workspace = true, features = ["jitter", "std"] }
nonzero_ext = { workspace = true }
reqwest = { workspace = true, features = ["json", "query", "rustls"] }
sea-orm = { workspace = true, optional = true }
serde = { workspace = true, features = ["derive"] } serde = { workspace = true, features = ["derive"] }
thiserror = { workspace = true } thiserror = { workspace = true }
url = { workspace = true } url = { workspace = true }
url-macro = { workspace = true } url-macro = { workspace = true }
[dev-dependencies]
serde_test = { workspace = true }
[features]
default = []
sea-orm = ["dep:sea-orm"]
[lints]
workspace = true
+16 -2
View File
@@ -1,7 +1,13 @@
//! Collections API
use core::time::Duration;
use std::rc::Rc; use std::rc::Rc;
use governor::Jitter;
use crate::Config; use crate::Config;
use crate::model::{Collection, CollectionId}; use crate::model::Collection;
use crate::model::id::CollectionId;
use super::{Error, make_request}; use super::{Error, make_request};
@@ -24,12 +30,20 @@ impl Client {
id: impl Into<CollectionId>, id: impl Into<CollectionId>,
language: Option<&str>, language: Option<&str>,
) -> Result<Collection, Error> { ) -> Result<Collection, Error> {
self.config
.limiter
.until_ready_with_jitter(Jitter::new(
Duration::from_millis(0),
Duration::from_millis(50),
))
.await;
Ok(self Ok(self
.config .config
.client .client
.execute(make_request( .execute(make_request(
&self.config, &self.config,
&format!("/3/collection/{}", id.into()), &format!("/3/collection/{}", id.into().into_raw()),
language, language,
)?) )?)
.await? .await?
+20 -4
View File
@@ -1,7 +1,15 @@
//! Episodes API
use core::time::Duration;
use std::rc::Rc; use std::rc::Rc;
use flix_model::numbers::{EpisodeNumber, SeasonNumber};
use governor::Jitter;
use crate::Config; use crate::Config;
use crate::model::{Episode, ShowId}; use crate::model::Episode;
use crate::model::id::ShowId;
use super::{Error, make_request}; use super::{Error, make_request};
@@ -22,10 +30,18 @@ impl Client {
pub async fn get_details( pub async fn get_details(
&self, &self,
id: impl Into<ShowId>, id: impl Into<ShowId>,
season: impl Into<u32>, season: impl Into<SeasonNumber>,
episode: impl Into<u32>, episode: impl Into<EpisodeNumber>,
language: Option<&str>, language: Option<&str>,
) -> Result<Episode, Error> { ) -> Result<Episode, Error> {
self.config
.limiter
.until_ready_with_jitter(Jitter::new(
Duration::from_millis(0),
Duration::from_millis(50),
))
.await;
Ok(self Ok(self
.config .config
.client .client
@@ -33,7 +49,7 @@ impl Client {
&self.config, &self.config,
&format!( &format!(
"/3/tv/{}/season/{}/episode/{}", "/3/tv/{}/season/{}/episode/{}",
id.into(), id.into().into_raw(),
season.into(), season.into(),
episode.into() episode.into()
), ),
-58
View File
@@ -1,58 +0,0 @@
use std::rc::Rc;
use crate::Config;
use crate::model::{MovieGenre, ShowGenre};
use super::{Error, make_request};
/// TMDB Genre API client
pub struct Client {
config: Rc<Config>,
}
impl Client {
/// Create a new client with the given configuration
pub fn new(config: Rc<Config>) -> Self {
Self { config }
}
}
impl Client {
/// Fetch the list of all valid movie genres
pub async fn get_movie_genres(&self, language: Option<&str>) -> Result<Vec<MovieGenre>, Error> {
#[derive(Debug, serde::Deserialize)]
struct Genres {
genres: Vec<MovieGenre>,
}
let genres: Genres = self
.config
.client
.execute(make_request(&self.config, "/3/genre/movie/list", language)?)
.await?
.error_for_status()?
.json()
.await?;
Ok(genres.genres)
}
/// Fetch the list of all valid show genres
pub async fn get_tv_genres(&self, language: Option<&str>) -> Result<Vec<ShowGenre>, Error> {
#[derive(Debug, serde::Deserialize)]
struct Genres {
genres: Vec<ShowGenre>,
}
let genres: Genres = self
.config
.client
.execute(make_request(&self.config, "/3/genre/tv/list", language)?)
.await?
.error_for_status()?
.json()
.await?;
Ok(genres.genres)
}
}
+2 -7
View File
@@ -1,19 +1,14 @@
//! TMDB API clients
use reqwest::Request; use reqwest::Request;
use reqwest::header; use reqwest::header;
use crate::Config; use crate::Config;
/// Collections API
pub mod collections; pub mod collections;
/// Episodes API
pub mod episodes; pub mod episodes;
/// Genres API
pub mod genres;
/// Movies API
pub mod movies; pub mod movies;
/// Seasons API
pub mod seasons; pub mod seasons;
/// Shows API
pub mod shows; pub mod shows;
/// A generic error wrapping Url and Reqwest errors /// A generic error wrapping Url and Reqwest errors
+16 -2
View File
@@ -1,7 +1,13 @@
//! Movies API
use core::time::Duration;
use std::rc::Rc; use std::rc::Rc;
use governor::Jitter;
use crate::Config; use crate::Config;
use crate::model::{Movie, MovieId}; use crate::model::Movie;
use crate::model::id::MovieId;
use super::{Error, make_request}; use super::{Error, make_request};
@@ -24,12 +30,20 @@ impl Client {
id: impl Into<MovieId>, id: impl Into<MovieId>,
language: Option<&str>, language: Option<&str>,
) -> Result<Movie, Error> { ) -> Result<Movie, Error> {
self.config
.limiter
.until_ready_with_jitter(Jitter::new(
Duration::from_millis(0),
Duration::from_millis(50),
))
.await;
Ok(self Ok(self
.config .config
.client .client
.execute(make_request( .execute(make_request(
&self.config, &self.config,
&format!("/3/movie/{}", id.into()), &format!("/3/movie/{}", id.into().into_raw()),
language, language,
)?) )?)
.await? .await?
+19 -3
View File
@@ -1,7 +1,15 @@
//! Seasons API
use core::time::Duration;
use std::rc::Rc; use std::rc::Rc;
use flix_model::numbers::SeasonNumber;
use governor::Jitter;
use crate::Config; use crate::Config;
use crate::model::{Season, ShowId}; use crate::model::Season;
use crate::model::id::ShowId;
use super::{Error, make_request}; use super::{Error, make_request};
@@ -22,15 +30,23 @@ impl Client {
pub async fn get_details( pub async fn get_details(
&self, &self,
id: impl Into<ShowId>, id: impl Into<ShowId>,
season: impl Into<u32>, season: impl Into<SeasonNumber>,
language: Option<&str>, language: Option<&str>,
) -> Result<Season, Error> { ) -> Result<Season, Error> {
self.config
.limiter
.until_ready_with_jitter(Jitter::new(
Duration::from_millis(0),
Duration::from_millis(50),
))
.await;
Ok(self Ok(self
.config .config
.client .client
.execute(make_request( .execute(make_request(
&self.config, &self.config,
&format!("/3/tv/{}/season/{}", id.into(), season.into()), &format!("/3/tv/{}/season/{}", id.into().into_raw(), season.into()),
language, language,
)?) )?)
.await? .await?
+16 -2
View File
@@ -1,7 +1,13 @@
//! Shows API
use core::time::Duration;
use std::rc::Rc; use std::rc::Rc;
use governor::Jitter;
use crate::Config; use crate::Config;
use crate::model::{Show, ShowId}; use crate::model::Show;
use crate::model::id::ShowId;
use super::{Error, make_request}; use super::{Error, make_request};
@@ -24,12 +30,20 @@ impl Client {
id: impl Into<ShowId>, id: impl Into<ShowId>,
language: Option<&str>, language: Option<&str>,
) -> Result<Show, Error> { ) -> Result<Show, Error> {
self.config
.limiter
.until_ready_with_jitter(Jitter::new(
Duration::from_millis(0),
Duration::from_millis(50),
))
.await;
Ok(self Ok(self
.config .config
.client .client
.execute(make_request( .execute(make_request(
&self.config, &self.config,
&format!("/3/tv/{}", id.into()), &format!("/3/tv/{}", id.into().into_raw()),
language, language,
)?) )?)
.await? .await?
-7
View File
@@ -4,7 +4,6 @@ use crate::{Config, api};
/// The primary client that references all other clients /// The primary client that references all other clients
pub struct Client { pub struct Client {
genres: api::genres::Client,
collections: api::collections::Client, collections: api::collections::Client,
movies: api::movies::Client, movies: api::movies::Client,
shows: api::shows::Client, shows: api::shows::Client,
@@ -22,7 +21,6 @@ impl Client {
pub fn new_with_config(config: Config) -> Self { pub fn new_with_config(config: Config) -> Self {
let config = Rc::new(config); let config = Rc::new(config);
Self { Self {
genres: api::genres::Client::new(config.clone()),
collections: api::collections::Client::new(config.clone()), collections: api::collections::Client::new(config.clone()),
movies: api::movies::Client::new(config.clone()), movies: api::movies::Client::new(config.clone()),
shows: api::shows::Client::new(config.clone()), shows: api::shows::Client::new(config.clone()),
@@ -33,11 +31,6 @@ impl Client {
} }
impl Client { impl Client {
/// Access the Genres API
pub fn genres(&self) -> &api::genres::Client {
&self.genres
}
/// Access the Collections API /// Access the Collections API
pub fn collections(&self) -> &api::collections::Client { pub fn collections(&self) -> &api::collections::Client {
&self.collections &self.collections
+7
View File
@@ -1,3 +1,7 @@
use governor::clock::MonotonicClock;
use governor::state::{InMemoryState, NotKeyed};
use governor::{Quota, RateLimiter};
use nonzero_ext::nonzero;
use url::Url; use url::Url;
use url_macro::url; use url_macro::url;
@@ -7,6 +11,8 @@ pub struct Config {
pub base_url: Url, pub base_url: Url,
/// The reqwest client that is used for every request /// The reqwest client that is used for every request
pub client: reqwest::Client, pub client: reqwest::Client,
/// The rate limiter to use for the client
pub limiter: RateLimiter<NotKeyed, InMemoryState, MonotonicClock>,
/// The bearer token for readonly access to the API /// The bearer token for readonly access to the API
pub bearer_token: String, pub bearer_token: String,
/// An optional user agent string to provide to the API /// An optional user agent string to provide to the API
@@ -19,6 +25,7 @@ impl Config {
Self { Self {
base_url: url!("https://api.themoviedb.org"), base_url: url!("https://api.themoviedb.org"),
client: reqwest::Client::new(), client: reqwest::Client::new(),
limiter: RateLimiter::direct(Quota::per_second(nonzero!(30u32))),
bearer_token, bearer_token,
user_agent: None, user_agent: None,
} }
+2 -2
View File
@@ -1,8 +1,8 @@
//! flix-tmdb provides clients and models for fetching data from TMDB //! flix-tmdb provides clients and models for fetching data from TMDB
/// TMDB API clients #![cfg_attr(docsrs, feature(doc_cfg))]
pub mod api; pub mod api;
/// Deserializable types from the TMDB API
pub mod model; pub mod model;
mod client; mod client;
+3 -1
View File
@@ -1,4 +1,4 @@
use super::{CollectionId, MovieId}; use super::id::{CollectionId, MovieId};
/// A deserialized Collection from the TMDB API /// A deserialized Collection from the TMDB API
#[derive(Debug, Clone, serde::Deserialize)] #[derive(Debug, Clone, serde::Deserialize)]
@@ -20,4 +20,6 @@ pub struct Collection {
pub struct Item { pub struct Item {
/// The movie's TMDB ID /// The movie's TMDB ID
pub id: MovieId, pub id: MovieId,
/// The movie's title
pub title: String,
} }
+10 -1
View File
@@ -1,10 +1,16 @@
use core::time::Duration;
use flix_model::numbers::EpisodeNumber;
use chrono::NaiveDate; use chrono::NaiveDate;
use super::duration_from_minutes;
/// A deserialized Episode from the TMDB API /// A deserialized Episode from the TMDB API
#[derive(Debug, Clone, serde::Deserialize)] #[derive(Debug, Clone, serde::Deserialize)]
pub struct Episode { pub struct Episode {
/// The episode's number /// The episode's number
pub episode_number: u32, pub episode_number: EpisodeNumber,
/// The episode's title /// The episode's title
#[serde(rename = "name")] #[serde(rename = "name")]
pub title: String, pub title: String,
@@ -12,4 +18,7 @@ pub struct Episode {
pub overview: String, pub overview: String,
/// The episode's air date /// The episode's air date
pub air_date: NaiveDate, pub air_date: NaiveDate,
/// The movie's runtime
#[serde(deserialize_with = "duration_from_minutes")]
pub runtime: Duration,
} }
-19
View File
@@ -1,19 +0,0 @@
use super::id::{MovieGenreId, ShowGenreId};
/// A deserialized movie Genre from the TMDB API
#[derive(Debug, Clone, serde::Deserialize)]
pub struct MovieGenre {
/// The genre's TMDB ID
pub id: MovieGenreId,
/// The genre's name
pub name: String,
}
/// A deserialized show Genre from the TMDB API
#[derive(Debug, Clone, serde::Deserialize)]
pub struct ShowGenre {
/// The genre's TMDB ID
pub id: ShowGenreId,
/// The genre's name
pub name: String,
}
+215 -63
View File
@@ -1,90 +1,242 @@
//! Typed TMDB IDs
use core::cmp::Ordering;
use core::fmt; use core::fmt;
use core::hash::{Hash, Hasher}; use core::hash::{Hash, Hasher};
use core::marker::PhantomData; use core::marker::PhantomData;
/// The TMDB ID type of a movie genre #[cfg(feature = "sea-orm")]
pub type MovieGenreId = TmdbId<MovieGenre>; use sea_orm::sea_query::{ArrayType, Nullable, ValueType, ValueTypeErr};
/// The TMDB ID type of a show genre #[cfg(feature = "sea-orm")]
pub type ShowGenreId = TmdbId<ShowGenre>; use sea_orm::{ColIdx, ColumnType, DbErr, QueryResult, TryFromU64, TryGetError, TryGetable, Value};
/// The TMDB ID type of a collection
pub type CollectionId = TmdbId<Collection>;
/// The TMDB ID type of a movie
pub type MovieId = TmdbId<Movie>;
/// The TMDB ID type of a show
pub type ShowId = TmdbId<Show>;
pub enum MovieGenre {} /// The internal representation used by TMDB
pub enum ShowGenre {} pub type TmdbRepr = u32;
pub enum Collection {}
pub enum Movie {}
pub enum Show {}
/// The inner type of TmdbId /// An opaque type representing a TMDB ID
pub type Inner = u32;
/// Wraps an ID from TMDB, the generic parameter is to enforce that
/// IDs for different types of media are not interchangeable
#[derive(serde::Serialize, serde::Deserialize)] #[derive(serde::Serialize, serde::Deserialize)]
#[serde(transparent)] #[serde(transparent)]
#[repr(transparent)] #[repr(transparent)]
pub struct TmdbId<T> { pub struct Id<T> {
inner: Inner, id: TmdbRepr,
#[serde(skip_serializing, default)] #[serde(skip_serializing, default)]
_phantom: PhantomData<T>, _phantom: PhantomData<T>,
} }
impl<T> TmdbId<T> { // Manual implementation since `T: Clone` is not required
/// Extract the inner value impl<T> Clone for Id<T> {
pub fn inner(self) -> Inner {
self.inner
}
}
impl<T> From<Inner> for TmdbId<T> {
fn from(value: Inner) -> Self {
Self {
inner: value,
_phantom: PhantomData,
}
}
}
impl<T> From<TmdbId<T>> for Inner {
fn from(value: TmdbId<T>) -> Self {
value.inner
}
}
impl<T> fmt::Debug for TmdbId<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.inner.fmt(f)
}
}
impl<T> fmt::Display for TmdbId<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.inner.fmt(f)
}
}
impl<T> Clone for TmdbId<T> {
fn clone(&self) -> Self { fn clone(&self) -> Self {
*self *self
} }
} }
impl<T> Copy for TmdbId<T> {} // Manual implementation since `T: Copy` is not required
impl<T> Copy for Id<T> {}
impl<T> PartialEq for TmdbId<T> { // Manual implementation since `T: PartialEq` is not required
impl<T> PartialEq for Id<T> {
fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool {
self.inner == other.inner self.id == other.id
} }
} }
impl<T> Eq for TmdbId<T> {} // Manual implementation since `T: Eq` is not required
impl<T> Eq for Id<T> {}
impl<T> Hash for TmdbId<T> { // Manual implementation since `T: PartialOrd` is not required
impl<T> PartialOrd for Id<T> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
// Manual implementation since `T: Ord` is not required
impl<T> Ord for Id<T> {
fn cmp(&self, other: &Self) -> Ordering {
self.id.cmp(&other.id)
}
}
// Manual implementation since `T: Hash` is not required
impl<T> Hash for Id<T> {
fn hash<H: Hasher>(&self, state: &mut H) { fn hash<H: Hasher>(&self, state: &mut H) {
self.inner.hash(state); self.id.hash(state);
}
}
impl<T> Id<T> {
/// Allows the conversion from a raw value to [Id], though the use is discouraged.
pub fn from_raw(raw: TmdbRepr) -> Self {
Self {
id: raw,
_phantom: PhantomData,
}
}
/// Allows extracting the raw value, though the use is discouraged.
pub fn into_raw(self) -> TmdbRepr {
self.id
}
}
impl<T> fmt::Debug for Id<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Id")
.field("T", &core::any::type_name::<T>())
.field("id", &self.id)
.finish()
}
}
#[cfg(feature = "sea-orm")]
impl<T> ValueType for Id<T> {
fn try_from(v: Value) -> Result<Self, ValueTypeErr> {
<TmdbRepr as ValueType>::try_from(v).map(|id| Self {
id,
_phantom: PhantomData,
})
}
fn type_name() -> String {
format!("Id<{}>", &core::any::type_name::<T>())
}
fn array_type() -> ArrayType {
TmdbRepr::array_type()
}
fn column_type() -> ColumnType {
TmdbRepr::column_type()
}
}
#[cfg(feature = "sea-orm")]
impl<T> From<Id<T>> for Value {
fn from(value: Id<T>) -> Self {
value.id.into()
}
}
#[cfg(feature = "sea-orm")]
impl<T> TryGetable for Id<T> {
fn try_get_by<I: ColIdx>(res: &QueryResult, index: I) -> Result<Self, TryGetError> {
TmdbRepr::try_get_by(res, index).map(|id| Self {
id,
_phantom: PhantomData,
})
}
}
#[cfg(feature = "sea-orm")]
impl<T> TryFromU64 for Id<T> {
fn try_from_u64(n: u64) -> Result<Self, DbErr> {
TmdbRepr::try_from_u64(n).map(|id| Self {
id,
_phantom: PhantomData,
})
}
}
#[cfg(feature = "sea-orm")]
impl<T> Nullable for Id<T> {
fn null() -> Value {
TmdbRepr::null()
}
}
#[cfg(test)]
mod tests {
#[test]
#[cfg(feature = "sea-orm")]
fn test_sea_orm() {
use sea_orm::{
ActiveModelBehavior, DeriveEntityModel, DerivePrimaryKey, DeriveRelation, EntityTrait,
EnumIter, PrimaryKeyTrait,
};
use super::Id;
#[allow(dead_code)]
#[derive(Debug, Clone, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "ids")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
id: Id<Model>,
nullable: Option<Id<Model>>,
}
impl ActiveModelBehavior for ActiveModel {}
#[allow(dead_code)]
#[derive(Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
}
#[test]
fn test_serde() {
use super::Id;
let id: Id<()> = Id::from_raw(1234);
serde_test::assert_tokens(&id, &[serde_test::Token::U32(1234)]);
}
}
/// Type alias for the raw ID representation
pub use self::TmdbRepr as RawId;
#[doc(hidden)]
pub enum Collection {}
/// Type alias for a collection ID
pub type CollectionId = Id<Collection>;
impl From<CollectionId> for flix_model::id::CollectionId {
fn from(value: CollectionId) -> Self {
Self::from_raw(value.into_raw().into())
}
}
impl TryFrom<flix_model::id::CollectionId> for CollectionId {
type Error = <RawId as TryFrom<flix_model::id::RawId>>::Error;
fn try_from(value: flix_model::id::CollectionId) -> Result<Self, Self::Error> {
value.into_raw().try_into().map(Self::from_raw)
}
}
#[doc(hidden)]
pub enum Movie {}
/// Type alias for a movie ID
pub type MovieId = Id<Movie>;
impl From<MovieId> for flix_model::id::MovieId {
fn from(value: MovieId) -> Self {
Self::from_raw(value.into_raw().into())
}
}
impl TryFrom<flix_model::id::MovieId> for MovieId {
type Error = <RawId as TryFrom<flix_model::id::RawId>>::Error;
fn try_from(value: flix_model::id::MovieId) -> Result<Self, Self::Error> {
value.into_raw().try_into().map(Self::from_raw)
}
}
#[doc(hidden)]
pub enum Show {}
/// Type alias for a show ID
pub type ShowId = Id<Show>;
impl From<ShowId> for flix_model::id::ShowId {
fn from(value: ShowId) -> Self {
Self::from_raw(value.into_raw().into())
}
}
impl TryFrom<flix_model::id::ShowId> for ShowId {
type Error = <RawId as TryFrom<flix_model::id::RawId>>::Error;
fn try_from(value: flix_model::id::ShowId) -> Result<Self, Self::Error> {
value.into_raw().try_into().map(Self::from_raw)
} }
} }
+15 -6
View File
@@ -1,18 +1,27 @@
//! Deserializable types from the TMDB API
use core::time::Duration;
use serde::{Deserialize, Deserializer};
pub mod id;
mod collection; mod collection;
mod episode; mod episode;
mod genre;
mod id;
mod movie; mod movie;
mod season; mod season;
mod show; mod show;
pub use collection::*; pub use collection::*;
pub use episode::*; pub use episode::*;
pub use genre::*;
pub use movie::*; pub use movie::*;
pub use season::*; pub use season::*;
pub use serde::*;
pub use show::*; pub use show::*;
pub use id::{CollectionId, MovieGenreId, MovieId, ShowGenreId, ShowId}; fn duration_from_minutes<'de, D>(deserializer: D) -> Result<Duration, D::Error>
pub use id::{Inner as TmdbIdInner, TmdbId}; where
D: Deserializer<'de>,
{
let minutes = u64::deserialize(deserializer)?;
Ok(Duration::from_secs(minutes.saturating_mul(60)))
}
+19 -27
View File
@@ -1,6 +1,9 @@
use core::time::Duration;
use chrono::NaiveDate; use chrono::NaiveDate;
use super::{CollectionId, MovieGenre, MovieId}; use super::duration_from_minutes;
use super::id::{CollectionId, MovieId};
/// A deserialized Movie from the TMDB API /// A deserialized Movie from the TMDB API
#[derive(Debug, Clone, serde::Deserialize)] #[derive(Debug, Clone, serde::Deserialize)]
@@ -12,14 +15,15 @@ pub struct Movie {
pub collection: Option<InCollection>, pub collection: Option<InCollection>,
/// The movie's title /// The movie's title
pub title: String, pub title: String,
/// The movie's tagline
pub tagline: String,
/// The movie's overview /// The movie's overview
pub overview: String, pub overview: String,
/// The list of genres the movie belongs to
pub genres: Vec<MovieGenre>,
/// The movie's release date /// The movie's release date
pub release_date: NaiveDate, pub release_date: NaiveDate,
/// The movie's status /// The movie's runtime
pub status: MovieStatus, #[serde(deserialize_with = "duration_from_minutes")]
pub runtime: Duration,
} }
/// A deserialized movie's collection from the TMDB API /// A deserialized movie's collection from the TMDB API
@@ -27,27 +31,15 @@ pub struct Movie {
pub struct InCollection { pub struct InCollection {
/// The collection's TMDB ID /// The collection's TMDB ID
pub id: CollectionId, pub id: CollectionId,
/// The collection's title
#[serde(rename = "name")]
pub title: String,
} }
/// A deserialized movie status from the TMDB API // TODO: Genres
#[derive(Debug, Clone, Copy, serde::Deserialize)] // pub genres: Vec<Genre>,
pub enum MovieStatus { // where: struct Genre { id, name }
/// The movie was cancelled
#[serde(rename = "Canceled")] // TODO: Company
Canceled, // pub companies: Vec<Company>
/// The movie is in production // where: struct Company { id, name }
#[serde(rename = "In Production")]
InProduction,
/// The movie is planned
#[serde(rename = "Planned")]
Planned,
/// The movie is in post production
#[serde(rename = "Post Production")]
PostProduction,
/// The movie is released
#[serde(rename = "Released")]
Released,
/// The movie is rumored
#[serde(rename = "Rumored")]
Rumored,
}
+8 -4
View File
@@ -1,12 +1,12 @@
use chrono::NaiveDate; use chrono::NaiveDate;
use super::Episode; use flix_model::numbers::SeasonNumber;
/// A deserialized Season from the TMDB API /// A deserialized Season from the TMDB API
#[derive(Debug, Clone, serde::Deserialize)] #[derive(Debug, Clone, serde::Deserialize)]
pub struct Season { pub struct Season {
/// The season's number /// The season's number
pub season_number: u32, pub season_number: SeasonNumber,
/// The season's title /// The season's title
#[serde(rename = "name")] #[serde(rename = "name")]
pub title: String, pub title: String,
@@ -14,6 +14,10 @@ pub struct Season {
pub overview: String, pub overview: String,
/// The season's air date /// The season's air date
pub air_date: NaiveDate, pub air_date: NaiveDate,
/// The list of episodes in this season /// The number of episodes in this season
pub episodes: Vec<Episode>, pub episodes: Vec<FakeEpisode>,
} }
/// A placeholder struct for parsing the episodes list for a season
#[derive(Debug, Clone, serde::Deserialize)]
pub struct FakeEpisode {}
+16 -27
View File
@@ -1,6 +1,6 @@
use chrono::NaiveDate; use chrono::NaiveDate;
use super::{ShowGenre, ShowId}; use super::id::ShowId;
/// A deserialized Show from the TMDB API /// A deserialized Show from the TMDB API
#[derive(Debug, Clone, serde::Deserialize)] #[derive(Debug, Clone, serde::Deserialize)]
@@ -10,39 +10,28 @@ pub struct Show {
/// The show's title /// The show's title
#[serde(rename = "name")] #[serde(rename = "name")]
pub title: String, pub title: String,
/// The show's tagline
pub tagline: String,
/// The show's overview /// The show's overview
pub overview: String, pub overview: String,
/// The list of genres this show belongs to
pub genres: Vec<ShowGenre>,
/// The show's first air date /// The show's first air date
pub first_air_date: NaiveDate, pub first_air_date: NaiveDate,
/// The show's last air date /// The show's last air date
pub last_air_date: NaiveDate, pub last_air_date: NaiveDate,
/// The total number of episodes in this show
pub number_of_episodes: u32,
/// The number of seasons in this show /// The number of seasons in this show
pub number_of_seasons: u32, pub number_of_seasons: u32,
/// The show's status
pub status: ShowStatus,
} }
/// A deserialized show Status from the TMDB API // TODO: Genres
#[derive(Debug, Clone, Copy, serde::Deserialize)] // pub genres: Vec<Genre>,
pub enum ShowStatus { // where: struct Genre { id, name }
/// The show is returning
#[serde(rename = "Returning Series")] // TODO: Network
Returning, // pub networks: Vec<Network>
/// The show is planned // where: struct Network { id, name }
#[serde(rename = "Planned")]
Planned, // TODO: Company
/// The show is in procuction // pub companies: Vec<Company>
#[serde(rename = "In Production")] // where: struct Company { id, name }
InProduction,
/// The show has ended
#[serde(rename = "Ended")]
Ended,
/// The show is canceled
#[serde(rename = "Canceled")]
Canceled,
/// The show only released a pilot
#[serde(rename = "Pilot")]
Pilot,
}
+5
View File
@@ -0,0 +1,5 @@
toml-version = "v1.0.0"
[format.rules]
indent-style = "tab"
indent-width = 4