You've already forked flix
Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
6eec67a0fd
|
|||
|
06110b91a1
|
|||
|
ba9c3fa03d
|
|||
|
ced1fe8194
|
|||
|
2b348851d7
|
|||
|
73c5e4af9b
|
|||
|
62e933448c
|
|||
|
492f054e23
|
Generated
+1917
-360
File diff suppressed because it is too large
Load Diff
+20
-3
@@ -12,6 +12,7 @@ rust-version = "1.85.0"
|
||||
arithmetic_overflow = "forbid"
|
||||
missing_docs = "forbid"
|
||||
unsafe_code = "forbid"
|
||||
unused_doc_comments = "forbid"
|
||||
|
||||
[workspace.lints.clippy]
|
||||
arithmetic_side_effects = "forbid"
|
||||
@@ -34,17 +35,33 @@ overflow-checks = true
|
||||
strip = "debuginfo"
|
||||
|
||||
[workspace.dependencies]
|
||||
flix = { path = "crates/flix", version = "=0.0.2", default-features = false }
|
||||
flix-tmdb = { path = "crates/tmdb", version = "=0.0.2", default-features = false }
|
||||
flix = { path = "crates/flix", version = "=0.0.10", default-features = false }
|
||||
flix-cli = { path = "crates/cli", version = "=0.0.10", default-features = false }
|
||||
flix-db = { path = "crates/db", version = "=0.0.10", default-features = false }
|
||||
flix-fs = { path = "crates/fs", version = "=0.0.10", default-features = false }
|
||||
flix-model = { path = "crates/model", version = "=0.0.10", default-features = false }
|
||||
flix-tmdb = { path = "crates/tmdb", version = "=0.0.10", default-features = false }
|
||||
|
||||
seamantic = { version = "0.0.6", default-features = false }
|
||||
|
||||
sea-orm = { version = "2.0.0-rc.7", default-features = false }
|
||||
sea-orm-migration = { version = "2.0.0-rc.7", default-features = false }
|
||||
|
||||
anyhow = { version = "^1", default-features = false }
|
||||
async-stream = { version = "^0.3", 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 }
|
||||
governor = { version = "^0.10", default-features = false }
|
||||
home = { version = "^0.5", default-features = false }
|
||||
nonzero_ext = { version = "^0.3", default-features = false }
|
||||
regex = { version = "^1", default-features = false }
|
||||
reqwest = { version = "^0.12", 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 }
|
||||
toml = { version = "^0.8", default-features = false }
|
||||
tokio-stream = { version = "^0.1", default-features = false }
|
||||
toml = { version = "^0.9", default-features = false }
|
||||
url = { version = "^2", default-features = false }
|
||||
url-macro = { version = "^0.2", default-features = false }
|
||||
|
||||
@@ -6,9 +6,10 @@ Libraries and tools for dealing with media metadata
|
||||
|
||||
- build: `cargo hack --feature-powerset build`
|
||||
- clippy: `cargo hack --feature-powerset clippy -- -D warnings`
|
||||
- test: `cargo hack --feature-powerset test`
|
||||
- test old: `cargo +1.85 hack --feature-powerset test`
|
||||
- fmt: `cargo fmt --check`
|
||||
- docs: `RUSTDOCFLAGS="--cfg docsrs" cargo +nightly doc --all-features`
|
||||
- install: `cargo install --path crates/cli`
|
||||
- publish: `cargo publish --dry-run -p flix-tmdb`
|
||||
- publish: `cargo publish --dry-run -p flix`
|
||||
- publish: `cargo publish --dry-run -p flix-cli`
|
||||
- semver: `cargo semver-checks --all-features`
|
||||
- publish: `cargo publish --dry-run --workspace`
|
||||
|
||||
+10
-4
@@ -1,9 +1,9 @@
|
||||
[package]
|
||||
name = "flix-cli"
|
||||
version = "0.0.2"
|
||||
version = "0.0.10"
|
||||
|
||||
categories = ["command-line-utilities"]
|
||||
description = "CLI for interacting with flix media"
|
||||
description = "CLI for interacting with a flix database"
|
||||
repository = "https://github.com/QuantumShade/flix"
|
||||
|
||||
authors.workspace = true
|
||||
@@ -11,6 +11,10 @@ edition.workspace = true
|
||||
license-file.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
|
||||
[[bin]]
|
||||
doc = false
|
||||
name = "flix"
|
||||
@@ -35,9 +39,9 @@ unwrap_used = "deny"
|
||||
|
||||
[dependencies]
|
||||
flix = { workspace = true, features = ["tmdb"] }
|
||||
flix-tmdb = { workspace = true }
|
||||
|
||||
anyhow = { workspace = true }
|
||||
chrono = { workspace = true, features = ["now"] }
|
||||
clap = { workspace = true, features = [
|
||||
"derive",
|
||||
"color",
|
||||
@@ -46,7 +50,9 @@ clap = { workspace = true, features = [
|
||||
"suggestions",
|
||||
"usage",
|
||||
] }
|
||||
futures = { workspace = true }
|
||||
home = { workspace = true }
|
||||
sea-orm = { workspace = true, features = ["runtime-tokio"] }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
tokio = { workspace = true, features = ["rt", "fs", "macros"] }
|
||||
toml = { workspace = true, features = ["display", "parse"] }
|
||||
toml = { workspace = true, features = ["parse", "serde"] }
|
||||
|
||||
@@ -2,4 +2,10 @@
|
||||
|
||||
[](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>
|
||||
```
|
||||
|
||||
+52
-25
@@ -1,5 +1,6 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::{Result, anyhow};
|
||||
use clap::{Parser, Subcommand};
|
||||
|
||||
pub mod tmdb;
|
||||
@@ -7,9 +8,13 @@ pub mod tmdb;
|
||||
#[derive(Parser)]
|
||||
#[command(version, about, long_about = None)]
|
||||
pub struct Cli {
|
||||
/// Use a custom config file [default: ~/.flix]
|
||||
#[arg(short, long, value_name = "FILE")]
|
||||
config: Option<PathBuf>,
|
||||
/// Use a custom config file
|
||||
#[arg(short, long, value_name = "FILE", default_value = "~/.flix")]
|
||||
config: PathBuf,
|
||||
|
||||
/// Use a custom database file
|
||||
#[arg(short, long, value_name = "DATABASE", default_value = "./flix.db")]
|
||||
database: PathBuf,
|
||||
|
||||
#[command(subcommand)]
|
||||
command: Command,
|
||||
@@ -17,40 +22,61 @@ pub struct Cli {
|
||||
|
||||
impl Cli {
|
||||
pub fn config_path(&self) -> PathBuf {
|
||||
match self.config.as_ref() {
|
||||
Some(path) => match path.strip_prefix("~/") {
|
||||
fn expect_home_dir() -> PathBuf {
|
||||
#[allow(clippy::expect_used)]
|
||||
home::home_dir().expect("you do not have a home directory")
|
||||
}
|
||||
|
||||
match self.config.strip_prefix("~/") {
|
||||
Ok(path) => expect_home_dir().join(path),
|
||||
Err(_) => path.to_owned(),
|
||||
},
|
||||
None => expect_home_dir().join(".flix"),
|
||||
Err(_) => self.config.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn command(&self) -> &Command {
|
||||
&self.command
|
||||
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 {
|
||||
self.command
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
pub enum Command {
|
||||
/// Print a flix manifest
|
||||
Print {
|
||||
/// Initialize a new database
|
||||
Init,
|
||||
/// Add new items to the database
|
||||
Add {
|
||||
#[command(subcommand)]
|
||||
command: BackendCommand,
|
||||
},
|
||||
/// Write a flix manifest if the destination does not exist
|
||||
Write {
|
||||
/// Overwrite the destination
|
||||
#[arg(short, long, default_value_t = false)]
|
||||
force: bool,
|
||||
|
||||
/// Change the destination
|
||||
#[arg(short, long, value_name = "FILE")]
|
||||
output: Option<PathBuf>,
|
||||
|
||||
/// Update an existing item in the database
|
||||
Update {
|
||||
#[command(subcommand)]
|
||||
command: BackendCommand,
|
||||
},
|
||||
/// Delete an existing item in the database
|
||||
Delete {
|
||||
#[command(subcommand)]
|
||||
command: BackendCommand,
|
||||
},
|
||||
/// Create a toml backup of the database
|
||||
Backup {
|
||||
/// Change the destination
|
||||
#[arg(short, long, value_name = "FILE", default_value = "./flix.toml")]
|
||||
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)]
|
||||
@@ -62,7 +88,8 @@ pub enum BackendCommand {
|
||||
},
|
||||
}
|
||||
|
||||
fn expect_home_dir() -> PathBuf {
|
||||
#[allow(clippy::expect_used)]
|
||||
home::home_dir().expect("you do not have a home directory")
|
||||
impl From<tmdb::Command> for BackendCommand {
|
||||
fn from(value: tmdb::Command) -> Self {
|
||||
Self::Tmdb { command: value }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
use flix::model::numbers::{EpisodeNumber, SeasonNumber};
|
||||
use flix::tmdb::model::id::RawId;
|
||||
|
||||
use clap::Subcommand;
|
||||
|
||||
#[derive(Subcommand)]
|
||||
@@ -5,32 +8,35 @@ pub enum Command {
|
||||
/// Process a TMDB collection
|
||||
Collection {
|
||||
#[arg(value_name = "TMDB_ID")]
|
||||
id: i32,
|
||||
id: RawId,
|
||||
},
|
||||
/// Process a TMDB movie
|
||||
Movie {
|
||||
#[arg(value_name = "TMDB_ID")]
|
||||
id: i32,
|
||||
id: RawId,
|
||||
},
|
||||
/// Process a TMDB show
|
||||
Show {
|
||||
#[arg(value_name = "TMDB_ID")]
|
||||
id: i32,
|
||||
id: RawId,
|
||||
},
|
||||
/// Process a TMDB season
|
||||
Season {
|
||||
#[arg(value_name = "TMDB_ID")]
|
||||
id: i32,
|
||||
id: RawId,
|
||||
#[arg(value_name = "SEASON_NUM")]
|
||||
season: i32,
|
||||
season: SeasonNumber,
|
||||
},
|
||||
/// Process a TMDB episode
|
||||
#[command(trailing_var_arg = true)]
|
||||
Episode {
|
||||
#[arg(value_name = "TMDB_ID")]
|
||||
id: i32,
|
||||
id: RawId,
|
||||
#[arg(value_name = "SEASON_NUM")]
|
||||
season: i32,
|
||||
season: SeasonNumber,
|
||||
#[arg(value_name = "EPISODE_NUM")]
|
||||
episode: i32,
|
||||
episode: EpisodeNumber,
|
||||
#[arg(value_name = "...")]
|
||||
episodes: Vec<EpisodeNumber>,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
//! Placeholder
|
||||
|
||||
#![cfg_attr(docsrs, feature(doc_cfg))]
|
||||
+66
-36
@@ -1,4 +1,6 @@
|
||||
use flix_tmdb::Client;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use flix::tmdb::Client;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use clap::Parser;
|
||||
@@ -9,8 +11,8 @@ use cli::{BackendCommand, Cli, Command};
|
||||
|
||||
mod config;
|
||||
use config::Config;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
|
||||
mod db;
|
||||
mod run;
|
||||
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
@@ -22,44 +24,72 @@ async fn main() -> Result<()> {
|
||||
let config: Config = toml::from_str(config.as_str())
|
||||
.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());
|
||||
|
||||
match cli.command() {
|
||||
Command::Print { command } => match command {
|
||||
BackendCommand::Tmdb { command } => {
|
||||
let object = run::tmdb::TmdbObject::fetch(&client, command).await?;
|
||||
println!("{}", object.serialize().context("failed to serialize")?)
|
||||
}
|
||||
},
|
||||
Command::Write {
|
||||
force,
|
||||
output,
|
||||
command,
|
||||
} => match command {
|
||||
BackendCommand::Tmdb { command } => {
|
||||
let object = run::tmdb::TmdbObject::fetch(&client, command).await?;
|
||||
let output = output
|
||||
.as_ref()
|
||||
.map(|p| p.as_path())
|
||||
.unwrap_or(object.default_filename());
|
||||
|
||||
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()))?;
|
||||
}
|
||||
},
|
||||
Command::Init => exec_init(database_path).await?,
|
||||
Command::Add { command } => exec_add(client, database_path, command).await?,
|
||||
Command::Update { command } => exec_update(client, database_path, command).await?,
|
||||
Command::Delete { command } => exec_delete(client, database_path, command).await?,
|
||||
Command::Backup { output } => exec_backup(database_path, output).await?,
|
||||
Command::Restore { input } => exec_restore(database_path, input).await?,
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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: BackendCommand) -> Result<()> {
|
||||
let database = db::open(database_path).await?;
|
||||
|
||||
match command {
|
||||
BackendCommand::Tmdb { command } => {
|
||||
run::tmdb::add(client, database.as_ref(), command).await?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn exec_update(client: Client, database_path: String, command: BackendCommand) -> Result<()> {
|
||||
let database = db::open(database_path).await?;
|
||||
|
||||
match command {
|
||||
BackendCommand::Tmdb { command } => {
|
||||
run::tmdb::update(client, database.as_ref(), command).await?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn exec_delete(client: Client, database_path: String, command: BackendCommand) -> Result<()> {
|
||||
let database = db::open(database_path).await?;
|
||||
|
||||
match command {
|
||||
BackendCommand::Tmdb { command } => {
|
||||
run::tmdb::delete(client, database.as_ref(), command).await?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn exec_backup(database_path: String, output: PathBuf) -> Result<()> {
|
||||
_ = database_path;
|
||||
_ = output;
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
async fn exec_restore(database_path: String, input: PathBuf) -> Result<()> {
|
||||
_ = database_path;
|
||||
_ = input;
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
+477
-101
@@ -1,131 +1,507 @@
|
||||
use std::path::Path;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use flix::model::{
|
||||
Collection, Episode, GenericCollection, GenericEpisode, GenericMovie, GenericSeason,
|
||||
GenericShow, Movie, Season, Show, TmdbCollection, TmdbMovie, TmdbShow,
|
||||
};
|
||||
use flix_tmdb::Client;
|
||||
use flix_tmdb::model::{
|
||||
Collection as TCollection, Episode as TEpisode, Movie as TMovie, Season as TSeason,
|
||||
Show as TShow,
|
||||
use flix::db::entity;
|
||||
use flix::model::id::{CollectionId, MovieId, ShowId};
|
||||
use flix::model::numbers::{EpisodeNumber, SeasonNumber};
|
||||
use flix::tmdb::Client;
|
||||
use flix::tmdb::model::id::{
|
||||
CollectionId as TmdbCollectionId, MovieId as TmdbMovieId, ShowId as TmdbShowId,
|
||||
};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use anyhow::{Context, Result, bail};
|
||||
use chrono::Utc;
|
||||
use sea_orm::ActiveValue::{NotSet, Set};
|
||||
use sea_orm::{
|
||||
ActiveModelTrait, DatabaseConnection, DbErr, EntityTrait, TransactionError, TransactionTrait,
|
||||
};
|
||||
|
||||
use crate::cli::tmdb::Command;
|
||||
|
||||
pub enum TmdbObject {
|
||||
Collection(TCollection),
|
||||
Movie(TMovie),
|
||||
Show(TShow),
|
||||
Season(TSeason),
|
||||
Episode(TEpisode),
|
||||
pub async fn add(client: Client, db: &DatabaseConnection, command: Command) -> Result<()> {
|
||||
match command {
|
||||
Command::Collection { id } => {
|
||||
let id = TmdbCollectionId::from_raw(id);
|
||||
|
||||
let collection = entity::tmdb::collections::Entity::find_by_id(id)
|
||||
.one(db)
|
||||
.await?;
|
||||
if collection.is_some() {
|
||||
bail!("collection already exists");
|
||||
}
|
||||
|
||||
impl TmdbObject {
|
||||
pub fn default_filename(&self) -> &'static Path {
|
||||
Path::new(match self {
|
||||
TmdbObject::Collection(_) => "collection.toml",
|
||||
TmdbObject::Movie(_) => "movie.toml",
|
||||
TmdbObject::Show(_) => "show.toml",
|
||||
TmdbObject::Season(_) => "season.toml",
|
||||
TmdbObject::Episode(_) => "episode.toml",
|
||||
})
|
||||
}
|
||||
|
||||
pub fn serialize(self) -> Result<String> {
|
||||
Ok(match self {
|
||||
TmdbObject::Collection(tmdb) => toml::to_string(&Collection {
|
||||
collection: GenericCollection {
|
||||
name: tmdb.name,
|
||||
overview: tmdb.overview,
|
||||
},
|
||||
tmdb: Some(TmdbCollection { id: tmdb.id }),
|
||||
})?,
|
||||
TmdbObject::Movie(tmdb) => toml::to_string(&Movie {
|
||||
movie: GenericMovie {
|
||||
title: tmdb.title,
|
||||
overview: tmdb.overview,
|
||||
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 {
|
||||
name: tmdb.name,
|
||||
overview: tmdb.overview,
|
||||
air_date: tmdb.first_air_date,
|
||||
},
|
||||
tmdb: Some(TmdbShow {
|
||||
id: tmdb.id,
|
||||
genres: tmdb.genres.iter().map(|g| g.id).collect(),
|
||||
}),
|
||||
})?,
|
||||
TmdbObject::Season(tmdb) => toml::to_string(&Season {
|
||||
season: GenericSeason {
|
||||
name: tmdb.name,
|
||||
overview: tmdb.overview,
|
||||
air_date: tmdb.air_date,
|
||||
},
|
||||
})?,
|
||||
TmdbObject::Episode(tmdb) => toml::to_string(&Episode {
|
||||
episode: GenericEpisode {
|
||||
name: tmdb.name,
|
||||
overview: tmdb.overview,
|
||||
air_date: tmdb.air_date,
|
||||
},
|
||||
})?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TmdbObject {
|
||||
pub async fn fetch(client: &Client, command: &Command) -> Result<Self> {
|
||||
Ok(match *command {
|
||||
Command::Collection { id } => Self::Collection(
|
||||
client
|
||||
let collection = client
|
||||
.collections()
|
||||
.get_details(id, None)
|
||||
.await
|
||||
.with_context(|| format!("could not get collection details for '{id}'"))?,
|
||||
),
|
||||
Command::Movie { id } => Self::Movie(
|
||||
client
|
||||
.with_context(|| format!("collections().get_details({})", id.into_raw()))?;
|
||||
|
||||
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),
|
||||
}
|
||||
.insert(txn)
|
||||
.await?;
|
||||
|
||||
entity::tmdb::collections::ActiveModel {
|
||||
tmdb_id: Set(id),
|
||||
flix_id: Set(flix.id),
|
||||
last_update: Set(Utc::now().date_naive()),
|
||||
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: {}", flix_id.into_raw());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Command::Movie { id } => {
|
||||
let id = TmdbMovieId::from_raw(id);
|
||||
|
||||
let movie = entity::tmdb::movies::Entity::find_by_id(id).one(db).await?;
|
||||
if movie.is_some() {
|
||||
bail!("movie already exists");
|
||||
}
|
||||
|
||||
let movie = client
|
||||
.movies()
|
||||
.get_details(id, None)
|
||||
.await
|
||||
.with_context(|| format!("could not get movie details for '{id}'"))?,
|
||||
),
|
||||
Command::Show { id } => Self::Show(
|
||||
client
|
||||
.with_context(|| format!("movies().get_details({})", id.into_raw()))?;
|
||||
|
||||
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),
|
||||
}
|
||||
.insert(txn)
|
||||
.await?;
|
||||
|
||||
entity::tmdb::movies::ActiveModel {
|
||||
tmdb_id: Set(id),
|
||||
flix_id: Set(flix.id),
|
||||
last_update: Set(Utc::now().date_naive()),
|
||||
runtime: Set(movie.runtime.into()),
|
||||
collection: 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: {}", flix_id.into_raw());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Command::Show { id } => {
|
||||
let id = TmdbShowId::from_raw(id);
|
||||
|
||||
let show = entity::tmdb::shows::Entity::find_by_id(id).one(db).await?;
|
||||
if show.is_some() {
|
||||
bail!("show already exists");
|
||||
}
|
||||
|
||||
let show = client
|
||||
.shows()
|
||||
.get_details(id, None)
|
||||
.await
|
||||
.with_context(|| format!("could not get show details for '{id}'"))?,
|
||||
),
|
||||
Command::Season { id, season } => Self::Season(
|
||||
client
|
||||
.with_context(|| format!("shows().get_details({})", id.into_raw()))?;
|
||||
let mut seasons = Vec::new();
|
||||
let mut episodes = HashMap::new();
|
||||
|
||||
for season in 1..=show.number_of_seasons {
|
||||
let season = client
|
||||
.seasons()
|
||||
.get_details(id, season, None)
|
||||
.await
|
||||
.with_context(|| format!("could not get show details for '{id}' S{season}"))?,
|
||||
),
|
||||
.with_context(|| {
|
||||
format!("seasons().get_details({}, {})", id.into_raw(), season)
|
||||
})?;
|
||||
if season.air_date > Utc::now().date_naive() {
|
||||
eprintln!(
|
||||
"skipping season ({}, {})",
|
||||
id.into_raw(),
|
||||
season.season_number
|
||||
);
|
||||
break;
|
||||
}
|
||||
|
||||
let Ok(number_of_episodes) = EpisodeNumber::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 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 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),
|
||||
}
|
||||
.insert(txn)
|
||||
.await?;
|
||||
|
||||
entity::tmdb::shows::ActiveModel {
|
||||
tmdb_id: Set(id),
|
||||
flix_id: Set(flix.id),
|
||||
last_update: Set(Utc::now().date_naive()),
|
||||
number_of_seasons: Set(show.number_of_seasons),
|
||||
}
|
||||
.insert(txn)
|
||||
.await?;
|
||||
|
||||
for season in seasons {
|
||||
entity::info::seasons::ActiveModel {
|
||||
show: Set(flix.id),
|
||||
season: 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().date_naive()),
|
||||
}
|
||||
.insert(txn)
|
||||
.await?;
|
||||
}
|
||||
|
||||
for (season, episodes) in episodes {
|
||||
for episode in episodes {
|
||||
entity::info::episodes::ActiveModel {
|
||||
show: Set(flix.id),
|
||||
season: Set(season),
|
||||
episode: 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().date_naive()),
|
||||
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: {}", 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) = EpisodeNumber::try_from(season.episodes.len()) else {
|
||||
bail!(
|
||||
"could not convert {} to an EpisodeNumber",
|
||||
season.episodes.len()
|
||||
)
|
||||
};
|
||||
|
||||
for episode in 1..=number_of_episodes {
|
||||
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: Set(show.flix_id),
|
||||
season: 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().date_naive()),
|
||||
}
|
||||
.insert(txn)
|
||||
.await?;
|
||||
|
||||
for episode in episodes {
|
||||
entity::info::episodes::ActiveModel {
|
||||
show: Set(show.flix_id),
|
||||
season: Set(season_number),
|
||||
episode: 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().date_naive()),
|
||||
runtime: Set(episode.runtime.into()),
|
||||
}
|
||||
.insert(txn)
|
||||
.await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
})
|
||||
})
|
||||
.await;
|
||||
|
||||
match result {
|
||||
Ok(_) => (),
|
||||
Err(TransactionError::Connection(err)) => Err(err)?,
|
||||
Err(TransactionError::Transaction(err)) => Err(err)?,
|
||||
};
|
||||
println!(
|
||||
"Created Season: {} S{}",
|
||||
show.flix_id.into_raw(),
|
||||
season_number
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Command::Episode {
|
||||
id,
|
||||
season,
|
||||
episode,
|
||||
} => Self::Episode(
|
||||
client
|
||||
episodes,
|
||||
} => {
|
||||
let id = TmdbShowId::from_raw(id);
|
||||
let season_number = season;
|
||||
|
||||
let Some(show) = entity::tmdb::shows::Entity::find_by_id(id).one(db).await? else {
|
||||
bail!("show does not exists");
|
||||
};
|
||||
let Some(_) = entity::tmdb::seasons::Entity::find_by_id((id, season))
|
||||
.one(db)
|
||||
.await?
|
||||
else {
|
||||
bail!("season does not exists");
|
||||
};
|
||||
|
||||
async fn fetch_episode(
|
||||
client: &Client,
|
||||
db: &DatabaseConnection,
|
||||
flix_id: ShowId,
|
||||
tmdb_id: TmdbShowId,
|
||||
id: TmdbShowId,
|
||||
season: SeasonNumber,
|
||||
episode: EpisodeNumber,
|
||||
) -> Result<()> {
|
||||
let episode_number = episode;
|
||||
|
||||
let episode = entity::tmdb::episodes::Entity::find_by_id((id, season, episode))
|
||||
.one(db)
|
||||
.await?;
|
||||
if episode.is_some() {
|
||||
bail!("episode already exists");
|
||||
}
|
||||
|
||||
let episode = client
|
||||
.episodes()
|
||||
.get_details(id, season, episode, None)
|
||||
.get_details(id, season, episode_number, None)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!("could not get show details for '{id}' S{season}E{episode}")
|
||||
})?,
|
||||
),
|
||||
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: Set(flix_id),
|
||||
season: Set(season),
|
||||
episode: 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().date_naive()),
|
||||
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")
|
||||
}
|
||||
|
||||
pub async fn delete(client: Client, database: &DatabaseConnection, command: Command) -> Result<()> {
|
||||
_ = client;
|
||||
_ = database;
|
||||
_ = command;
|
||||
unimplemented!("deletions")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
[package]
|
||||
name = "flix-db"
|
||||
version = "0.0.10"
|
||||
|
||||
categories = []
|
||||
description = "Types for storing persistent data about media"
|
||||
repository = "https://github.com/QuantumShade/flix"
|
||||
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
license-file.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
default = []
|
||||
tmdb = ["dep:flix-tmdb"]
|
||||
|
||||
[dependencies]
|
||||
flix-model = { workspace = true }
|
||||
|
||||
flix-tmdb = { workspace = true, optional = true, features = ["sea-orm"] }
|
||||
|
||||
seamantic = { workspace = true, features = ["sqlite"] }
|
||||
|
||||
chrono = { workspace = true }
|
||||
sea-orm = { workspace = true, features = ["with-chrono"] }
|
||||
sea-orm-migration = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
sea-orm-migration = { workspace = true, features = ["runtime-tokio-rustls"] }
|
||||
tokio = { version = "^1", default-features = false, features = [
|
||||
"rt",
|
||||
"macros",
|
||||
] }
|
||||
@@ -0,0 +1,5 @@
|
||||
# flix-db
|
||||
|
||||
[](https://crates.io/crates/flix-db)
|
||||
|
||||
A library providing types for storing persistent data about media
|
||||
@@ -0,0 +1,22 @@
|
||||
//! 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 apllying database migrations while wrapping a
|
||||
/// [DatabaseConnection] in a newtype
|
||||
pub async fn try_from(database: DatabaseConnection) -> Result<Self, DbErr> {
|
||||
crate::migration::Migrator::up(&database, None).await?;
|
||||
Ok(Self(database))
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<DatabaseConnection> for Connection {
|
||||
fn as_ref(&self) -> &DatabaseConnection {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
//! Collection entity
|
||||
|
||||
use flix_model::id::{CollectionId, LibraryId};
|
||||
|
||||
use seamantic::model::path::PathBytes;
|
||||
|
||||
use sea_orm::{
|
||||
ActiveModelBehavior, DeriveEntityModel, DerivePrimaryKey, DeriveRelation, EntityTrait,
|
||||
EnumIter, PrimaryKeyTrait, Related, RelationDef, RelationTrait,
|
||||
};
|
||||
|
||||
/// The database representation of a collection media folder
|
||||
#[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
|
||||
pub parent: Option<CollectionId>,
|
||||
/// The collection's slug
|
||||
pub slug: String,
|
||||
/// The collection's library ID
|
||||
pub library: LibraryId,
|
||||
/// The collection's directory
|
||||
pub directory: PathBytes,
|
||||
/// The collection's poster path
|
||||
pub relative_poster_path: Option<String>,
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
|
||||
/// Relation
|
||||
#[derive(Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
/// The parent collection of this collection
|
||||
#[sea_orm(
|
||||
belongs_to = "super::collections::Entity",
|
||||
from = "Column::Parent",
|
||||
to = "super::collections::Column::Id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
Parent,
|
||||
/// The library this collection belongs to
|
||||
#[sea_orm(
|
||||
belongs_to = "super::libraries::Entity",
|
||||
from = "Column::Library",
|
||||
to = "super::libraries::Column::Id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
Library,
|
||||
/// The media info for this collection
|
||||
#[sea_orm(
|
||||
belongs_to = "super::super::info::collections::Entity",
|
||||
from = "Column::Id",
|
||||
to = "super::super::info::collections::Column::Id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
MediaInfo,
|
||||
/// The watched info for this collection
|
||||
#[sea_orm(
|
||||
belongs_to = "super::super::watched::collections::Entity",
|
||||
from = "Column::Id",
|
||||
to = "super::super::watched::collections::Column::Id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
WatchInfo,
|
||||
}
|
||||
|
||||
impl Related<super::collections::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Parent.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::libraries::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Library.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::super::info::collections::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::MediaInfo.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::super::watched::collections::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::WatchInfo.def()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
//! Episode entity
|
||||
|
||||
use flix_model::id::{LibraryId, ShowId};
|
||||
|
||||
use seamantic::model::path::PathBytes;
|
||||
|
||||
use flix_model::numbers::{EpisodeNumber, SeasonNumber};
|
||||
use sea_orm::{
|
||||
ActiveModelBehavior, DeriveEntityModel, DerivePrimaryKey, DeriveRelation, EntityTrait,
|
||||
EnumIter, PrimaryKeyTrait, Related, RelationDef, RelationTrait,
|
||||
};
|
||||
|
||||
/// The database representation of a episode media folder
|
||||
#[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: ShowId,
|
||||
/// The episode's season's number
|
||||
#[sea_orm(primary_key, auto_increment = false)]
|
||||
pub season: SeasonNumber,
|
||||
/// The episode's number
|
||||
#[sea_orm(primary_key, auto_increment = false)]
|
||||
pub episode: EpisodeNumber,
|
||||
/// The number of additional contained episodes
|
||||
pub count: u8,
|
||||
/// The episode's slug
|
||||
pub slug: String,
|
||||
/// The episode's library
|
||||
pub library: 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>,
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
|
||||
/// Relation
|
||||
#[derive(Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
/// The library this episode belongs to
|
||||
#[sea_orm(
|
||||
belongs_to = "super::libraries::Entity",
|
||||
from = "Column::Library",
|
||||
to = "super::libraries::Column::Id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
Library,
|
||||
/// The media info for this episode
|
||||
#[sea_orm(
|
||||
belongs_to = "super::super::info::seasons::Entity",
|
||||
from = "(Column::Show, Column::Season)",
|
||||
to = "(super::super::info::seasons::Column::Show, super::super::info::seasons::Column::Season)",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
MediaInfo,
|
||||
/// The watched info for this episode
|
||||
#[sea_orm(
|
||||
belongs_to = "super::super::watched::episodes::Entity",
|
||||
from = "(Column::Show, Column::Season, Column::Episode)",
|
||||
to = "(super::super::watched::episodes::Column::Show, super::super::watched::episodes::Column::Season, super::super::watched::episodes::Column::Episode)",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
WatchInfo,
|
||||
}
|
||||
|
||||
impl Related<super::libraries::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Library.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::super::info::episodes::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::MediaInfo.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::super::watched::episodes::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::WatchInfo.def()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
//! Library entity
|
||||
|
||||
use flix_model::id::LibraryId;
|
||||
|
||||
use seamantic::model::path::PathBytes;
|
||||
|
||||
use sea_orm::{
|
||||
ActiveModelBehavior, DeriveEntityModel, DerivePrimaryKey, DeriveRelation, EntityTrait,
|
||||
EnumIter, PrimaryKeyTrait, Related, RelationDef, RelationTrait,
|
||||
};
|
||||
|
||||
/// The database representation of a library media folder
|
||||
#[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,
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
|
||||
/// Relation
|
||||
#[derive(Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
/// All collections in this library
|
||||
#[sea_orm(has_many = "super::collections::Entity")]
|
||||
Collections,
|
||||
#[sea_orm(has_many = "super::movies::Entity")]
|
||||
/// All movies in this library
|
||||
Movies,
|
||||
#[sea_orm(has_many = "super::shows::Entity")]
|
||||
/// All shows in this library
|
||||
Shows,
|
||||
#[sea_orm(has_many = "super::seasons::Entity")]
|
||||
/// All seasons in this library
|
||||
Seasons,
|
||||
#[sea_orm(has_many = "super::episodes::Entity")]
|
||||
/// All episodes in this library
|
||||
Episodes,
|
||||
}
|
||||
|
||||
impl Related<super::collections::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Collections.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::movies::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Movies.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::shows::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Shows.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::seasons::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Seasons.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::episodes::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Episodes.def()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
//! This module contains entities for storing media file information
|
||||
|
||||
pub mod libraries;
|
||||
|
||||
pub mod collections;
|
||||
|
||||
pub mod movies;
|
||||
|
||||
pub mod episodes;
|
||||
pub mod seasons;
|
||||
pub mod shows;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::path::Path;
|
||||
|
||||
use flix_model::id::{CollectionId, LibraryId, MovieId, ShowId};
|
||||
|
||||
use sea_orm::ActiveModelTrait;
|
||||
use sea_orm::ActiveValue::{NotSet, Set};
|
||||
use sea_orm::sqlx::error::ErrorKind;
|
||||
use sea_orm_migration::MigratorTrait;
|
||||
|
||||
use crate::migration::Migrator;
|
||||
use crate::tests::new_memory_db;
|
||||
|
||||
use super::super::tests::get_error_kind;
|
||||
use super::super::tests::{
|
||||
make_flix_collection, make_flix_episode, make_flix_movie, make_flix_season, make_flix_show,
|
||||
};
|
||||
use super::super::tests::{noneable, notsettable};
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_inserts() {
|
||||
let db = new_memory_db().await;
|
||||
Migrator::up(&db, None).await.expect("up");
|
||||
|
||||
// Libraries
|
||||
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/", $id)).to_owned().into());
|
||||
};
|
||||
($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/", $id)).to_owned().into() $(, $($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);
|
||||
|
||||
// Collections
|
||||
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, $pid);
|
||||
assert_eq!(model.slug, concat!("C/", $id).to_string());
|
||||
assert_eq!(model.library, LibraryId::from_raw($lid));
|
||||
assert_eq!(model.directory, Path::new(concat!("/C/", $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: notsettable!(parent, $pid $(, $($skip),+)?),
|
||||
slug: notsettable!(slug, concat!("C/", $id).to_string() $(, $($skip),+)?),
|
||||
library: notsettable!(library, LibraryId::from_raw($lid) $(, $($skip),+)?),
|
||||
directory: notsettable!(directory, Path::new(concat!("/C/", $id)).to_owned().into() $(, $($skip),+)?),
|
||||
relative_poster_path: notsettable!(relative_poster_path, Some(concat!("C/Poster", $id).to_owned()) $(, $($skip),+)?),
|
||||
}.insert($db).await
|
||||
};
|
||||
}
|
||||
assert_collection!(&db, 1, None, 0, ForeignKeyViolation);
|
||||
assert_collection!(
|
||||
&db,
|
||||
1,
|
||||
Some(CollectionId::from_raw(0)),
|
||||
1,
|
||||
ForeignKeyViolation
|
||||
);
|
||||
assert_collection!(&db, 1, None, 1, ForeignKeyViolation);
|
||||
make_flix_collection!(&db, 1);
|
||||
make_flix_collection!(&db, 2);
|
||||
make_flix_collection!(&db, 3);
|
||||
make_flix_collection!(&db, 4);
|
||||
make_flix_collection!(&db, 8);
|
||||
|
||||
assert_collection!(&db, 1, None, 1, Success);
|
||||
assert_collection!(&db, 1, None, 1, UniqueViolation);
|
||||
assert_collection!(&db, 2, None, 1, Success);
|
||||
assert_collection!(&db, 3, None, 1, Success; id);
|
||||
assert_collection!(&db, 4, None, 1, Success; parent);
|
||||
assert_collection!(&db, 5, None, 1, NotNullViolation; slug);
|
||||
assert_collection!(&db, 6, None, 1, NotNullViolation; library);
|
||||
assert_collection!(&db, 7, None, 1, NotNullViolation; directory);
|
||||
assert_collection!(&db, 8, None, 1, Success; relative_poster_path);
|
||||
|
||||
// Movies
|
||||
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, $pid);
|
||||
assert_eq!(model.slug, concat!("M/", $id).to_string());
|
||||
assert_eq!(model.library, LibraryId::from_raw($lid));
|
||||
assert_eq!(model.directory, Path::new(concat!("/M/", $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: notsettable!(parent, $pid $(, $($skip),+)?),
|
||||
slug: notsettable!(slug, concat!("M/", $id).to_string() $(, $($skip),+)?),
|
||||
library: notsettable!(library, LibraryId::from_raw($lid) $(, $($skip),+)?),
|
||||
directory: notsettable!(directory, Path::new(concat!("/M/", $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
|
||||
};
|
||||
}
|
||||
assert_movie!(&db, 1, None, 0, ForeignKeyViolation);
|
||||
assert_movie!(
|
||||
&db,
|
||||
1,
|
||||
Some(CollectionId::from_raw(0)),
|
||||
1,
|
||||
ForeignKeyViolation
|
||||
);
|
||||
assert_movie!(&db, 1, None, 1, ForeignKeyViolation);
|
||||
make_flix_movie!(&db, 1);
|
||||
make_flix_movie!(&db, 2);
|
||||
make_flix_movie!(&db, 3);
|
||||
make_flix_movie!(&db, 4);
|
||||
make_flix_movie!(&db, 9);
|
||||
|
||||
assert_movie!(&db, 1, None, 1, Success);
|
||||
assert_movie!(&db, 1, None, 1, UniqueViolation);
|
||||
assert_movie!(&db, 2, None, 1, Success);
|
||||
assert_movie!(&db, 3, None, 1, Success; id);
|
||||
assert_movie!(&db, 4, None, 1, Success; parent);
|
||||
assert_movie!(&db, 5, None, 1, NotNullViolation; slug);
|
||||
assert_movie!(&db, 6, None, 1, NotNullViolation; library);
|
||||
assert_movie!(&db, 7, None, 1, NotNullViolation; directory);
|
||||
assert_movie!(&db, 8, None, 1, NotNullViolation; relative_media_path);
|
||||
assert_movie!(&db, 9, None, 1, Success; relative_poster_path);
|
||||
|
||||
// Shows
|
||||
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, $pid);
|
||||
assert_eq!(model.slug, concat!("S/", $id).to_string());
|
||||
assert_eq!(model.library, LibraryId::from_raw($lid));
|
||||
assert_eq!(model.directory, Path::new(concat!("/S/", $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: notsettable!(parent, $pid $(, $($skip),+)?),
|
||||
slug: notsettable!(slug, concat!("S/", $id).to_string() $(, $($skip),+)?),
|
||||
library: notsettable!(library, LibraryId::from_raw($lid) $(, $($skip),+)?),
|
||||
directory: notsettable!(directory, Path::new(concat!("/S/", $id)).to_owned().into() $(, $($skip),+)?),
|
||||
relative_poster_path: notsettable!(relative_poster_path, Some(concat!("S/Poster", $id).to_owned()) $(, $($skip),+)?),
|
||||
}.insert($db).await
|
||||
};
|
||||
}
|
||||
assert_show!(&db, 1, None, 0, ForeignKeyViolation);
|
||||
assert_show!(
|
||||
&db,
|
||||
1,
|
||||
Some(CollectionId::from_raw(0)),
|
||||
1,
|
||||
ForeignKeyViolation
|
||||
);
|
||||
assert_show!(&db, 1, None, 1, ForeignKeyViolation);
|
||||
make_flix_show!(&db, 1);
|
||||
make_flix_show!(&db, 2);
|
||||
make_flix_show!(&db, 3);
|
||||
make_flix_show!(&db, 4);
|
||||
make_flix_show!(&db, 8);
|
||||
|
||||
assert_show!(&db, 1, None, 1, Success);
|
||||
assert_show!(&db, 1, None, 1, UniqueViolation);
|
||||
assert_show!(&db, 2, None, 1, Success);
|
||||
assert_show!(&db, 3, None, 1, Success; id);
|
||||
assert_show!(&db, 4, None, 1, Success; parent);
|
||||
assert_show!(&db, 5, None, 1, NotNullViolation; slug);
|
||||
assert_show!(&db, 6, None, 1, NotNullViolation; library);
|
||||
assert_show!(&db, 7, None, 1, NotNullViolation; directory);
|
||||
assert_show!(&db, 8, None, 1, Success; relative_poster_path);
|
||||
|
||||
// Seasons
|
||||
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, ShowId::from_raw($id));
|
||||
assert_eq!(model.season, $season);
|
||||
assert_eq!(model.slug, concat!("S/S", $id).to_string());
|
||||
assert_eq!(model.library, LibraryId::from_raw($lid));
|
||||
assert_eq!(model.directory, Path::new(concat!("/S/S", $id)).to_owned().into());
|
||||
assert_eq!(model.relative_poster_path, noneable!(relative_poster_path, concat!("S/S/Poster", $id).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: notsettable!(id, ShowId::from_raw($id) $(, $($skip),+)?),
|
||||
season: notsettable!(season, $season $(, $($skip),+)?),
|
||||
slug: notsettable!(slug, concat!("S/S", $id).to_string() $(, $($skip),+)?),
|
||||
library: notsettable!(library, LibraryId::from_raw($lid) $(, $($skip),+)?),
|
||||
directory: notsettable!(directory, Path::new(concat!("/S/S", $id)).to_owned().into() $(, $($skip),+)?),
|
||||
relative_poster_path: notsettable!(relative_poster_path, Some(concat!("S/S/Poster", $id).to_owned()) $(, $($skip),+)?),
|
||||
}.insert($db).await
|
||||
};
|
||||
}
|
||||
assert_season!(&db, 1, 1, 0, ForeignKeyViolation);
|
||||
assert_season!(&db, 1, 1, 1, ForeignKeyViolation);
|
||||
make_flix_season!(&db, 1, 1);
|
||||
make_flix_season!(&db, 1, 2);
|
||||
make_flix_season!(&db, 2, 1);
|
||||
make_flix_season!(&db, 3, 1);
|
||||
make_flix_season!(&db, 8, 1);
|
||||
|
||||
assert_season!(&db, 1, 1, 1, Success);
|
||||
assert_season!(&db, 1, 2, 1, Success);
|
||||
assert_season!(&db, 1, 1, 1, UniqueViolation);
|
||||
assert_season!(&db, 2, 1, 1, Success);
|
||||
assert_season!(&db, 3, 1, 1, Success; show);
|
||||
assert_season!(&db, 4, 1, 1, NotNullViolation; season);
|
||||
assert_season!(&db, 5, 1, 1, NotNullViolation; slug);
|
||||
assert_season!(&db, 6, 1, 1, NotNullViolation; library);
|
||||
assert_season!(&db, 7, 1, 1, NotNullViolation; directory);
|
||||
assert_season!(&db, 8, 1, 1, Success; relative_poster_path);
|
||||
|
||||
// Episodes
|
||||
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, ShowId::from_raw($id));
|
||||
assert_eq!(model.season, $season);
|
||||
assert_eq!(model.episode, $episode);
|
||||
assert_eq!(model.slug, concat!("S/S/E", $id).to_string());
|
||||
assert_eq!(model.library, LibraryId::from_raw($lid));
|
||||
assert_eq!(model.directory, Path::new(concat!("/S/S/E", $id)).to_owned().into());
|
||||
assert_eq!(model.relative_media_path, concat!("E/Media", $id));
|
||||
assert_eq!(model.relative_poster_path, noneable!(relative_poster_path, concat!("S/S/E/Poster", $id).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: notsettable!(id, ShowId::from_raw($id) $(, $($skip),+)?),
|
||||
season: notsettable!(season, $season $(, $($skip),+)?),
|
||||
episode: notsettable!(episode, $episode $(, $($skip),+)?),
|
||||
count: notsettable!(count, 0 $(, $($skip),+)?),
|
||||
slug: notsettable!(slug, concat!("S/S/E", $id).to_string() $(, $($skip),+)?),
|
||||
library: notsettable!(library, LibraryId::from_raw($lid) $(, $($skip),+)?),
|
||||
directory: notsettable!(directory, Path::new(concat!("/S/S/E", $id)).to_owned().into() $(, $($skip),+)?),
|
||||
relative_media_path: notsettable!(relative_media_path, concat!("E/Media", $id).to_owned() $(, $($skip),+)?),
|
||||
relative_poster_path: notsettable!(relative_poster_path, Some(concat!("S/S/E/Poster", $id).to_owned()) $(, $($skip),+)?),
|
||||
}.insert($db).await
|
||||
};
|
||||
}
|
||||
assert_episode!(&db, 1, 1, 1, 0, ForeignKeyViolation);
|
||||
assert_episode!(&db, 1, 1, 1, 1, ForeignKeyViolation);
|
||||
make_flix_episode!(&db, 1, 1, 1);
|
||||
make_flix_episode!(&db, 1, 1, 2);
|
||||
make_flix_episode!(&db, 2, 1, 1);
|
||||
make_flix_episode!(&db, 3, 1, 1);
|
||||
make_flix_show!(&db, 11);
|
||||
make_flix_season!(&db, 11, 1);
|
||||
make_flix_episode!(&db, 11, 1, 1);
|
||||
|
||||
assert_episode!(&db, 1, 1, 1, 1, Success);
|
||||
assert_episode!(&db, 1, 1, 2, 1, Success);
|
||||
assert_episode!(&db, 1, 1, 1, 1, UniqueViolation);
|
||||
assert_episode!(&db, 2, 1, 1, 1, Success);
|
||||
assert_episode!(&db, 3, 1, 1, 1, Success; show);
|
||||
assert_episode!(&db, 4, 1, 1, 1, NotNullViolation; season);
|
||||
assert_episode!(&db, 5, 1, 1, 1, NotNullViolation; episode);
|
||||
assert_episode!(&db, 6, 1, 1, 1, NotNullViolation; count);
|
||||
assert_episode!(&db, 7, 1, 1, 1, NotNullViolation; slug);
|
||||
assert_episode!(&db, 8, 1, 1, 1, NotNullViolation; library);
|
||||
assert_episode!(&db, 9, 1, 1, 1, NotNullViolation; directory);
|
||||
assert_episode!(&db, 10, 1, 1, 1, NotNullViolation; relative_media_path);
|
||||
assert_episode!(&db, 11, 1, 1, 1, Success; relative_poster_path);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
//! Movie entity
|
||||
|
||||
use flix_model::id::{CollectionId, LibraryId, MovieId};
|
||||
|
||||
use seamantic::model::path::PathBytes;
|
||||
|
||||
use sea_orm::{
|
||||
ActiveModelBehavior, DeriveEntityModel, DerivePrimaryKey, DeriveRelation, EntityTrait,
|
||||
EnumIter, PrimaryKeyTrait, Related, RelationDef, RelationTrait,
|
||||
};
|
||||
|
||||
/// The database representation of a movie media folder
|
||||
#[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
|
||||
pub parent: Option<CollectionId>,
|
||||
/// The movie's slug
|
||||
pub slug: String,
|
||||
/// The movie's library
|
||||
pub library: 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>,
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
|
||||
/// Relation
|
||||
#[derive(Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
/// The parent collection of this collection
|
||||
#[sea_orm(
|
||||
belongs_to = "super::collections::Entity",
|
||||
from = "Column::Parent",
|
||||
to = "super::collections::Column::Id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
Parent,
|
||||
/// The library this movie belongs to
|
||||
#[sea_orm(
|
||||
belongs_to = "super::libraries::Entity",
|
||||
from = "Column::Library",
|
||||
to = "super::libraries::Column::Id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
Library,
|
||||
/// The media info for this movie
|
||||
#[sea_orm(
|
||||
belongs_to = "super::super::info::movies::Entity",
|
||||
from = "Column::Id",
|
||||
to = "super::super::info::movies::Column::Id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
MediaInfo,
|
||||
/// The watched info for this movie
|
||||
#[sea_orm(
|
||||
belongs_to = "super::super::watched::movies::Entity",
|
||||
from = "Column::Id",
|
||||
to = "super::super::watched::movies::Column::Id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
WatchInfo,
|
||||
}
|
||||
|
||||
impl Related<super::collections::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Parent.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::libraries::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Library.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::super::info::movies::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::MediaInfo.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::super::watched::movies::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::WatchInfo.def()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
//! Season entity
|
||||
|
||||
use flix_model::id::{LibraryId, ShowId};
|
||||
|
||||
use seamantic::model::path::PathBytes;
|
||||
|
||||
use flix_model::numbers::SeasonNumber;
|
||||
use sea_orm::{
|
||||
ActiveModelBehavior, DeriveEntityModel, DerivePrimaryKey, DeriveRelation, EntityTrait,
|
||||
EnumIter, PrimaryKeyTrait, Related, RelationDef, RelationTrait,
|
||||
};
|
||||
|
||||
/// The database representation of a season media folder
|
||||
#[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: ShowId,
|
||||
/// The season's number
|
||||
#[sea_orm(primary_key, auto_increment = false)]
|
||||
pub season: SeasonNumber,
|
||||
/// The season's slug
|
||||
pub slug: String,
|
||||
/// The season's library
|
||||
pub library: LibraryId,
|
||||
/// The season's directory
|
||||
pub directory: PathBytes,
|
||||
/// The season's poster path
|
||||
pub relative_poster_path: Option<String>,
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
|
||||
/// Relation
|
||||
#[derive(Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
/// The library this season belongs to
|
||||
#[sea_orm(
|
||||
belongs_to = "super::libraries::Entity",
|
||||
from = "Column::Library",
|
||||
to = "super::libraries::Column::Id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
Library,
|
||||
/// The media info for this show
|
||||
#[sea_orm(
|
||||
belongs_to = "super::super::info::seasons::Entity",
|
||||
from = "(Column::Show, Column::Season)",
|
||||
to = "(super::super::info::seasons::Column::Show, super::super::info::seasons::Column::Season)",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
MediaInfo,
|
||||
/// The watched info for this show
|
||||
#[sea_orm(
|
||||
belongs_to = "super::super::watched::seasons::Entity",
|
||||
from = "(Column::Show, Column::Season)",
|
||||
to = "(super::super::watched::seasons::Column::Show, super::super::watched::seasons::Column::Season)",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
WatchInfo,
|
||||
}
|
||||
|
||||
impl Related<super::libraries::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Library.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::super::info::seasons::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::MediaInfo.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::super::watched::seasons::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::WatchInfo.def()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
//! Show entity
|
||||
|
||||
use flix_model::id::{CollectionId, LibraryId, ShowId};
|
||||
|
||||
use seamantic::model::path::PathBytes;
|
||||
|
||||
use sea_orm::{
|
||||
ActiveModelBehavior, DeriveEntityModel, DerivePrimaryKey, DeriveRelation, EntityTrait,
|
||||
EnumIter, PrimaryKeyTrait, Related, RelationDef, RelationTrait,
|
||||
};
|
||||
|
||||
/// The database representation of a show media folder
|
||||
#[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
|
||||
pub parent: Option<CollectionId>,
|
||||
/// The show's slug
|
||||
pub slug: String,
|
||||
/// The show's library
|
||||
pub library: LibraryId,
|
||||
/// The show's directory
|
||||
pub directory: PathBytes,
|
||||
/// The show's poster path
|
||||
pub relative_poster_path: Option<String>,
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
|
||||
/// Relation
|
||||
#[derive(Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
/// The parent collection of this collection
|
||||
#[sea_orm(
|
||||
belongs_to = "super::collections::Entity",
|
||||
from = "Column::Parent",
|
||||
to = "super::collections::Column::Id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
Parent,
|
||||
/// The library this show belongs to
|
||||
#[sea_orm(
|
||||
belongs_to = "super::libraries::Entity",
|
||||
from = "Column::Library",
|
||||
to = "super::libraries::Column::Id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
Library,
|
||||
/// The media info for this show
|
||||
#[sea_orm(
|
||||
belongs_to = "super::super::info::shows::Entity",
|
||||
from = "Column::Id",
|
||||
to = "super::super::info::shows::Column::Id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
MediaInfo,
|
||||
/// The watched info for this show
|
||||
#[sea_orm(
|
||||
belongs_to = "super::super::watched::shows::Entity",
|
||||
from = "Column::Id",
|
||||
to = "super::super::watched::shows::Column::Id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
WatchInfo,
|
||||
}
|
||||
|
||||
impl Related<super::collections::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Parent.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::libraries::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Library.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::super::info::shows::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::MediaInfo.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::super::watched::shows::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::WatchInfo.def()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
//! Collection entity
|
||||
|
||||
use flix_model::id::CollectionId;
|
||||
|
||||
use sea_orm::{
|
||||
ActiveModelBehavior, DeriveEntityModel, DerivePrimaryKey, DeriveRelation, EnumIter,
|
||||
PrimaryKeyTrait,
|
||||
};
|
||||
|
||||
/// The database representation of a flix collection
|
||||
#[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,
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
|
||||
/// Relation
|
||||
#[derive(Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {}
|
||||
@@ -0,0 +1,53 @@
|
||||
//! Episode entity
|
||||
|
||||
use flix_model::id::ShowId;
|
||||
|
||||
use chrono::NaiveDate;
|
||||
use flix_model::numbers::{EpisodeNumber, SeasonNumber};
|
||||
use sea_orm::{
|
||||
ActiveModelBehavior, DeriveEntityModel, DerivePrimaryKey, DeriveRelation, EntityTrait,
|
||||
EnumIter, PrimaryKeyTrait, Related, RelationDef, RelationTrait,
|
||||
};
|
||||
|
||||
/// The database representation of a flix episode
|
||||
#[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: ShowId,
|
||||
/// The episode's season's number
|
||||
#[sea_orm(primary_key, auto_increment = false)]
|
||||
pub season: SeasonNumber,
|
||||
/// The episode's number
|
||||
#[sea_orm(primary_key, auto_increment = false)]
|
||||
pub episode: EpisodeNumber,
|
||||
/// The episode's title
|
||||
pub title: String,
|
||||
/// The episode's overview
|
||||
pub overview: String,
|
||||
/// The episode's air date
|
||||
pub date: NaiveDate,
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
|
||||
/// Relation
|
||||
#[derive(Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
/// The show this season belongs to
|
||||
#[sea_orm(
|
||||
belongs_to = "super::shows::Entity",
|
||||
from = "Column::Show",
|
||||
to = "super::shows::Column::Id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
Show,
|
||||
}
|
||||
|
||||
impl Related<super::shows::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Show.def()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
//! This module contains entities for storing media information such as
|
||||
//! titles and overviews
|
||||
|
||||
pub mod collections;
|
||||
|
||||
pub mod movies;
|
||||
|
||||
pub mod episodes;
|
||||
pub mod seasons;
|
||||
pub mod shows;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use flix_model::id::{CollectionId, MovieId, ShowId};
|
||||
|
||||
use chrono::NaiveDate;
|
||||
use sea_orm::ActiveModelTrait;
|
||||
use sea_orm::ActiveValue::{NotSet, Set};
|
||||
use sea_orm::sqlx::error::ErrorKind;
|
||||
use sea_orm_migration::MigratorTrait;
|
||||
|
||||
use crate::migration::Migrator;
|
||||
use crate::tests::new_memory_db;
|
||||
|
||||
use super::super::tests::get_error_kind;
|
||||
use super::super::tests::notsettable;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_inserts() {
|
||||
let db = new_memory_db().await;
|
||||
Migrator::up(&db, None).await.expect("up");
|
||||
|
||||
// Collections
|
||||
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", $id));
|
||||
assert_eq!(model.overview, concat!("Collection", " ", $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", $id).to_string() $(, $($skip),+)?),
|
||||
overview: notsettable!(overview, concat!("Collection", " ", $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);
|
||||
|
||||
// Movies
|
||||
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", $id));
|
||||
assert_eq!(model.tagline, concat!("Watch Movie", " ", $id));
|
||||
assert_eq!(model.overview, concat!("Movie", " ", $id));
|
||||
assert_eq!(model.date, NaiveDate::from_yo_opt(2000, $id).expect("NaiveDate::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", $id).to_string() $(, $($skip),+)?),
|
||||
tagline: notsettable!(tagline, concat!("Watch Movie", " ", $id).to_string() $(, $($skip),+)?),
|
||||
overview: notsettable!(overview, concat!("Movie", " ", $id).to_string() $(, $($skip),+)?),
|
||||
date: notsettable!(date, NaiveDate::from_yo_opt(2000, $id).expect("NaiveDate::from_yo_opt") $(, $($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);
|
||||
|
||||
// Shows
|
||||
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", $id));
|
||||
assert_eq!(model.tagline, concat!("Watch Show", " ", $id));
|
||||
assert_eq!(model.overview, concat!("Show", " ", $id));
|
||||
assert_eq!(model.date, NaiveDate::from_yo_opt(2000, $id).expect("NaiveDate::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", $id).to_string() $(, $($skip),+)?),
|
||||
tagline: notsettable!(tagline, concat!("Watch Show", " ", $id).to_string() $(, $($skip),+)?),
|
||||
overview: notsettable!(overview, concat!("Show", " ", $id).to_string() $(, $($skip),+)?),
|
||||
date: notsettable!(date, NaiveDate::from_yo_opt(2000, $id).expect("NaiveDate::from_yo_opt") $(, $($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);
|
||||
|
||||
// Seasons
|
||||
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, ShowId::from_raw($show));
|
||||
assert_eq!(model.season, $season);
|
||||
assert_eq!(model.title, concat!("S", $show, "S", $season));
|
||||
assert_eq!(model.overview, concat!("Show", " ", $show, " ", "Season", " ", $season));
|
||||
assert_eq!(model.date, NaiveDate::from_yo_opt(2000, $show + $season).expect("NaiveDate::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: notsettable!(show, ShowId::from_raw($show) $(, $($skip),+)?),
|
||||
season: notsettable!(season, $season $(, $($skip),+)?),
|
||||
title: notsettable!(title, concat!("S", $show, "S", $season).to_string() $(, $($skip),+)?),
|
||||
overview: notsettable!(overview, concat!("Show", " ", $show, " ", "Season", " ", $season).to_string() $(, $($skip),+)?),
|
||||
date: notsettable!(date, NaiveDate::from_yo_opt(2000, $show + $season).expect("NaiveDate::from_yo_opt") $(, $($skip),+)?),
|
||||
}.insert($db).await
|
||||
};
|
||||
}
|
||||
assert_season!(&db, 1, 1, Success);
|
||||
assert_season!(&db, 1, 1, UniqueViolation);
|
||||
assert_season!(&db, 2, 1, Success);
|
||||
assert_season!(&db, 0, 1, ForeignKeyViolation);
|
||||
assert_season!(&db, 1, 2, Success);
|
||||
assert_season!(&db, 1, 3, NotNullViolation; show);
|
||||
assert_season!(&db, 1, 4, NotNullViolation; season);
|
||||
assert_season!(&db, 1, 5, NotNullViolation; title);
|
||||
assert_season!(&db, 1, 6, NotNullViolation; overview);
|
||||
assert_season!(&db, 1, 7, NotNullViolation; date);
|
||||
|
||||
// Episodes
|
||||
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, ShowId::from_raw($show));
|
||||
assert_eq!(model.season, $season);
|
||||
assert_eq!(model.episode, $episode);
|
||||
assert_eq!(model.title, concat!("S", $show, "S", $season, "E", $episode));
|
||||
assert_eq!(model.overview, concat!("Show", " ", $show, " ", "Season", " ", $season, " ", "Episode", " ", $episode));
|
||||
assert_eq!(model.date, NaiveDate::from_yo_opt(2000, $show + $season + $episode).expect("NaiveDate::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: notsettable!(show, ShowId::from_raw($show) $(, $($skip),+)?),
|
||||
season: notsettable!(season, $season $(, $($skip),+)?),
|
||||
episode: notsettable!(episode, $episode $(, $($skip),+)?),
|
||||
title: notsettable!(title, concat!("S", $show, "S", $season, "E", $episode).to_string() $(, $($skip),+)?),
|
||||
overview: notsettable!(overview, concat!("Show", " ", $show, " ", "Season", " ", $season, " ", "Episode", " ", $episode).to_string() $(, $($skip),+)?),
|
||||
date: notsettable!(date, NaiveDate::from_yo_opt(2000, $show + $season + $episode).expect("NaiveDate::from_yo_opt") $(, $($skip),+)?),
|
||||
}.insert($db).await
|
||||
};
|
||||
}
|
||||
assert_episode!(&db, 1, 1, 1, Success);
|
||||
assert_episode!(&db, 1, 1, 1, UniqueViolation);
|
||||
assert_episode!(&db, 1, 2, 1, Success);
|
||||
assert_episode!(&db, 2, 1, 1, Success);
|
||||
assert_episode!(&db, 1, 0, 1, ForeignKeyViolation);
|
||||
assert_episode!(&db, 0, 1, 1, ForeignKeyViolation);
|
||||
assert_episode!(&db, 1, 1, 2, Success);
|
||||
assert_episode!(&db, 1, 1, 3, NotNullViolation; show);
|
||||
assert_episode!(&db, 1, 1, 4, NotNullViolation; season);
|
||||
assert_episode!(&db, 1, 1, 4, NotNullViolation; episode);
|
||||
assert_episode!(&db, 1, 1, 5, NotNullViolation; title);
|
||||
assert_episode!(&db, 1, 1, 6, NotNullViolation; overview);
|
||||
assert_episode!(&db, 1, 1, 7, NotNullViolation; date);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
//! Movie entity
|
||||
|
||||
use flix_model::id::MovieId;
|
||||
|
||||
use chrono::NaiveDate;
|
||||
use sea_orm::{
|
||||
ActiveModelBehavior, DeriveEntityModel, DerivePrimaryKey, DeriveRelation, EnumIter,
|
||||
PrimaryKeyTrait,
|
||||
};
|
||||
|
||||
/// The database representation of a flix movie
|
||||
#[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
|
||||
pub date: NaiveDate,
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
|
||||
/// Relation
|
||||
#[derive(Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {}
|
||||
@@ -0,0 +1,50 @@
|
||||
//! Season entity
|
||||
|
||||
use flix_model::id::ShowId;
|
||||
|
||||
use chrono::NaiveDate;
|
||||
use flix_model::numbers::SeasonNumber;
|
||||
use sea_orm::{
|
||||
ActiveModelBehavior, DeriveEntityModel, DerivePrimaryKey, DeriveRelation, EntityTrait,
|
||||
EnumIter, PrimaryKeyTrait, Related, RelationDef, RelationTrait,
|
||||
};
|
||||
|
||||
/// The database representation of a flix season
|
||||
#[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: ShowId,
|
||||
/// The season's number
|
||||
#[sea_orm(primary_key, auto_increment = false)]
|
||||
pub season: SeasonNumber,
|
||||
/// The season's title
|
||||
pub title: String,
|
||||
/// The season's overview
|
||||
pub overview: String,
|
||||
/// The season's air date
|
||||
pub date: NaiveDate,
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
|
||||
/// Relation
|
||||
#[derive(Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
/// The show this season belongs to
|
||||
#[sea_orm(
|
||||
belongs_to = "super::shows::Entity",
|
||||
from = "Column::Show",
|
||||
to = "super::shows::Column::Id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
Show,
|
||||
}
|
||||
|
||||
impl Related<super::shows::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Show.def()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
//! Show entity
|
||||
|
||||
use flix_model::id::ShowId;
|
||||
|
||||
use chrono::NaiveDate;
|
||||
use sea_orm::{
|
||||
ActiveModelBehavior, DeriveEntityModel, DerivePrimaryKey, DeriveRelation, EntityTrait,
|
||||
EnumIter, PrimaryKeyTrait, Related, RelationDef, RelationTrait,
|
||||
};
|
||||
|
||||
/// The database representation of a flix show
|
||||
#[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
|
||||
pub date: NaiveDate,
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
|
||||
/// Relation
|
||||
#[derive(Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
/// The seasons that are part of this show
|
||||
#[sea_orm(has_many = "super::seasons::Entity")]
|
||||
Seasons,
|
||||
/// The episodes that are part of this show
|
||||
#[sea_orm(has_many = "super::episodes::Entity")]
|
||||
Episodes,
|
||||
}
|
||||
|
||||
impl Related<super::seasons::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Seasons.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::episodes::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Episodes.def()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
//! Entity structs for interacting with the database
|
||||
|
||||
pub mod content;
|
||||
pub mod info;
|
||||
#[cfg(feature = "tmdb")]
|
||||
pub mod tmdb;
|
||||
pub mod watched;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
pub use sea_orm::DbErr;
|
||||
use sea_orm::sqlx::error::ErrorKind;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ErrorKindError {
|
||||
NotRuntimeError,
|
||||
NotSqlxError,
|
||||
NotDatabaseError,
|
||||
}
|
||||
|
||||
pub fn get_error_kind(error: DbErr) -> Result<ErrorKind, ErrorKindError> {
|
||||
let runtime_err = match error {
|
||||
DbErr::Conn(runtime_err) => runtime_err,
|
||||
DbErr::Exec(runtime_err) => runtime_err,
|
||||
DbErr::Query(runtime_err) => runtime_err,
|
||||
_ => return Err(ErrorKindError::NotRuntimeError),
|
||||
};
|
||||
|
||||
let sqlx_err = match runtime_err {
|
||||
sea_orm::RuntimeErr::SqlxError(sqlx_err) => sqlx_err,
|
||||
_ => return Err(ErrorKindError::NotSqlxError),
|
||||
};
|
||||
|
||||
let database_err = match sqlx_err.as_ref() {
|
||||
sea_orm::SqlxError::Database(database_err) => database_err,
|
||||
_ => return Err(ErrorKindError::NotDatabaseError),
|
||||
};
|
||||
|
||||
Ok(database_err.kind())
|
||||
}
|
||||
|
||||
/// Helper macro for writing tests for `ActiveModel` structs where
|
||||
/// toggling [sea_orm::ActiveValue] is needed
|
||||
macro_rules! notsettable {
|
||||
($field:ident, $value:expr $(, $($skip:ident),+)?) => {
|
||||
if notsettable!(@skip, $field $(, $($skip),+)?) {
|
||||
NotSet
|
||||
} else {
|
||||
Set($value)
|
||||
}
|
||||
};
|
||||
(@skip, $field:ident $(, $skip:ident),*) => {
|
||||
false $(|| stringify!($field) == stringify!($skip))*
|
||||
};
|
||||
}
|
||||
pub(super) use notsettable;
|
||||
|
||||
/// Helper macro for writing tests for `ActiveModel` structs where
|
||||
/// toggling [sea_orm::ActiveValue] is needed
|
||||
macro_rules! noneable {
|
||||
($field:ident, $value:expr $(, $($skip:ident),+)?) => {
|
||||
if noneable!(@skip, $field $(, $($skip),+)?) {
|
||||
None
|
||||
} else {
|
||||
Some($value)
|
||||
}
|
||||
};
|
||||
(@skip, $field:ident $(, $skip:ident),*) => {
|
||||
false $(|| stringify!($field) == stringify!($skip))*
|
||||
};
|
||||
}
|
||||
pub(super) use noneable;
|
||||
|
||||
/// Helper macro for creating a flix library
|
||||
macro_rules! have_library {
|
||||
($db:expr, $id:literal) => {
|
||||
$crate::entity::content::libraries::ActiveModel {
|
||||
id: Set(::flix_model::id::LibraryId::from_raw($id)),
|
||||
directory: Set(::std::path::PathBuf::new().into()),
|
||||
}
|
||||
.insert($db)
|
||||
.await
|
||||
.expect("insert");
|
||||
};
|
||||
}
|
||||
pub(super) use have_library;
|
||||
|
||||
/// Helper macro for creating a flix collection
|
||||
macro_rules! make_flix_collection {
|
||||
($db:expr, $id:literal) => {
|
||||
$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()),
|
||||
}
|
||||
.insert($db)
|
||||
.await
|
||||
.expect("insert");
|
||||
};
|
||||
}
|
||||
pub(super) use make_flix_collection;
|
||||
macro_rules! have_collection {
|
||||
($db:expr, $lid:literal, $id:literal, $pid:expr) => {
|
||||
$crate::entity::tests::make_flix_collection!($db, $id);
|
||||
$crate::entity::content::collections::ActiveModel {
|
||||
id: Set(::flix_model::id::CollectionId::from_raw($id)),
|
||||
parent: Set($pid.map(::flix_model::id::CollectionId::from_raw)),
|
||||
slug: Set(::std::string::String::new()),
|
||||
library: 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(super) use have_collection;
|
||||
|
||||
/// Helper macro for creating a flix movie
|
||||
macro_rules! make_flix_movie {
|
||||
($db:expr, $id:literal) => {
|
||||
$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(2000, $id).expect("NaiveDate::from_yo_opt")
|
||||
),
|
||||
}
|
||||
.insert($db)
|
||||
.await
|
||||
.expect("insert");
|
||||
};
|
||||
}
|
||||
pub(super) use make_flix_movie;
|
||||
macro_rules! have_movie {
|
||||
($db:expr, $lid:literal, $id:literal, $pid:expr) => {
|
||||
$crate::entity::tests::make_flix_movie!($db, $id);
|
||||
$crate::entity::content::movies::ActiveModel {
|
||||
id: Set(::flix_model::id::MovieId::from_raw($id)),
|
||||
parent: Set($pid.map(::flix_model::id::CollectionId::from_raw)),
|
||||
slug: Set(::std::string::String::new()),
|
||||
library: 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(super) use have_movie;
|
||||
|
||||
/// Helper macro for creating a flix show
|
||||
macro_rules! make_flix_show {
|
||||
($db:expr, $id:literal) => {
|
||||
$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(2000, $id).expect("NaiveDate::from_yo_opt")
|
||||
),
|
||||
}
|
||||
.insert($db)
|
||||
.await
|
||||
.expect("insert");
|
||||
};
|
||||
}
|
||||
pub(super) use make_flix_show;
|
||||
macro_rules! have_show {
|
||||
($db:expr, $lid:literal, $id:literal, $pid:expr) => {
|
||||
$crate::entity::tests::make_flix_show!($db, $id);
|
||||
$crate::entity::content::shows::ActiveModel {
|
||||
id: Set(::flix_model::id::ShowId::from_raw($id)),
|
||||
parent: Set($pid.map(::flix_model::id::CollectionId::from_raw)),
|
||||
slug: Set(::std::string::String::new()),
|
||||
library: 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(super) use have_show;
|
||||
|
||||
/// Helper macro for creating a flix season
|
||||
macro_rules! make_flix_season {
|
||||
($db:expr, $show:literal, $season:literal) => {
|
||||
$crate::entity::info::seasons::ActiveModel {
|
||||
show: Set(::flix_model::id::ShowId::from_raw($show)),
|
||||
season: Set($season),
|
||||
title: Set(::std::string::String::new()),
|
||||
overview: Set(::std::string::String::new()),
|
||||
date: Set(::chrono::NaiveDate::from_yo_opt(2000, $show + $season)
|
||||
.expect("NaiveDate::from_yo_opt")),
|
||||
}
|
||||
.insert($db)
|
||||
.await
|
||||
.expect("insert");
|
||||
};
|
||||
}
|
||||
pub(super) use make_flix_season;
|
||||
macro_rules! have_season {
|
||||
($db:expr, $lid:literal, $show:literal, $season:literal) => {
|
||||
$crate::entity::tests::make_flix_season!($db, $show, $season);
|
||||
$crate::entity::content::seasons::ActiveModel {
|
||||
show: Set(::flix_model::id::ShowId::from_raw($show)),
|
||||
season: Set($season),
|
||||
slug: Set(::std::string::String::new()),
|
||||
library: 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(super) use have_season;
|
||||
|
||||
/// Helper macro for creating a flix episode
|
||||
macro_rules! make_flix_episode {
|
||||
($db:expr, $show:literal, $season:literal, $episode:literal) => {
|
||||
$crate::entity::info::episodes::ActiveModel {
|
||||
show: Set(::flix_model::id::ShowId::from_raw($show)),
|
||||
season: Set($season),
|
||||
episode: Set($episode),
|
||||
title: Set(::std::string::String::new()),
|
||||
overview: Set(::std::string::String::new()),
|
||||
date: Set(::chrono::NaiveDate::from_yo_opt(2000, $show + $season)
|
||||
.expect("NaiveDate::from_yo_opt")),
|
||||
}
|
||||
.insert($db)
|
||||
.await
|
||||
.expect("insert");
|
||||
};
|
||||
}
|
||||
pub(super) use make_flix_episode;
|
||||
macro_rules! have_episode {
|
||||
($db:expr, $lid:literal, $show:literal, $season:literal, $episode:literal) => {
|
||||
have_episode!(@make, $db, $lid, $show, $season, $episode, 0);
|
||||
};
|
||||
($db:expr, $lid:literal, $show:literal, $season:literal, $episode:literal, >1) => {
|
||||
have_episode!(@make, $db, $lid, $show, $season, $episode, 1);
|
||||
};
|
||||
(@make, $db:expr, $lid:literal, $show:literal, $season:literal, $episode:literal, $count:literal) => {
|
||||
$crate::entity::tests::make_flix_episode!($db, $show, $season, $episode);
|
||||
$crate::entity::content::episodes::ActiveModel {
|
||||
show: Set(::flix_model::id::ShowId::from_raw($show)),
|
||||
season: Set($season),
|
||||
episode: Set($episode),
|
||||
count: Set($count),
|
||||
slug: Set(::std::string::String::new()),
|
||||
library: 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(super) use have_episode;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
//! Collection entity
|
||||
|
||||
use flix_model::id::CollectionId as FlixId;
|
||||
use flix_tmdb::model::id::CollectionId;
|
||||
|
||||
use chrono::NaiveDate;
|
||||
use sea_orm::{
|
||||
ActiveModelBehavior, DeriveEntityModel, DerivePrimaryKey, DeriveRelation, EntityTrait,
|
||||
EnumIter, PrimaryKeyTrait, Related, RelationDef, RelationTrait,
|
||||
};
|
||||
|
||||
/// The database representation of a tmdb collection
|
||||
#[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
|
||||
pub flix_id: FlixId,
|
||||
/// The date of the last update
|
||||
pub last_update: NaiveDate,
|
||||
/// The number of movies in the collection
|
||||
pub movie_count: u16,
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
|
||||
/// Relation
|
||||
#[derive(Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
/// The movies that are part of this collection
|
||||
#[sea_orm(has_many = "super::movies::Entity")]
|
||||
Movies,
|
||||
}
|
||||
|
||||
impl Related<super::movies::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Movies.def()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
//! Season entity
|
||||
|
||||
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::NaiveDate;
|
||||
use sea_orm::{
|
||||
ActiveModelBehavior, DeriveEntityModel, DerivePrimaryKey, DeriveRelation, EnumIter,
|
||||
PrimaryKeyTrait,
|
||||
};
|
||||
|
||||
/// The database representation of a tmdb episode
|
||||
#[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
|
||||
pub flix_show: FlixId,
|
||||
/// The episode's season's number
|
||||
pub flix_season: SeasonNumber,
|
||||
/// The episode's number
|
||||
pub flix_episode: EpisodeNumber,
|
||||
/// The date of the last update
|
||||
pub last_update: NaiveDate,
|
||||
/// The episode's runtime in seconds
|
||||
pub runtime: Seconds,
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
|
||||
/// Relation
|
||||
#[derive(Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {}
|
||||
@@ -0,0 +1,278 @@
|
||||
//! This module contains entities for storing dynamic data from TMDB
|
||||
|
||||
pub mod collections;
|
||||
|
||||
pub mod movies;
|
||||
|
||||
pub mod episodes;
|
||||
pub mod seasons;
|
||||
pub mod shows;
|
||||
|
||||
#[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::ActiveModelTrait;
|
||||
use sea_orm::ActiveValue::{NotSet, Set};
|
||||
use sea_orm::sqlx::error::ErrorKind;
|
||||
use sea_orm_migration::MigratorTrait;
|
||||
|
||||
use crate::migration::Migrator;
|
||||
use crate::tests::new_memory_db;
|
||||
|
||||
use super::super::tests::get_error_kind;
|
||||
use super::super::tests::notsettable;
|
||||
use super::super::tests::{
|
||||
make_flix_collection, make_flix_episode, make_flix_movie, make_flix_season, make_flix_show,
|
||||
};
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_inserts() {
|
||||
let db = new_memory_db().await;
|
||||
Migrator::up(&db, None).await.expect("up");
|
||||
|
||||
// Collections
|
||||
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(2000, $tid).expect("NaiveDate::from_yo_opt"));
|
||||
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(2000, $tid).expect("NaiveDate::from_yo_opt") $(, $($skip),+)?),
|
||||
movie_count: notsettable!(movie_count, $id $(, $($skip),+)?),
|
||||
}.insert($db).await
|
||||
};
|
||||
}
|
||||
assert_collection!(&db, 1, 1, ForeignKeyViolation);
|
||||
make_flix_collection!(&db, 1);
|
||||
make_flix_collection!(&db, 2);
|
||||
make_flix_collection!(&db, 3);
|
||||
|
||||
assert_collection!(&db, 1, 1, Success);
|
||||
assert_collection!(&db, 1, 1, UniqueViolation);
|
||||
assert_collection!(&db, 1, 2, UniqueViolation);
|
||||
assert_collection!(&db, 2, 1, UniqueViolation);
|
||||
assert_collection!(&db, 2, 2, Success);
|
||||
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);
|
||||
|
||||
// Movies
|
||||
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(2000, $tid).expect("NaiveDate::from_yo_opt"));
|
||||
assert_eq!(model.runtime, Duration::from_secs($tid).into());
|
||||
assert_eq!(model.collection, $cid);
|
||||
};
|
||||
($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(2000, $tid).expect("NaiveDate::from_yo_opt") $(, $($skip),+)?),
|
||||
runtime: notsettable!(runtime, Duration::from_secs($tid).into() $(, $($skip),+)?),
|
||||
collection: notsettable!(collection, $cid $(, $($skip),+)?),
|
||||
}.insert($db).await
|
||||
};
|
||||
}
|
||||
assert_movie!(
|
||||
&db,
|
||||
1,
|
||||
1,
|
||||
Some(TmdbCollectionId::from_raw(1)),
|
||||
ForeignKeyViolation
|
||||
);
|
||||
make_flix_movie!(&db, 1);
|
||||
make_flix_movie!(&db, 2);
|
||||
make_flix_movie!(&db, 3);
|
||||
|
||||
assert_movie!(&db, 1, 1, Some(TmdbCollectionId::from_raw(1)), Success);
|
||||
assert_movie!(&db, 1, 1, None, UniqueViolation);
|
||||
assert_movie!(&db, 1, 2, None, UniqueViolation);
|
||||
assert_movie!(&db, 2, 1, None, UniqueViolation);
|
||||
assert_movie!(&db, 2, 2, Some(TmdbCollectionId::from_raw(1)), Success);
|
||||
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); // Must be `Set(None)`
|
||||
|
||||
// Shows
|
||||
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(2000, $tid).expect("NaiveDate::from_yo_opt"));
|
||||
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(2000, $tid).expect("NaiveDate::from_yo_opt") $(, $($skip),+)?),
|
||||
number_of_seasons: notsettable!(number_of_seasons, $id $(, $($skip),+)?),
|
||||
}.insert($db).await
|
||||
};
|
||||
}
|
||||
assert_show!(&db, 1, 1, ForeignKeyViolation);
|
||||
make_flix_show!(&db, 1);
|
||||
make_flix_show!(&db, 2);
|
||||
make_flix_show!(&db, 3);
|
||||
|
||||
assert_show!(&db, 1, 1, Success);
|
||||
assert_show!(&db, 1, 1, UniqueViolation);
|
||||
assert_show!(&db, 1, 2, UniqueViolation);
|
||||
assert_show!(&db, 2, 1, UniqueViolation);
|
||||
assert_show!(&db, 2, 2, Success);
|
||||
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);
|
||||
|
||||
// Seasons
|
||||
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, $tseason);
|
||||
assert_eq!(model.flix_show, ShowId::from_raw($show));
|
||||
assert_eq!(model.flix_season, $season);
|
||||
assert_eq!(model.last_update, NaiveDate::from_yo_opt(2000, $tshow).expect("NaiveDate::from_yo_opt"));
|
||||
};
|
||||
($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, $tseason $(, $($skip),+)?),
|
||||
flix_show: notsettable!(flix_show, ShowId::from_raw($show) $(, $($skip),+)?),
|
||||
flix_season: notsettable!(flix_season, $season $(, $($skip),+)?),
|
||||
last_update: notsettable!(last_update, NaiveDate::from_yo_opt(2000, $tshow).expect("NaiveDate::from_yo_opt") $(, $($skip),+)?),
|
||||
}.insert($db).await
|
||||
};
|
||||
}
|
||||
assert_season!(&db, 1, 1, 1, 1, ForeignKeyViolation);
|
||||
make_flix_season!(&db, 1, 1);
|
||||
make_flix_season!(&db, 1, 2);
|
||||
|
||||
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);
|
||||
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);
|
||||
|
||||
// Episodes
|
||||
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, $tseason);
|
||||
assert_eq!(model.tmdb_episode, $tepisode);
|
||||
assert_eq!(model.flix_show, ShowId::from_raw($show));
|
||||
assert_eq!(model.flix_season, $season);
|
||||
assert_eq!(model.flix_episode, $episode);
|
||||
assert_eq!(model.last_update, NaiveDate::from_yo_opt(2000, $tshow).expect("NaiveDate::from_yo_opt"));
|
||||
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, $tseason $(, $($skip),+)?),
|
||||
tmdb_episode: notsettable!(tmdb_episode, $tepisode $(, $($skip),+)?),
|
||||
flix_show: notsettable!(flix_show, ShowId::from_raw($show) $(, $($skip),+)?),
|
||||
flix_season: notsettable!(flix_season, $season $(, $($skip),+)?),
|
||||
flix_episode: notsettable!(flix_episode, $episode $(, $($skip),+)?),
|
||||
last_update: notsettable!(last_update, NaiveDate::from_yo_opt(2000, $tshow).expect("NaiveDate::from_yo_opt") $(, $($skip),+)?),
|
||||
runtime: notsettable!(runtime, Duration::from_secs($tshow).into() $(, $($skip),+)?),
|
||||
}.insert($db).await
|
||||
};
|
||||
}
|
||||
assert_episode!(&db, 1, 1, 1, 1, 1, 1, ForeignKeyViolation);
|
||||
make_flix_episode!(&db, 1, 1, 1);
|
||||
make_flix_episode!(&db, 1, 1, 2);
|
||||
|
||||
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);
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
//! Movie entity
|
||||
|
||||
use flix_model::id::MovieId as FlixId;
|
||||
use flix_tmdb::model::id::{CollectionId, MovieId};
|
||||
|
||||
use seamantic::model::duration::Seconds;
|
||||
|
||||
use chrono::NaiveDate;
|
||||
use sea_orm::{
|
||||
ActiveModelBehavior, DeriveEntityModel, DerivePrimaryKey, DeriveRelation, EntityTrait,
|
||||
EnumIter, PrimaryKeyTrait, Related, RelationDef, RelationTrait,
|
||||
};
|
||||
|
||||
/// The database representation of a tmdb movie
|
||||
#[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
|
||||
pub flix_id: FlixId,
|
||||
/// The date of the last update
|
||||
pub last_update: NaiveDate,
|
||||
/// The movie's runtime in seconds
|
||||
pub runtime: Seconds,
|
||||
/// The TMDB ID of the collection this movie belongs to
|
||||
pub collection: Option<CollectionId>,
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
|
||||
/// Relation
|
||||
#[derive(Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
/// The collection this movie belongs to
|
||||
#[sea_orm(
|
||||
belongs_to = "super::collections::Entity",
|
||||
from = "Column::Collection",
|
||||
to = "super::collections::Column::TmdbId",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
Collection,
|
||||
}
|
||||
|
||||
impl Related<super::collections::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Collection.def()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
//! Season entity
|
||||
|
||||
use flix_model::id::ShowId as FlixId;
|
||||
use flix_model::numbers::SeasonNumber;
|
||||
use flix_tmdb::model::id::ShowId;
|
||||
|
||||
use chrono::NaiveDate;
|
||||
use sea_orm::{
|
||||
ActiveModelBehavior, DeriveEntityModel, DerivePrimaryKey, DeriveRelation, EntityTrait,
|
||||
EnumIter, PrimaryKeyTrait, Related, RelationDef, RelationTrait,
|
||||
};
|
||||
|
||||
/// The database representation of a tmdb season
|
||||
#[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
|
||||
pub flix_show: FlixId,
|
||||
/// The season's number
|
||||
pub flix_season: SeasonNumber,
|
||||
/// The date of the last update
|
||||
pub last_update: NaiveDate,
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
|
||||
/// Relation
|
||||
#[derive(Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
/// The show this season belongs to
|
||||
#[sea_orm(
|
||||
belongs_to = "super::shows::Entity",
|
||||
from = "Column::TmdbShow",
|
||||
to = "super::shows::Column::TmdbId",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
Show,
|
||||
}
|
||||
|
||||
impl Related<super::shows::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Show.def()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
//! Show entity
|
||||
|
||||
use flix_model::id::ShowId as FlixId;
|
||||
use flix_tmdb::model::id::ShowId;
|
||||
|
||||
use chrono::NaiveDate;
|
||||
use sea_orm::{
|
||||
ActiveModelBehavior, DeriveEntityModel, DerivePrimaryKey, DeriveRelation, EntityTrait,
|
||||
EnumIter, PrimaryKeyTrait, Related, RelationDef, RelationTrait,
|
||||
};
|
||||
|
||||
/// The database representation of a tmdb show
|
||||
#[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
|
||||
pub flix_id: FlixId,
|
||||
/// The movie's runtime in seconds
|
||||
pub last_update: NaiveDate,
|
||||
/// The number of seasons the show has
|
||||
pub number_of_seasons: u32,
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
|
||||
/// Relation
|
||||
#[derive(Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
/// The seasons that are part of this show
|
||||
#[sea_orm(has_many = "super::seasons::Entity")]
|
||||
Seasons,
|
||||
}
|
||||
|
||||
impl Related<super::seasons::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Seasons.def()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
//! Collection entity
|
||||
|
||||
use flix_model::id::{CollectionId, RawId};
|
||||
|
||||
use sea_orm::{
|
||||
ActiveModelBehavior, DeriveEntityModel, DerivePrimaryKey, DeriveRelation, EnumIter,
|
||||
PrimaryKeyTrait,
|
||||
};
|
||||
|
||||
/// The database representation of a watched movie
|
||||
#[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,
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
|
||||
/// Relation
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {}
|
||||
@@ -0,0 +1,36 @@
|
||||
//! Episode entity
|
||||
|
||||
use flix_model::id::{RawId, ShowId};
|
||||
use flix_model::numbers::{EpisodeNumber, SeasonNumber};
|
||||
|
||||
use chrono::NaiveDate;
|
||||
use sea_orm::{
|
||||
ActiveModelBehavior, DeriveEntityModel, DerivePrimaryKey, DeriveRelation, EnumIter,
|
||||
PrimaryKeyTrait,
|
||||
};
|
||||
|
||||
/// The database representation of a watched movie
|
||||
#[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: ShowId,
|
||||
/// The episode's season's number
|
||||
#[sea_orm(primary_key, auto_increment = false)]
|
||||
pub season: SeasonNumber,
|
||||
/// The episode's number
|
||||
#[sea_orm(primary_key, auto_increment = false)]
|
||||
pub episode: 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: NaiveDate,
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
|
||||
/// Relation
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {}
|
||||
@@ -0,0 +1,289 @@
|
||||
//! This module contains entities for storing watched information
|
||||
|
||||
pub mod collections;
|
||||
|
||||
pub mod movies;
|
||||
|
||||
pub mod episodes;
|
||||
pub mod seasons;
|
||||
pub mod shows;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
use flix_model::id::{MovieId, ShowId};
|
||||
|
||||
use chrono::NaiveDate;
|
||||
use sea_orm::ActiveValue::{NotSet, Set};
|
||||
use sea_orm::sqlx::error::ErrorKind;
|
||||
use sea_orm::{ActiveModelTrait, ColumnTrait, Condition, EntityTrait, QueryFilter};
|
||||
use sea_orm_migration::MigratorTrait;
|
||||
|
||||
use crate::entity::tests::{have_collection, have_library, have_movie, have_season, have_show};
|
||||
use crate::migration::Migrator;
|
||||
use crate::tests::new_memory_db;
|
||||
|
||||
use super::super::tests::get_error_kind;
|
||||
use super::super::tests::notsettable;
|
||||
use super::super::tests::{
|
||||
have_episode, make_flix_episode, make_flix_movie, make_flix_season, make_flix_show,
|
||||
};
|
||||
|
||||
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(2000, $uid).expect("NaiveDate::from_yo_opt"));
|
||||
};
|
||||
($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(2000, $uid).expect("NaiveDate::from_yo_opt") $(, $($skip),+)?),
|
||||
}.insert($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, ShowId::from_raw($show));
|
||||
assert_eq!(model.season, $season);
|
||||
assert_eq!(model.episode, $episode);
|
||||
assert_eq!(model.user_id, $uid);
|
||||
assert_eq!(model.watched_date, NaiveDate::from_yo_opt(2000, $uid).expect("NaiveDate::from_yo_opt"));
|
||||
};
|
||||
($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: notsettable!(show, ShowId::from_raw($show) $(, $($skip),+)?),
|
||||
season: notsettable!(season, $season $(, $($skip),+)?),
|
||||
episode: notsettable!(episode, $episode $(, $($skip),+)?),
|
||||
user_id: notsettable!(user_id, $uid $(, $($skip),+)?),
|
||||
watched_date: notsettable!(watched_date, NaiveDate::from_yo_opt(2000, $uid).expect("NaiveDate::from_yo_opt") $(, $($skip),+)?),
|
||||
}.insert($db).await
|
||||
};
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_inserts() {
|
||||
let db = new_memory_db().await;
|
||||
Migrator::up(&db, None).await.expect("up");
|
||||
|
||||
// Movies
|
||||
assert_movie!(&db, 1, 1, ForeignKeyViolation);
|
||||
make_flix_movie!(&db, 1);
|
||||
make_flix_movie!(&db, 2);
|
||||
|
||||
assert_movie!(&db, 1, 1, Success);
|
||||
assert_movie!(&db, 1, 1, UniqueViolation);
|
||||
assert_movie!(&db, 2, 1, Success);
|
||||
assert_movie!(&db, 3, 1, NotNullViolation; id);
|
||||
assert_movie!(&db, 4, 1, NotNullViolation; user_id);
|
||||
assert_movie!(&db, 5, 1, NotNullViolation; watched_date);
|
||||
|
||||
// Episodes
|
||||
make_flix_show!(&db, 1);
|
||||
make_flix_season!(&db, 1, 1);
|
||||
make_flix_show!(&db, 2);
|
||||
make_flix_season!(&db, 2, 1);
|
||||
|
||||
assert_episode!(&db, 1, 1, 1, 1, ForeignKeyViolation);
|
||||
make_flix_episode!(&db, 1, 1, 1);
|
||||
make_flix_episode!(&db, 1, 1, 2);
|
||||
make_flix_episode!(&db, 2, 1, 1);
|
||||
|
||||
assert_episode!(&db, 1, 1, 1, 1, Success);
|
||||
assert_episode!(&db, 1, 1, 1, 1, UniqueViolation);
|
||||
assert_episode!(&db, 1, 1, 2, 1, Success);
|
||||
assert_episode!(&db, 2, 1, 1, 1, Success);
|
||||
assert_episode!(&db, 3, 1, 1, 1, NotNullViolation; show);
|
||||
assert_episode!(&db, 4, 1, 1, 1, NotNullViolation; season);
|
||||
assert_episode!(&db, 5, 1, 1, 1, NotNullViolation; episode);
|
||||
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_queries() {
|
||||
let db = new_memory_db().await;
|
||||
Migrator::up(&db, None).await.expect("up");
|
||||
|
||||
have_library!(&db, 1);
|
||||
|
||||
// Season + Show
|
||||
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::Show.eq($show))
|
||||
.add(super::seasons::Column::Season.eq($season))
|
||||
.add(super::seasons::Column::UserId.eq($uid)),
|
||||
)
|
||||
.one(&db)
|
||||
.await
|
||||
.expect("find.filter.one")
|
||||
};
|
||||
}
|
||||
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")
|
||||
};
|
||||
}
|
||||
|
||||
have_show!(&db, 1, 1, None);
|
||||
have_season!(&db, 1, 1, 1);
|
||||
have_episode!(&db, 1, 1, 1, 1);
|
||||
assert_episode!(&db, 1, 1, 1, 1, Success);
|
||||
assert_episode!(&db, 1, 1, 1, 2, Success);
|
||||
have_episode!(&db, 1, 1, 1, 2, >1); // Covers 2 and 3
|
||||
make_flix_episode!(&db, 1, 1, 3);
|
||||
assert_episode!(&db, 1, 1, 2, 1, Success);
|
||||
assert_episode!(&db, 1, 1, 2, 2, Success);
|
||||
have_season!(&db, 1, 1, 2);
|
||||
have_episode!(&db, 1, 1, 2, 1);
|
||||
assert_episode!(&db, 1, 2, 1, 1, Success);
|
||||
assert_episode!(&db, 1, 2, 1, 2, Success);
|
||||
have_episode!(&db, 1, 1, 2, 2);
|
||||
assert_episode!(&db, 1, 2, 2, 1, Success);
|
||||
have_episode!(&db, 1, 1, 2, 3);
|
||||
assert_episode!(&db, 1, 2, 3, 1, Success);
|
||||
|
||||
// Add watched episodes that we do not have
|
||||
make_flix_episode!(&db, 1, 1, 4);
|
||||
assert_episode!(&db, 1, 1, 4, 1, Success);
|
||||
make_flix_episode!(&db, 1, 2, 4);
|
||||
assert_episode!(&db, 1, 2, 4, 2, Success);
|
||||
make_flix_episode!(&db, 1, 2, 5);
|
||||
assert_episode!(&db, 1, 2, 5, 2, Success);
|
||||
|
||||
assert_season!(&db, 1, 1, 1, Watched);
|
||||
assert_season!(&db, 1, 1, 2, Watched);
|
||||
assert_season!(&db, 1, 1, 3, Unwatched);
|
||||
assert_season!(&db, 1, 2, 1, Watched);
|
||||
assert_season!(&db, 1, 2, 2, Unwatched);
|
||||
assert_season!(&db, 1, 2, 3, Unwatched);
|
||||
assert_season!(&db, 1, 3, 1, Unwatched);
|
||||
assert_season!(&db, 1, 3, 2, Unwatched);
|
||||
assert_season!(&db, 1, 3, 3, Unwatched);
|
||||
|
||||
assert_show!(&db, 1, 1, Watched);
|
||||
assert_show!(&db, 1, 2, Unwatched);
|
||||
assert_show!(&db, 1, 3, Unwatched);
|
||||
assert_show!(&db, 2, 1, Unwatched);
|
||||
assert_show!(&db, 2, 2, Unwatched);
|
||||
assert_show!(&db, 2, 3, Unwatched);
|
||||
|
||||
// Collection
|
||||
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")
|
||||
};
|
||||
}
|
||||
|
||||
have_collection!(&db, 1, 1, None);
|
||||
have_movie!(&db, 1, 1, Some(1));
|
||||
assert_movie!(&db, 1, 1, Success);
|
||||
assert_movie!(&db, 1, 2, Success);
|
||||
have_movie!(&db, 1, 2, Some(1));
|
||||
assert_movie!(&db, 2, 1, Success);
|
||||
assert_movie!(&db, 2, 2, Success);
|
||||
|
||||
have_collection!(&db, 1, 2, Some(1));
|
||||
have_movie!(&db, 1, 3, Some(2));
|
||||
have_show!(&db, 1, 2, Some(2));
|
||||
have_season!(&db, 1, 2, 1);
|
||||
have_episode!(&db, 1, 2, 1, 1);
|
||||
assert_episode!(&db, 2, 1, 1, 1, Success);
|
||||
assert_movie!(&db, 3, 1, Success);
|
||||
have_movie!(&db, 1, 4, Some(2));
|
||||
assert_movie!(&db, 4, 1, Success);
|
||||
|
||||
have_collection!(&db, 1, 3, Some(2));
|
||||
have_movie!(&db, 1, 5, Some(3));
|
||||
assert_movie!(&db, 5, 1, Success);
|
||||
have_movie!(&db, 1, 6, Some(3));
|
||||
assert_movie!(&db, 6, 1, Success);
|
||||
assert_movie!(&db, 6, 2, Success);
|
||||
|
||||
have_collection!(&db, 1, 4, Some(3));
|
||||
have_movie!(&db, 1, 7, Some(4));
|
||||
assert_movie!(&db, 7, 1, Success);
|
||||
assert_movie!(&db, 7, 2, Success);
|
||||
have_movie!(&db, 1, 8, Some(4));
|
||||
assert_movie!(&db, 8, 1, Success);
|
||||
assert_movie!(&db, 8, 2, Success);
|
||||
|
||||
assert_collection!(&db, 1, 1, Watched);
|
||||
assert_collection!(&db, 1, 2, Unwatched);
|
||||
assert_collection!(&db, 2, 1, Watched);
|
||||
assert_collection!(&db, 2, 2, Unwatched);
|
||||
assert_collection!(&db, 3, 1, Watched);
|
||||
assert_collection!(&db, 3, 2, Unwatched);
|
||||
assert_collection!(&db, 4, 1, Watched);
|
||||
assert_collection!(&db, 4, 2, Watched);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//! Movie entity
|
||||
|
||||
use flix_model::id::{MovieId, RawId};
|
||||
|
||||
use chrono::NaiveDate;
|
||||
use sea_orm::{
|
||||
ActiveModelBehavior, DeriveEntityModel, DerivePrimaryKey, DeriveRelation, EnumIter,
|
||||
PrimaryKeyTrait,
|
||||
};
|
||||
|
||||
/// The database representation of a watched movie
|
||||
#[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: NaiveDate,
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
|
||||
/// Relation
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {}
|
||||
@@ -0,0 +1,33 @@
|
||||
//! Episode entity
|
||||
|
||||
use flix_model::id::{RawId, ShowId};
|
||||
use flix_model::numbers::SeasonNumber;
|
||||
|
||||
use chrono::NaiveDate;
|
||||
use sea_orm::{
|
||||
ActiveModelBehavior, DeriveEntityModel, DerivePrimaryKey, DeriveRelation, EnumIter,
|
||||
PrimaryKeyTrait,
|
||||
};
|
||||
|
||||
/// The database representation of a watched movie
|
||||
#[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: ShowId,
|
||||
/// The season's number
|
||||
#[sea_orm(primary_key, auto_increment = false)]
|
||||
pub season: 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: NaiveDate,
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
|
||||
/// Relation
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {}
|
||||
@@ -0,0 +1,29 @@
|
||||
//! Show entity
|
||||
|
||||
use flix_model::id::{RawId, ShowId};
|
||||
|
||||
use chrono::NaiveDate;
|
||||
use sea_orm::{
|
||||
ActiveModelBehavior, DeriveEntityModel, DerivePrimaryKey, DeriveRelation, EnumIter,
|
||||
PrimaryKeyTrait,
|
||||
};
|
||||
|
||||
/// The database representation of a watched movie
|
||||
#[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: NaiveDate,
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
|
||||
/// Relation
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {}
|
||||
@@ -0,0 +1,17 @@
|
||||
//! 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};
|
||||
|
||||
pub async fn new_memory_db() -> DatabaseConnection {
|
||||
let options = ConnectOptions::new("sqlite:/tmp/db?mode=memory");
|
||||
Database::connect(options).await.expect("Database::connect")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
//! Adds entity/info tables:
|
||||
//! - Collections
|
||||
//! - Movies
|
||||
//! - Shows
|
||||
//! - Seasons
|
||||
//! - Episodes
|
||||
|
||||
use sea_orm::{DbErr, DeriveMigrationName};
|
||||
use sea_orm_migration::async_trait;
|
||||
use sea_orm_migration::{MigrationTrait, SchemaManager};
|
||||
|
||||
mod collections;
|
||||
mod episodes;
|
||||
mod movies;
|
||||
mod seasons;
|
||||
mod shows;
|
||||
|
||||
#[allow(unused_imports)]
|
||||
pub use collections::FlixInfoCollections;
|
||||
#[allow(unused_imports)]
|
||||
pub use episodes::FlixInfoEpisodes;
|
||||
#[allow(unused_imports)]
|
||||
pub use movies::FlixInfoMovies;
|
||||
#[allow(unused_imports)]
|
||||
pub use seasons::FlixInfoSeasons;
|
||||
#[allow(unused_imports)]
|
||||
pub use shows::FlixInfoShows;
|
||||
|
||||
#[derive(DeriveMigrationName)]
|
||||
pub(super) struct Migration;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl MigrationTrait for Migration {
|
||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
collections::up(manager).await?;
|
||||
movies::up(manager).await?;
|
||||
shows::up(manager).await?;
|
||||
seasons::up(manager).await?;
|
||||
episodes::up(manager).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
episodes::down(manager).await?;
|
||||
seasons::down(manager).await?;
|
||||
shows::down(manager).await?;
|
||||
movies::down(manager).await?;
|
||||
collections::down(manager).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
use seamantic::schema::sqlite_rowid_alias;
|
||||
|
||||
use sea_orm::sea_query;
|
||||
use sea_orm::sea_query::{Index, Table};
|
||||
use sea_orm::{DbErr, Iden};
|
||||
use sea_orm_migration::SchemaManager;
|
||||
use sea_orm_migration::schema::string;
|
||||
|
||||
#[derive(Iden)]
|
||||
pub enum FlixInfoCollections {
|
||||
Table,
|
||||
Id,
|
||||
Title,
|
||||
Overview,
|
||||
}
|
||||
|
||||
pub async fn up(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.create_table(
|
||||
Table::create()
|
||||
.table(FlixInfoCollections::Table)
|
||||
.col(sqlite_rowid_alias(FlixInfoCollections::Id))
|
||||
.col(string(FlixInfoCollections::Title))
|
||||
.col(string(FlixInfoCollections::Overview))
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
manager
|
||||
.create_index(
|
||||
Index::create()
|
||||
.name("idx-flix_info_collections-title")
|
||||
.table(FlixInfoCollections::Table)
|
||||
.col(FlixInfoCollections::Title)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn down(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.drop_table(Table::drop().table(FlixInfoCollections::Table).to_owned())
|
||||
.await
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
use sea_orm::sea_query;
|
||||
use sea_orm::sea_query::{ForeignKeyCreateStatement, Index, Table};
|
||||
use sea_orm::{DbErr, Iden};
|
||||
use sea_orm_migration::SchemaManager;
|
||||
use sea_orm_migration::schema::{date, integer, string};
|
||||
|
||||
use crate::migration::m_000001::FlixInfoShows;
|
||||
|
||||
use super::FlixInfoSeasons;
|
||||
|
||||
#[derive(Iden)]
|
||||
pub enum FlixInfoEpisodes {
|
||||
Table,
|
||||
Show,
|
||||
Season,
|
||||
Episode,
|
||||
Title,
|
||||
Overview,
|
||||
Date,
|
||||
}
|
||||
|
||||
pub async fn up(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.create_table(
|
||||
Table::create()
|
||||
.table(FlixInfoEpisodes::Table)
|
||||
.col(integer(FlixInfoEpisodes::Show))
|
||||
.col(integer(FlixInfoEpisodes::Season))
|
||||
.col(integer(FlixInfoEpisodes::Episode))
|
||||
.col(string(FlixInfoEpisodes::Title))
|
||||
.col(string(FlixInfoEpisodes::Overview))
|
||||
.col(date(FlixInfoEpisodes::Date))
|
||||
.primary_key(
|
||||
Index::create()
|
||||
.col(FlixInfoEpisodes::Show)
|
||||
.col(FlixInfoEpisodes::Season)
|
||||
.col(FlixInfoEpisodes::Episode),
|
||||
)
|
||||
.foreign_key(
|
||||
ForeignKeyCreateStatement::new()
|
||||
.name("fk-flix_info_episodes-show")
|
||||
.from_tbl(FlixInfoEpisodes::Table)
|
||||
.from_col(FlixInfoEpisodes::Show)
|
||||
.to_tbl(FlixInfoShows::Table)
|
||||
.to_col(FlixInfoShows::Id),
|
||||
)
|
||||
.foreign_key(
|
||||
ForeignKeyCreateStatement::new()
|
||||
.name("fk-flix_info_episodes-show_season")
|
||||
.from_tbl(FlixInfoEpisodes::Table)
|
||||
.from_col(FlixInfoEpisodes::Show)
|
||||
.from_col(FlixInfoEpisodes::Season)
|
||||
.to_tbl(FlixInfoSeasons::Table)
|
||||
.to_col(FlixInfoSeasons::Show)
|
||||
.to_col(FlixInfoSeasons::Season),
|
||||
)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn down(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.drop_table(Table::drop().table(FlixInfoEpisodes::Table).to_owned())
|
||||
.await
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
use seamantic::schema::sqlite_rowid_alias;
|
||||
|
||||
use sea_orm::sea_query;
|
||||
use sea_orm::sea_query::{Index, Table};
|
||||
use sea_orm::{DbErr, Iden};
|
||||
use sea_orm_migration::SchemaManager;
|
||||
use sea_orm_migration::schema::{date, string};
|
||||
|
||||
#[derive(Iden)]
|
||||
pub enum FlixInfoMovies {
|
||||
Table,
|
||||
Id,
|
||||
Title,
|
||||
Tagline,
|
||||
Overview,
|
||||
Date,
|
||||
}
|
||||
|
||||
pub async fn up(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.create_table(
|
||||
Table::create()
|
||||
.table(FlixInfoMovies::Table)
|
||||
.col(sqlite_rowid_alias(FlixInfoMovies::Id))
|
||||
.col(string(FlixInfoMovies::Title))
|
||||
.col(string(FlixInfoMovies::Tagline))
|
||||
.col(string(FlixInfoMovies::Overview))
|
||||
.col(date(FlixInfoMovies::Date))
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
manager
|
||||
.create_index(
|
||||
Index::create()
|
||||
.name("idx-flix_info_movies-title")
|
||||
.table(FlixInfoMovies::Table)
|
||||
.col(FlixInfoMovies::Title)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
manager
|
||||
.create_index(
|
||||
Index::create()
|
||||
.name("idx-flix_info_movies-date")
|
||||
.table(FlixInfoMovies::Table)
|
||||
.col(FlixInfoMovies::Date)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn down(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.drop_table(Table::drop().table(FlixInfoMovies::Table).to_owned())
|
||||
.await
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
use sea_orm::sea_query;
|
||||
use sea_orm::sea_query::{ForeignKeyCreateStatement, Index, Table};
|
||||
use sea_orm::{DbErr, Iden};
|
||||
use sea_orm_migration::SchemaManager;
|
||||
use sea_orm_migration::schema::{date, integer, string};
|
||||
|
||||
use super::FlixInfoShows;
|
||||
|
||||
#[derive(Iden)]
|
||||
pub enum FlixInfoSeasons {
|
||||
Table,
|
||||
Show,
|
||||
Season,
|
||||
Title,
|
||||
Overview,
|
||||
Date,
|
||||
}
|
||||
|
||||
pub async fn up(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.create_table(
|
||||
Table::create()
|
||||
.table(FlixInfoSeasons::Table)
|
||||
.col(integer(FlixInfoSeasons::Show))
|
||||
.col(integer(FlixInfoSeasons::Season))
|
||||
.col(string(FlixInfoSeasons::Title))
|
||||
.col(string(FlixInfoSeasons::Overview))
|
||||
.col(date(FlixInfoSeasons::Date))
|
||||
.primary_key(
|
||||
Index::create()
|
||||
.col(FlixInfoSeasons::Show)
|
||||
.col(FlixInfoSeasons::Season),
|
||||
)
|
||||
.foreign_key(
|
||||
ForeignKeyCreateStatement::new()
|
||||
.name("fk-flix_info_seasons-show")
|
||||
.from_tbl(FlixInfoSeasons::Table)
|
||||
.from_col(FlixInfoSeasons::Show)
|
||||
.to_tbl(FlixInfoShows::Table)
|
||||
.to_col(FlixInfoShows::Id),
|
||||
)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn down(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.drop_table(Table::drop().table(FlixInfoSeasons::Table).to_owned())
|
||||
.await
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
use seamantic::schema::sqlite_rowid_alias;
|
||||
|
||||
use sea_orm::sea_query;
|
||||
use sea_orm::sea_query::{Index, Table};
|
||||
use sea_orm::{DbErr, Iden};
|
||||
use sea_orm_migration::SchemaManager;
|
||||
use sea_orm_migration::schema::{date, string};
|
||||
|
||||
#[derive(Iden)]
|
||||
pub enum FlixInfoShows {
|
||||
Table,
|
||||
Id,
|
||||
Title,
|
||||
Tagline,
|
||||
Overview,
|
||||
Date,
|
||||
}
|
||||
|
||||
pub async fn up(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.create_table(
|
||||
Table::create()
|
||||
.table(FlixInfoShows::Table)
|
||||
.col(sqlite_rowid_alias(FlixInfoShows::Id))
|
||||
.col(string(FlixInfoShows::Title))
|
||||
.col(string(FlixInfoShows::Tagline))
|
||||
.col(string(FlixInfoShows::Overview))
|
||||
.col(date(FlixInfoShows::Date))
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
manager
|
||||
.create_index(
|
||||
Index::create()
|
||||
.name("idx-flix_info_shows-title")
|
||||
.table(FlixInfoShows::Table)
|
||||
.col(FlixInfoShows::Title)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
manager
|
||||
.create_index(
|
||||
Index::create()
|
||||
.name("idx-flix_info_shows-date")
|
||||
.table(FlixInfoShows::Table)
|
||||
.col(FlixInfoShows::Date)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn down(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.drop_table(Table::drop().table(FlixInfoShows::Table).to_owned())
|
||||
.await
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
//! Adds entity/tmdb tables:
|
||||
//! - Collections
|
||||
//! - Movies
|
||||
//! - Shows
|
||||
//! - Seasons
|
||||
//! - Episodes
|
||||
|
||||
use sea_orm::{DbErr, DeriveMigrationName};
|
||||
use sea_orm_migration::async_trait;
|
||||
use sea_orm_migration::{MigrationTrait, SchemaManager};
|
||||
|
||||
mod collections;
|
||||
mod episodes;
|
||||
mod movies;
|
||||
mod seasons;
|
||||
mod shows;
|
||||
|
||||
#[allow(unused_imports)]
|
||||
pub use collections::FlixTmdbCollections;
|
||||
#[allow(unused_imports)]
|
||||
pub use episodes::FlixTmdbEpisodes;
|
||||
#[allow(unused_imports)]
|
||||
pub use movies::FlixTmdbMovies;
|
||||
#[allow(unused_imports)]
|
||||
pub use seasons::FlixTmdbSeasons;
|
||||
#[allow(unused_imports)]
|
||||
pub use shows::FlixTmdbShows;
|
||||
|
||||
#[derive(DeriveMigrationName)]
|
||||
pub(super) struct Migration;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl MigrationTrait for Migration {
|
||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
collections::up(manager).await?;
|
||||
movies::up(manager).await?;
|
||||
shows::up(manager).await?;
|
||||
seasons::up(manager).await?;
|
||||
episodes::up(manager).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
episodes::down(manager).await?;
|
||||
seasons::down(manager).await?;
|
||||
shows::down(manager).await?;
|
||||
movies::down(manager).await?;
|
||||
collections::down(manager).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
use seamantic::schema::sqlite_rowid_alias;
|
||||
|
||||
use sea_orm::sea_query;
|
||||
use sea_orm::sea_query::{ForeignKeyCreateStatement, Index, Table};
|
||||
use sea_orm::{DbErr, Iden};
|
||||
use sea_orm_migration::SchemaManager;
|
||||
use sea_orm_migration::schema::{date, integer};
|
||||
|
||||
use super::super::m_000001::FlixInfoCollections;
|
||||
|
||||
#[derive(Iden)]
|
||||
pub enum FlixTmdbCollections {
|
||||
Table,
|
||||
TmdbId,
|
||||
FlixId,
|
||||
LastUpdate,
|
||||
MovieCount,
|
||||
}
|
||||
|
||||
pub async fn up(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.create_table(
|
||||
Table::create()
|
||||
.table(FlixTmdbCollections::Table)
|
||||
.col(sqlite_rowid_alias(FlixTmdbCollections::TmdbId))
|
||||
.col(integer(FlixTmdbCollections::FlixId).unique_key())
|
||||
.col(date(FlixTmdbCollections::LastUpdate))
|
||||
.col(integer(FlixTmdbCollections::MovieCount))
|
||||
.foreign_key(
|
||||
ForeignKeyCreateStatement::new()
|
||||
.name("fk-flix_tmdb_collections-flixid")
|
||||
.from_tbl(FlixTmdbCollections::Table)
|
||||
.from_col(FlixTmdbCollections::FlixId)
|
||||
.to_tbl(FlixInfoCollections::Table)
|
||||
.to_col(FlixInfoCollections::Id),
|
||||
)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
manager
|
||||
.create_index(
|
||||
Index::create()
|
||||
.name("idx-flix_tmdb_collections-flixid")
|
||||
.table(FlixTmdbCollections::Table)
|
||||
.col(FlixTmdbCollections::FlixId)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn down(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.drop_table(Table::drop().table(FlixTmdbCollections::Table).to_owned())
|
||||
.await
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
use sea_orm::sea_query;
|
||||
use sea_orm::sea_query::{ForeignKeyCreateStatement, Index, Table};
|
||||
use sea_orm::{DbErr, Iden};
|
||||
use sea_orm_migration::SchemaManager;
|
||||
use sea_orm_migration::schema::{date, integer};
|
||||
|
||||
use super::super::m_000001::{FlixInfoEpisodes, FlixInfoSeasons};
|
||||
|
||||
use super::FlixTmdbSeasons;
|
||||
|
||||
#[derive(Iden)]
|
||||
pub enum FlixTmdbEpisodes {
|
||||
Table,
|
||||
TmdbShow,
|
||||
TmdbSeason,
|
||||
TmdbEpisode,
|
||||
FlixShow,
|
||||
FlixSeason,
|
||||
FlixEpisode,
|
||||
LastUpdate,
|
||||
Runtime,
|
||||
}
|
||||
|
||||
pub async fn up(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.create_table(
|
||||
Table::create()
|
||||
.table(FlixTmdbEpisodes::Table)
|
||||
.col(integer(FlixTmdbEpisodes::TmdbShow))
|
||||
.col(integer(FlixTmdbEpisodes::TmdbSeason))
|
||||
.col(integer(FlixTmdbEpisodes::TmdbEpisode))
|
||||
.col(integer(FlixTmdbEpisodes::FlixShow))
|
||||
.col(integer(FlixTmdbEpisodes::FlixSeason))
|
||||
.col(integer(FlixTmdbEpisodes::FlixEpisode))
|
||||
.col(date(FlixTmdbEpisodes::LastUpdate))
|
||||
.col(integer(FlixTmdbEpisodes::Runtime))
|
||||
.primary_key(
|
||||
Index::create()
|
||||
.col(FlixTmdbEpisodes::TmdbShow)
|
||||
.col(FlixTmdbEpisodes::TmdbSeason)
|
||||
.col(FlixTmdbEpisodes::TmdbEpisode),
|
||||
)
|
||||
.foreign_key(
|
||||
ForeignKeyCreateStatement::new()
|
||||
.name("fk-flix_tmdb_episodes-tmdb_show_season")
|
||||
.from_tbl(FlixTmdbEpisodes::Table)
|
||||
.from_col(FlixTmdbEpisodes::TmdbShow)
|
||||
.from_col(FlixTmdbEpisodes::TmdbSeason)
|
||||
.to_tbl(FlixTmdbSeasons::Table)
|
||||
.to_col(FlixTmdbSeasons::TmdbShow)
|
||||
.to_col(FlixTmdbSeasons::TmdbSeason),
|
||||
)
|
||||
.foreign_key(
|
||||
ForeignKeyCreateStatement::new()
|
||||
.name("fk-flix_tmdb_episodes-flix_show_season")
|
||||
.from_tbl(FlixTmdbEpisodes::Table)
|
||||
.from_col(FlixTmdbEpisodes::FlixShow)
|
||||
.from_col(FlixTmdbEpisodes::FlixSeason)
|
||||
.to_tbl(FlixInfoSeasons::Table)
|
||||
.to_col(FlixInfoSeasons::Show)
|
||||
.to_col(FlixInfoSeasons::Season),
|
||||
)
|
||||
.foreign_key(
|
||||
ForeignKeyCreateStatement::new()
|
||||
.name("fk-flix_tmdb_episodes-flix_show_season_episode")
|
||||
.from_tbl(FlixTmdbEpisodes::Table)
|
||||
.from_col(FlixTmdbEpisodes::FlixShow)
|
||||
.from_col(FlixTmdbEpisodes::FlixSeason)
|
||||
.from_col(FlixTmdbEpisodes::FlixEpisode)
|
||||
.to_tbl(FlixInfoEpisodes::Table)
|
||||
.to_col(FlixInfoEpisodes::Show)
|
||||
.to_col(FlixInfoEpisodes::Season)
|
||||
.to_col(FlixInfoEpisodes::Episode),
|
||||
)
|
||||
.index(
|
||||
Index::create()
|
||||
.unique()
|
||||
.name("idx-flix_tmdb_episodes-flix_show_season_episode")
|
||||
.col(FlixTmdbEpisodes::FlixShow)
|
||||
.col(FlixTmdbEpisodes::FlixSeason)
|
||||
.col(FlixTmdbEpisodes::FlixEpisode),
|
||||
)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn down(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.drop_table(Table::drop().table(FlixTmdbEpisodes::Table).to_owned())
|
||||
.await
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
use seamantic::schema::sqlite_rowid_alias;
|
||||
|
||||
use sea_orm::sea_query;
|
||||
use sea_orm::sea_query::{ForeignKeyCreateStatement, Index, Table};
|
||||
use sea_orm::{DbErr, Iden};
|
||||
use sea_orm_migration::SchemaManager;
|
||||
use sea_orm_migration::schema::{date, integer, integer_null};
|
||||
|
||||
use crate::migration::m_000002::FlixTmdbCollections;
|
||||
|
||||
use super::super::m_000001::FlixInfoMovies;
|
||||
|
||||
#[derive(Iden)]
|
||||
pub enum FlixTmdbMovies {
|
||||
Table,
|
||||
TmdbId,
|
||||
FlixId,
|
||||
LastUpdate,
|
||||
Runtime,
|
||||
Collection,
|
||||
}
|
||||
|
||||
pub async fn up(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.create_table(
|
||||
Table::create()
|
||||
.table(FlixTmdbMovies::Table)
|
||||
.col(sqlite_rowid_alias(FlixTmdbMovies::TmdbId))
|
||||
.col(integer(FlixTmdbMovies::FlixId).unique_key())
|
||||
.col(date(FlixTmdbMovies::LastUpdate))
|
||||
.col(integer(FlixTmdbMovies::Runtime))
|
||||
.col(integer_null(FlixTmdbMovies::Collection))
|
||||
.foreign_key(
|
||||
ForeignKeyCreateStatement::new()
|
||||
.name("fk-flix_tmdb_movies-flixid")
|
||||
.from_tbl(FlixTmdbMovies::Table)
|
||||
.from_col(FlixTmdbMovies::FlixId)
|
||||
.to_tbl(FlixInfoMovies::Table)
|
||||
.to_col(FlixInfoMovies::Id),
|
||||
)
|
||||
.foreign_key(
|
||||
ForeignKeyCreateStatement::new()
|
||||
.name("fk-flix_tmdb_movies-collectionid")
|
||||
.from_tbl(FlixTmdbMovies::Table)
|
||||
.from_col(FlixTmdbMovies::Collection)
|
||||
.to_tbl(FlixTmdbCollections::Table)
|
||||
.to_col(FlixTmdbCollections::TmdbId),
|
||||
)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
manager
|
||||
.create_index(
|
||||
Index::create()
|
||||
.name("idx-flix_tmdb_movies-flixid")
|
||||
.table(FlixTmdbMovies::Table)
|
||||
.col(FlixTmdbMovies::FlixId)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn down(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.drop_table(Table::drop().table(FlixTmdbMovies::Table).to_owned())
|
||||
.await
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
use sea_orm::sea_query;
|
||||
use sea_orm::sea_query::{ForeignKeyCreateStatement, Index, Table};
|
||||
use sea_orm::{DbErr, Iden};
|
||||
use sea_orm_migration::SchemaManager;
|
||||
use sea_orm_migration::schema::{date, integer};
|
||||
|
||||
use crate::migration::m_000001::FlixInfoShows;
|
||||
|
||||
use super::super::m_000001::FlixInfoSeasons;
|
||||
|
||||
use super::FlixTmdbShows;
|
||||
|
||||
#[derive(Iden)]
|
||||
pub enum FlixTmdbSeasons {
|
||||
Table,
|
||||
TmdbShow,
|
||||
TmdbSeason,
|
||||
FlixShow,
|
||||
FlixSeason,
|
||||
LastUpdate,
|
||||
}
|
||||
|
||||
pub async fn up(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.create_table(
|
||||
Table::create()
|
||||
.table(FlixTmdbSeasons::Table)
|
||||
.col(integer(FlixTmdbSeasons::TmdbShow))
|
||||
.col(integer(FlixTmdbSeasons::TmdbSeason))
|
||||
.col(integer(FlixTmdbSeasons::FlixShow))
|
||||
.col(integer(FlixTmdbSeasons::FlixSeason))
|
||||
.col(date(FlixTmdbSeasons::LastUpdate))
|
||||
.primary_key(
|
||||
Index::create()
|
||||
.col(FlixTmdbSeasons::TmdbShow)
|
||||
.col(FlixTmdbSeasons::TmdbSeason),
|
||||
)
|
||||
.foreign_key(
|
||||
ForeignKeyCreateStatement::new()
|
||||
.name("fk-flix_tmdb_seasons-tmdb_show")
|
||||
.from_tbl(FlixTmdbSeasons::Table)
|
||||
.from_col(FlixTmdbSeasons::FlixShow)
|
||||
.to_tbl(FlixTmdbShows::Table)
|
||||
.to_col(FlixTmdbShows::FlixId),
|
||||
)
|
||||
.foreign_key(
|
||||
ForeignKeyCreateStatement::new()
|
||||
.name("fk-flix_tmdb_seasons-flix_show")
|
||||
.from_tbl(FlixTmdbSeasons::Table)
|
||||
.from_col(FlixTmdbSeasons::FlixShow)
|
||||
.to_tbl(FlixInfoShows::Table)
|
||||
.to_col(FlixInfoShows::Id),
|
||||
)
|
||||
.foreign_key(
|
||||
ForeignKeyCreateStatement::new()
|
||||
.name("fk-flix_tmdb_seasons-flix_show_season")
|
||||
.from_tbl(FlixTmdbSeasons::Table)
|
||||
.from_col(FlixTmdbSeasons::FlixShow)
|
||||
.from_col(FlixTmdbSeasons::FlixSeason)
|
||||
.to_tbl(FlixInfoSeasons::Table)
|
||||
.to_col(FlixInfoSeasons::Show)
|
||||
.to_col(FlixInfoSeasons::Season),
|
||||
)
|
||||
.index(
|
||||
Index::create()
|
||||
.unique()
|
||||
.name("idx-flix_tmdb_seasons-flix_show_season")
|
||||
.col(FlixTmdbSeasons::FlixShow)
|
||||
.col(FlixTmdbSeasons::FlixSeason),
|
||||
)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn down(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.drop_table(Table::drop().table(FlixTmdbSeasons::Table).to_owned())
|
||||
.await
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
use seamantic::schema::sqlite_rowid_alias;
|
||||
|
||||
use sea_orm::sea_query;
|
||||
use sea_orm::sea_query::{ForeignKeyCreateStatement, Index, Table};
|
||||
use sea_orm::{DbErr, Iden};
|
||||
use sea_orm_migration::SchemaManager;
|
||||
use sea_orm_migration::schema::{date, integer};
|
||||
|
||||
use super::super::m_000001::FlixInfoShows;
|
||||
|
||||
#[derive(Iden)]
|
||||
pub enum FlixTmdbShows {
|
||||
Table,
|
||||
TmdbId,
|
||||
FlixId,
|
||||
LastUpdate,
|
||||
NumberOfSeasons,
|
||||
}
|
||||
|
||||
pub async fn up(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.create_table(
|
||||
Table::create()
|
||||
.table(FlixTmdbShows::Table)
|
||||
.col(sqlite_rowid_alias(FlixTmdbShows::TmdbId))
|
||||
.col(integer(FlixTmdbShows::FlixId).unique_key())
|
||||
.col(date(FlixTmdbShows::LastUpdate))
|
||||
.col(integer(FlixTmdbShows::NumberOfSeasons))
|
||||
.foreign_key(
|
||||
ForeignKeyCreateStatement::new()
|
||||
.name("fk-flix_tmdb_shows-flixid")
|
||||
.from_tbl(FlixTmdbShows::Table)
|
||||
.from_col(FlixTmdbShows::FlixId)
|
||||
.to_tbl(FlixInfoShows::Table)
|
||||
.to_col(FlixInfoShows::Id),
|
||||
)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
manager
|
||||
.create_index(
|
||||
Index::create()
|
||||
.name("idx-flix_tmdb_shows-flixid")
|
||||
.table(FlixTmdbShows::Table)
|
||||
.col(FlixTmdbShows::FlixId)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn down(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.drop_table(Table::drop().table(FlixTmdbShows::Table).to_owned())
|
||||
.await
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
//! Adds entity/content tables:
|
||||
//! - Libraries
|
||||
//! - Collections
|
||||
//! - Movies
|
||||
//! - Shows
|
||||
//! - Seasons
|
||||
//! - Episodes
|
||||
|
||||
use sea_orm::{DbErr, DeriveMigrationName};
|
||||
use sea_orm_migration::async_trait;
|
||||
use sea_orm_migration::{MigrationTrait, SchemaManager};
|
||||
|
||||
mod collections;
|
||||
mod episodes;
|
||||
mod libraries;
|
||||
mod movies;
|
||||
mod seasons;
|
||||
mod shows;
|
||||
|
||||
#[allow(unused_imports)]
|
||||
pub use collections::FlixCollections;
|
||||
#[allow(unused_imports)]
|
||||
pub use episodes::FlixEpisodes;
|
||||
#[allow(unused_imports)]
|
||||
pub use libraries::FlixLibraries;
|
||||
#[allow(unused_imports)]
|
||||
pub use movies::FlixMovies;
|
||||
#[allow(unused_imports)]
|
||||
pub use seasons::FlixSeasons;
|
||||
#[allow(unused_imports)]
|
||||
pub use shows::FlixShows;
|
||||
|
||||
#[derive(DeriveMigrationName)]
|
||||
pub(super) struct Migration;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl MigrationTrait for Migration {
|
||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
libraries::up(manager).await?;
|
||||
collections::up(manager).await?;
|
||||
movies::up(manager).await?;
|
||||
shows::up(manager).await?;
|
||||
seasons::up(manager).await?;
|
||||
episodes::up(manager).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
episodes::down(manager).await?;
|
||||
seasons::down(manager).await?;
|
||||
shows::down(manager).await?;
|
||||
movies::down(manager).await?;
|
||||
collections::down(manager).await?;
|
||||
libraries::down(manager).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
use seamantic::schema::sqlite_rowid_alias;
|
||||
|
||||
use sea_orm::sea_query;
|
||||
use sea_orm::sea_query::{ForeignKeyCreateStatement, Table};
|
||||
use sea_orm::{DbErr, Iden};
|
||||
use sea_orm_migration::SchemaManager;
|
||||
use sea_orm_migration::schema::{binary, integer, integer_null, string, string_null};
|
||||
|
||||
use crate::migration::m_000001::FlixInfoCollections;
|
||||
use crate::migration::m_000003::FlixLibraries;
|
||||
|
||||
#[derive(Iden)]
|
||||
pub enum FlixCollections {
|
||||
Table,
|
||||
Id,
|
||||
Parent,
|
||||
Slug,
|
||||
Library,
|
||||
Directory,
|
||||
RelativePosterPath,
|
||||
}
|
||||
|
||||
pub async fn up(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.create_table(
|
||||
Table::create()
|
||||
.table(FlixCollections::Table)
|
||||
.col(sqlite_rowid_alias(FlixCollections::Id))
|
||||
.col(integer_null(FlixCollections::Parent))
|
||||
.col(string(FlixCollections::Slug))
|
||||
.col(integer(FlixCollections::Library))
|
||||
.col(binary(FlixCollections::Directory))
|
||||
.col(string_null(FlixCollections::RelativePosterPath))
|
||||
.foreign_key(
|
||||
ForeignKeyCreateStatement::new()
|
||||
.name("fk-flix_collections-id")
|
||||
.from_tbl(FlixCollections::Table)
|
||||
.from_col(FlixCollections::Id)
|
||||
.to_tbl(FlixInfoCollections::Table)
|
||||
.to_col(FlixInfoCollections::Id),
|
||||
)
|
||||
.foreign_key(
|
||||
ForeignKeyCreateStatement::new()
|
||||
.name("fk-flix_collections-parent")
|
||||
.from_tbl(FlixCollections::Table)
|
||||
.from_col(FlixCollections::Parent)
|
||||
.to_tbl(FlixCollections::Table)
|
||||
.to_col(FlixCollections::Id),
|
||||
)
|
||||
.foreign_key(
|
||||
ForeignKeyCreateStatement::new()
|
||||
.name("fk-flix_collections-library")
|
||||
.from_tbl(FlixCollections::Table)
|
||||
.from_col(FlixCollections::Library)
|
||||
.to_tbl(FlixLibraries::Table)
|
||||
.to_col(FlixLibraries::Id),
|
||||
)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn down(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.drop_table(Table::drop().table(FlixCollections::Table).to_owned())
|
||||
.await
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
use sea_orm::sea_query;
|
||||
use sea_orm::sea_query::{ForeignKeyCreateStatement, Index, Table};
|
||||
use sea_orm::{DbErr, Iden};
|
||||
use sea_orm_migration::SchemaManager;
|
||||
use sea_orm_migration::schema::{binary, integer, string, string_null};
|
||||
|
||||
use crate::migration::m_000001::FlixInfoEpisodes;
|
||||
use crate::migration::m_000003::FlixLibraries;
|
||||
|
||||
#[derive(Iden)]
|
||||
pub enum FlixEpisodes {
|
||||
Table,
|
||||
Show,
|
||||
Season,
|
||||
Episode,
|
||||
Count,
|
||||
Slug,
|
||||
Library,
|
||||
Directory,
|
||||
RelativeMediaPath,
|
||||
RelativePosterPath,
|
||||
}
|
||||
|
||||
pub async fn up(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.create_table(
|
||||
Table::create()
|
||||
.table(FlixEpisodes::Table)
|
||||
.col(integer(FlixEpisodes::Show))
|
||||
.col(integer(FlixEpisodes::Season))
|
||||
.col(integer(FlixEpisodes::Episode))
|
||||
.col(integer(FlixEpisodes::Count))
|
||||
.col(string(FlixEpisodes::Slug))
|
||||
.col(integer(FlixEpisodes::Library))
|
||||
.col(binary(FlixEpisodes::Directory))
|
||||
.col(string(FlixEpisodes::RelativeMediaPath))
|
||||
.col(string_null(FlixEpisodes::RelativePosterPath))
|
||||
.primary_key(
|
||||
Index::create()
|
||||
.col(FlixEpisodes::Show)
|
||||
.col(FlixEpisodes::Season)
|
||||
.col(FlixEpisodes::Episode),
|
||||
)
|
||||
.foreign_key(
|
||||
ForeignKeyCreateStatement::new()
|
||||
.name("fk-flix_episodes-show_season_episode")
|
||||
.from_tbl(FlixEpisodes::Table)
|
||||
.from_col(FlixEpisodes::Show)
|
||||
.from_col(FlixEpisodes::Season)
|
||||
.from_col(FlixEpisodes::Episode)
|
||||
.to_tbl(FlixInfoEpisodes::Table)
|
||||
.to_col(FlixInfoEpisodes::Show)
|
||||
.to_col(FlixInfoEpisodes::Season)
|
||||
.to_col(FlixInfoEpisodes::Episode),
|
||||
)
|
||||
.foreign_key(
|
||||
ForeignKeyCreateStatement::new()
|
||||
.name("fk-flix_episodes-library")
|
||||
.from_tbl(FlixEpisodes::Table)
|
||||
.from_col(FlixEpisodes::Library)
|
||||
.to_tbl(FlixLibraries::Table)
|
||||
.to_col(FlixLibraries::Id),
|
||||
)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn down(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.drop_table(Table::drop().table(FlixEpisodes::Table).to_owned())
|
||||
.await
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
use seamantic::schema::sqlite_rowid_alias;
|
||||
|
||||
use sea_orm::sea_query;
|
||||
use sea_orm::sea_query::Table;
|
||||
use sea_orm::{DbErr, Iden};
|
||||
use sea_orm_migration::SchemaManager;
|
||||
use sea_orm_migration::schema::binary;
|
||||
|
||||
#[derive(Iden)]
|
||||
pub enum FlixLibraries {
|
||||
Table,
|
||||
Id,
|
||||
Directory,
|
||||
}
|
||||
|
||||
pub async fn up(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.create_table(
|
||||
Table::create()
|
||||
.table(FlixLibraries::Table)
|
||||
.col(sqlite_rowid_alias(FlixLibraries::Id))
|
||||
.col(binary(FlixLibraries::Directory))
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn down(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.drop_table(Table::drop().table(FlixLibraries::Table).to_owned())
|
||||
.await
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
use seamantic::schema::sqlite_rowid_alias;
|
||||
|
||||
use sea_orm::sea_query;
|
||||
use sea_orm::sea_query::{ForeignKeyCreateStatement, Table};
|
||||
use sea_orm::{DbErr, Iden};
|
||||
use sea_orm_migration::SchemaManager;
|
||||
use sea_orm_migration::schema::{binary, integer, integer_null, string, string_null};
|
||||
|
||||
use crate::migration::m_000001::FlixInfoMovies;
|
||||
use crate::migration::m_000003::{FlixCollections, FlixLibraries};
|
||||
|
||||
#[derive(Iden)]
|
||||
pub enum FlixMovies {
|
||||
Table,
|
||||
Id,
|
||||
Parent,
|
||||
Slug,
|
||||
Library,
|
||||
Directory,
|
||||
RelativeMediaPath,
|
||||
RelativePosterPath,
|
||||
}
|
||||
|
||||
pub async fn up(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.create_table(
|
||||
Table::create()
|
||||
.table(FlixMovies::Table)
|
||||
.col(sqlite_rowid_alias(FlixMovies::Id))
|
||||
.col(integer_null(FlixMovies::Parent))
|
||||
.col(string(FlixMovies::Slug))
|
||||
.col(integer(FlixMovies::Library))
|
||||
.col(binary(FlixMovies::Directory))
|
||||
.col(string(FlixMovies::RelativeMediaPath))
|
||||
.col(string_null(FlixMovies::RelativePosterPath))
|
||||
.foreign_key(
|
||||
ForeignKeyCreateStatement::new()
|
||||
.name("fk-flix_movies-id")
|
||||
.from_tbl(FlixMovies::Table)
|
||||
.from_col(FlixMovies::Id)
|
||||
.to_tbl(FlixInfoMovies::Table)
|
||||
.to_col(FlixInfoMovies::Id),
|
||||
)
|
||||
.foreign_key(
|
||||
ForeignKeyCreateStatement::new()
|
||||
.name("fk-flix_movies-parent")
|
||||
.from_tbl(FlixMovies::Table)
|
||||
.from_col(FlixMovies::Parent)
|
||||
.to_tbl(FlixCollections::Table)
|
||||
.to_col(FlixCollections::Id),
|
||||
)
|
||||
.foreign_key(
|
||||
ForeignKeyCreateStatement::new()
|
||||
.name("fk-flix_movies-library")
|
||||
.from_tbl(FlixMovies::Table)
|
||||
.from_col(FlixMovies::Library)
|
||||
.to_tbl(FlixLibraries::Table)
|
||||
.to_col(FlixLibraries::Id),
|
||||
)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn down(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.drop_table(Table::drop().table(FlixMovies::Table).to_owned())
|
||||
.await
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
use sea_orm::sea_query;
|
||||
use sea_orm::sea_query::{ForeignKeyCreateStatement, Index, Table};
|
||||
use sea_orm::{DbErr, Iden};
|
||||
use sea_orm_migration::SchemaManager;
|
||||
use sea_orm_migration::schema::{binary, integer, string, string_null};
|
||||
|
||||
use crate::migration::m_000001::FlixInfoSeasons;
|
||||
use crate::migration::m_000003::FlixLibraries;
|
||||
|
||||
#[derive(Iden)]
|
||||
pub enum FlixSeasons {
|
||||
Table,
|
||||
Show,
|
||||
Season,
|
||||
Slug,
|
||||
Library,
|
||||
Directory,
|
||||
RelativePosterPath,
|
||||
}
|
||||
|
||||
pub async fn up(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.create_table(
|
||||
Table::create()
|
||||
.table(FlixSeasons::Table)
|
||||
.col(integer(FlixSeasons::Show))
|
||||
.col(integer(FlixSeasons::Season))
|
||||
.col(string(FlixSeasons::Slug))
|
||||
.col(integer(FlixSeasons::Library))
|
||||
.col(binary(FlixSeasons::Directory))
|
||||
.col(string_null(FlixSeasons::RelativePosterPath))
|
||||
.primary_key(
|
||||
Index::create()
|
||||
.col(FlixSeasons::Show)
|
||||
.col(FlixSeasons::Season),
|
||||
)
|
||||
.foreign_key(
|
||||
ForeignKeyCreateStatement::new()
|
||||
.name("fk-flix_seasons-show_season")
|
||||
.from_tbl(FlixSeasons::Table)
|
||||
.from_col(FlixSeasons::Show)
|
||||
.from_col(FlixSeasons::Season)
|
||||
.to_tbl(FlixInfoSeasons::Table)
|
||||
.to_col(FlixInfoSeasons::Show)
|
||||
.to_col(FlixInfoSeasons::Season),
|
||||
)
|
||||
.foreign_key(
|
||||
ForeignKeyCreateStatement::new()
|
||||
.name("fk-flix_seasons-library")
|
||||
.from_tbl(FlixSeasons::Table)
|
||||
.from_col(FlixSeasons::Library)
|
||||
.to_tbl(FlixLibraries::Table)
|
||||
.to_col(FlixLibraries::Id),
|
||||
)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn down(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.drop_table(Table::drop().table(FlixSeasons::Table).to_owned())
|
||||
.await
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
use seamantic::schema::sqlite_rowid_alias;
|
||||
|
||||
use sea_orm::sea_query;
|
||||
use sea_orm::sea_query::{ForeignKeyCreateStatement, Table};
|
||||
use sea_orm::{DbErr, Iden};
|
||||
use sea_orm_migration::SchemaManager;
|
||||
use sea_orm_migration::schema::{binary, integer, integer_null, string, string_null};
|
||||
|
||||
use crate::migration::m_000001::FlixInfoShows;
|
||||
use crate::migration::m_000003::{FlixCollections, FlixLibraries};
|
||||
|
||||
#[derive(Iden)]
|
||||
pub enum FlixShows {
|
||||
Table,
|
||||
Id,
|
||||
Parent,
|
||||
Slug,
|
||||
Library,
|
||||
Directory,
|
||||
RelativePosterPath,
|
||||
}
|
||||
|
||||
pub async fn up(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.create_table(
|
||||
Table::create()
|
||||
.table(FlixShows::Table)
|
||||
.col(sqlite_rowid_alias(FlixShows::Id))
|
||||
.col(integer_null(FlixShows::Parent))
|
||||
.col(string(FlixShows::Slug))
|
||||
.col(integer(FlixShows::Library))
|
||||
.col(binary(FlixShows::Directory))
|
||||
.col(string_null(FlixShows::RelativePosterPath))
|
||||
.foreign_key(
|
||||
ForeignKeyCreateStatement::new()
|
||||
.name("fk-flix_shows-id")
|
||||
.from_tbl(FlixShows::Table)
|
||||
.from_col(FlixShows::Id)
|
||||
.to_tbl(FlixInfoShows::Table)
|
||||
.to_col(FlixInfoShows::Id),
|
||||
)
|
||||
.foreign_key(
|
||||
ForeignKeyCreateStatement::new()
|
||||
.name("fk-flix_shows-parent")
|
||||
.from_tbl(FlixShows::Table)
|
||||
.from_col(FlixShows::Parent)
|
||||
.to_tbl(FlixCollections::Table)
|
||||
.to_col(FlixCollections::Id),
|
||||
)
|
||||
.foreign_key(
|
||||
ForeignKeyCreateStatement::new()
|
||||
.name("fk-flix_shows-library")
|
||||
.from_tbl(FlixShows::Table)
|
||||
.from_col(FlixShows::Library)
|
||||
.to_tbl(FlixLibraries::Table)
|
||||
.to_col(FlixLibraries::Id),
|
||||
)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn down(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.drop_table(Table::drop().table(FlixShows::Table).to_owned())
|
||||
.await
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
//! Adds entity/watched tables:
|
||||
//! - Collections
|
||||
//! - Movies
|
||||
//! - Shows
|
||||
//! - Seasons
|
||||
//! - Episodes
|
||||
|
||||
use sea_orm::{DbErr, DeriveMigrationName};
|
||||
use sea_orm_migration::async_trait;
|
||||
use sea_orm_migration::{MigrationTrait, SchemaManager};
|
||||
|
||||
mod collections;
|
||||
mod episodes;
|
||||
mod movies;
|
||||
mod seasons;
|
||||
mod shows;
|
||||
|
||||
#[allow(unused_imports)]
|
||||
pub use episodes::FlixWatchedEpisodes;
|
||||
#[allow(unused_imports)]
|
||||
pub use movies::FlixWatchedMovies;
|
||||
|
||||
#[derive(DeriveMigrationName)]
|
||||
pub(super) struct Migration;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl MigrationTrait for Migration {
|
||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
episodes::up(manager).await?;
|
||||
seasons::up(manager).await?;
|
||||
shows::up(manager).await?;
|
||||
movies::up(manager).await?;
|
||||
collections::up(manager).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
collections::down(manager).await?;
|
||||
movies::down(manager).await?;
|
||||
shows::down(manager).await?;
|
||||
seasons::down(manager).await?;
|
||||
episodes::down(manager).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
use sea_orm::DbErr;
|
||||
use sea_orm::{ConnectionTrait, DbBackend, Statement};
|
||||
use sea_orm_migration::SchemaManager;
|
||||
|
||||
pub async fn up(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
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,
|
||||
m.id,
|
||||
'movie' AS type
|
||||
FROM flix_movies m
|
||||
WHERE m.parent IS NOT NULL
|
||||
|
||||
UNION ALL
|
||||
|
||||
SELECT
|
||||
s.parent,
|
||||
s.id,
|
||||
'show' AS type
|
||||
FROM flix_shows s
|
||||
WHERE s.parent IS NOT NULL
|
||||
|
||||
UNION ALL
|
||||
|
||||
SELECT
|
||||
c.parent,
|
||||
ci.id,
|
||||
ci.type
|
||||
FROM collection_items ci
|
||||
JOIN flix_collections c
|
||||
ON c.id = ci.parent
|
||||
)
|
||||
SELECT
|
||||
ci.parent 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 = ci.parent
|
||||
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, 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,60 @@
|
||||
use sea_orm::sea_query;
|
||||
use sea_orm::sea_query::{ForeignKeyCreateStatement, Index, Table};
|
||||
use sea_orm::{DbErr, Iden};
|
||||
use sea_orm_migration::SchemaManager;
|
||||
use sea_orm_migration::schema::{date, integer};
|
||||
|
||||
use crate::migration::m_000001::FlixInfoEpisodes;
|
||||
|
||||
#[derive(Iden)]
|
||||
pub enum FlixWatchedEpisodes {
|
||||
Table,
|
||||
Show,
|
||||
Season,
|
||||
Episode,
|
||||
UserId,
|
||||
WatchedDate,
|
||||
}
|
||||
|
||||
pub async fn up(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.create_table(
|
||||
Table::create()
|
||||
.table(FlixWatchedEpisodes::Table)
|
||||
.col(integer(FlixWatchedEpisodes::Show))
|
||||
.col(integer(FlixWatchedEpisodes::Season))
|
||||
.col(integer(FlixWatchedEpisodes::Episode))
|
||||
.col(integer(FlixWatchedEpisodes::UserId))
|
||||
.col(date(FlixWatchedEpisodes::WatchedDate))
|
||||
.primary_key(
|
||||
Index::create()
|
||||
.col(FlixWatchedEpisodes::Show)
|
||||
.col(FlixWatchedEpisodes::Season)
|
||||
.col(FlixWatchedEpisodes::Episode)
|
||||
.col(FlixWatchedEpisodes::UserId),
|
||||
)
|
||||
.foreign_key(
|
||||
ForeignKeyCreateStatement::new()
|
||||
.name("fk-flix_watched_episodes-show_season_episode")
|
||||
.from_tbl(FlixWatchedEpisodes::Table)
|
||||
.from_tbl(FlixWatchedEpisodes::Table)
|
||||
.from_col(FlixWatchedEpisodes::Show)
|
||||
.from_col(FlixWatchedEpisodes::Season)
|
||||
.from_col(FlixWatchedEpisodes::Episode)
|
||||
.to_tbl(FlixInfoEpisodes::Table)
|
||||
.to_col(FlixInfoEpisodes::Show)
|
||||
.to_col(FlixInfoEpisodes::Season)
|
||||
.to_col(FlixInfoEpisodes::Episode),
|
||||
)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn down(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.drop_table(Table::drop().table(FlixWatchedEpisodes::Table).to_owned())
|
||||
.await
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
use sea_orm::sea_query;
|
||||
use sea_orm::sea_query::{ForeignKeyCreateStatement, Index, Table};
|
||||
use sea_orm::{DbErr, Iden};
|
||||
use sea_orm_migration::SchemaManager;
|
||||
use sea_orm_migration::schema::{date, integer};
|
||||
|
||||
use crate::migration::m_000001::FlixInfoMovies;
|
||||
|
||||
#[derive(Iden)]
|
||||
pub enum FlixWatchedMovies {
|
||||
Table,
|
||||
Id,
|
||||
UserId,
|
||||
WatchedDate,
|
||||
}
|
||||
|
||||
pub async fn up(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.create_table(
|
||||
Table::create()
|
||||
.table(FlixWatchedMovies::Table)
|
||||
.col(integer(FlixWatchedMovies::Id))
|
||||
.col(integer(FlixWatchedMovies::UserId))
|
||||
.col(date(FlixWatchedMovies::WatchedDate))
|
||||
.primary_key(
|
||||
Index::create()
|
||||
.col(FlixWatchedMovies::Id)
|
||||
.col(FlixWatchedMovies::UserId),
|
||||
)
|
||||
.foreign_key(
|
||||
ForeignKeyCreateStatement::new()
|
||||
.name("fk-flix_watched_movies-id")
|
||||
.from_tbl(FlixWatchedMovies::Table)
|
||||
.from_col(FlixWatchedMovies::Id)
|
||||
.to_tbl(FlixInfoMovies::Table)
|
||||
.to_col(FlixInfoMovies::Id),
|
||||
)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn down(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.drop_table(Table::drop().table(FlixWatchedMovies::Table).to_owned())
|
||||
.await
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
use sea_orm::DbErr;
|
||||
use sea_orm::{ConnectionTrait, DbBackend, Statement};
|
||||
use sea_orm_migration::SchemaManager;
|
||||
|
||||
pub async fn up(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.get_connection()
|
||||
.execute_raw(Statement::from_string(
|
||||
DbBackend::Sqlite,
|
||||
r#"
|
||||
CREATE VIEW flix_watched_seasons AS
|
||||
SELECT
|
||||
w.show,
|
||||
w.season,
|
||||
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 = w.show
|
||||
AND e.season = w.season
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM flix_watched_episodes wc
|
||||
WHERE wc.show = e.show
|
||||
AND wc.season = e.season
|
||||
AND wc.episode = e.episode
|
||||
AND wc.user_id = w.user_id
|
||||
)
|
||||
)
|
||||
GROUP BY w.show, w.season, 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(())
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
use sea_orm::DbErr;
|
||||
use sea_orm::{ConnectionTrait, DbBackend, Statement};
|
||||
use sea_orm_migration::SchemaManager;
|
||||
|
||||
pub async fn up(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
|
||||
manager
|
||||
.get_connection()
|
||||
.execute_raw(Statement::from_string(
|
||||
DbBackend::Sqlite,
|
||||
r#"
|
||||
CREATE VIEW flix_watched_shows AS
|
||||
SELECT
|
||||
w.show 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 = w.show
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM flix_watched_seasons wc
|
||||
WHERE wc.show = s.show
|
||||
AND wc.season = s.season
|
||||
AND wc.user_id = w.user_id
|
||||
)
|
||||
)
|
||||
GROUP BY w.show, 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(())
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//! Migrations for maintaining the database schema
|
||||
|
||||
seamantic::migrations! {
|
||||
"seaql_migrations_flix";
|
||||
m_000001,
|
||||
m_000002,
|
||||
m_000003,
|
||||
m_000004,
|
||||
}
|
||||
+13
-7
@@ -1,9 +1,9 @@
|
||||
[package]
|
||||
name = "flix"
|
||||
version = "0.0.2"
|
||||
version = "0.0.10"
|
||||
|
||||
categories = []
|
||||
description = "Types for storing persistent data about media"
|
||||
description = "Mechanisms for interacting with flix media"
|
||||
repository = "https://github.com/QuantumShade/flix"
|
||||
|
||||
authors.workspace = true
|
||||
@@ -11,16 +11,22 @@ edition.workspace = true
|
||||
license-file.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
default = []
|
||||
tmdb = ["dep:flix-tmdb"]
|
||||
fs = ["dep:flix-fs"]
|
||||
serde = ["flix-model/serde"]
|
||||
tmdb = ["dep:flix-tmdb", "flix-db/tmdb"]
|
||||
|
||||
[dependencies]
|
||||
flix-tmdb = { workspace = true, optional = true }
|
||||
flix-db = { workspace = true }
|
||||
flix-model = { workspace = true }
|
||||
|
||||
chrono = { workspace = true, features = ["serde"] }
|
||||
serde = { workspace = true, features = ["std", "derive"] }
|
||||
thiserror = { workspace = true }
|
||||
flix-fs = { workspace = true, optional = true }
|
||||
flix-tmdb = { workspace = true, optional = true }
|
||||
|
||||
@@ -2,4 +2,4 @@
|
||||
|
||||
[](https://crates.io/crates/flix)
|
||||
|
||||
A library providing types for storing persistent data about media
|
||||
A library for interacting with flix media
|
||||
|
||||
+12
-3
@@ -1,4 +1,13 @@
|
||||
//! flix provides types for storing persistent data about media
|
||||
//! flix provides mechanisms for interacting with flix media
|
||||
|
||||
/// flix types
|
||||
pub mod model;
|
||||
#![cfg_attr(docsrs, feature(doc_cfg))]
|
||||
|
||||
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;
|
||||
|
||||
@@ -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 name
|
||||
pub name: 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,
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
use chrono::NaiveDate;
|
||||
|
||||
/// An Episode container
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Episode {
|
||||
/// The generic episode data
|
||||
pub episode: GenericEpisode,
|
||||
}
|
||||
|
||||
/// The generic episode data
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub struct GenericEpisode {
|
||||
/// The episode's name
|
||||
pub name: String,
|
||||
/// The episode's overview
|
||||
pub overview: String,
|
||||
/// The episode's air date
|
||||
pub air_date: NaiveDate,
|
||||
}
|
||||
@@ -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::*;
|
||||
@@ -1,36 +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 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>,
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
use chrono::NaiveDate;
|
||||
|
||||
/// A Season container
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Season {
|
||||
/// The generic season data
|
||||
pub season: GenericSeason,
|
||||
}
|
||||
|
||||
/// The generic season data
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub struct GenericSeason {
|
||||
/// The season's name
|
||||
pub name: String,
|
||||
/// The season's overview
|
||||
pub overview: String,
|
||||
/// The season's air date
|
||||
pub air_date: NaiveDate,
|
||||
}
|
||||
@@ -1,36 +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 name
|
||||
pub name: String,
|
||||
/// The show's overview
|
||||
pub overview: 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>,
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
#[cfg(feature = "tmdb")]
|
||||
use flix_tmdb::model::{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 name
|
||||
pub name: 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 movie TMDB IDs in the verse
|
||||
pub movies: Vec<MovieId>,
|
||||
/// The list of show TMDB IDs in the verse
|
||||
pub shows: Vec<ShowId>,
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
[package]
|
||||
name = "flix-fs"
|
||||
version = "0.0.10"
|
||||
|
||||
categories = []
|
||||
description = "Filesystem scanner for flix media"
|
||||
repository = "https://github.com/QuantumShade/flix"
|
||||
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
license-file.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
flix-model = { workspace = true }
|
||||
|
||||
async-stream = { workspace = true }
|
||||
regex = { workspace = true, features = ["std", "perf"] }
|
||||
thiserror = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
tokio-stream = { workspace = true, features = ["fs"] }
|
||||
@@ -0,0 +1,5 @@
|
||||
# flix-fs
|
||||
|
||||
[](https://crates.io/crates/flix-fs)
|
||||
|
||||
A library providing filesystem scanners for flix media
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -0,0 +1,282 @@
|
||||
//! 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 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) {
|
||||
is_image_extension!() => {
|
||||
if poster_file_name.is_some() {
|
||||
yield Item {
|
||||
path: path.to_owned(),
|
||||
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: path.to_owned(),
|
||||
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());
|
||||
}
|
||||
}
|
||||
}))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
//! 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 filetype = match dir.file_type().await {
|
||||
Ok(filetype) => filetype,
|
||||
Err(err) => {
|
||||
yield Item {
|
||||
path: path.to_owned(),
|
||||
event: Err(Error::FileType(err)),
|
||||
};
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if !filetype.is_file() {
|
||||
yield Item {
|
||||
path: path.to_owned(),
|
||||
event: Err(Error::UnexpectedNonFile),
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
let path = dir.path();
|
||||
match path.extension().and_then(OsStr::to_str) {
|
||||
is_media_extension!() => {
|
||||
if media_file_name.is_some() {
|
||||
yield Item {
|
||||
path: path.to_owned(),
|
||||
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: path.to_owned(),
|
||||
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: path.to_owned(),
|
||||
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,
|
||||
}),
|
||||
};
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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 filetype = match dir.file_type().await {
|
||||
Ok(filetype) => filetype,
|
||||
Err(err) => {
|
||||
yield Item {
|
||||
path: path.to_owned(),
|
||||
event: Err(Error::FileType(err)),
|
||||
};
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if !filetype.is_dir() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let dir_path = dir.path();
|
||||
let Some(folder_name) = dir_path.file_name().and_then(OsStr::to_str)
|
||||
else {
|
||||
yield Item {
|
||||
path: path.to_owned(),
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -0,0 +1,142 @@
|
||||
//! 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 filetype = match dir.file_type().await {
|
||||
Ok(filetype) => filetype,
|
||||
Err(err) => {
|
||||
yield Item {
|
||||
path: path.to_owned(),
|
||||
event: Err(Error::FileType(err)),
|
||||
};
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if !filetype.is_file() {
|
||||
yield Item {
|
||||
path: path.to_owned(),
|
||||
event: Err(Error::UnexpectedNonFile),
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
let path = dir.path();
|
||||
match path.extension().and_then(OsStr::to_str) {
|
||||
is_media_extension!() => {
|
||||
if media_file_name.is_some() {
|
||||
yield Item {
|
||||
path: path.to_owned(),
|
||||
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: path.to_owned(),
|
||||
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: path.to_owned(),
|
||||
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,
|
||||
}),
|
||||
};
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
//! 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 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() {
|
||||
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: path.to_owned(),
|
||||
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: path.to_owned(),
|
||||
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: path.to_owned(),
|
||||
event: Err(Error::UnexpectedFolder),
|
||||
};
|
||||
continue;
|
||||
};
|
||||
|
||||
let Some((_, s_e_str)) = episode_dir_name.split_once('S') else {
|
||||
yield Item {
|
||||
path: path.to_owned(),
|
||||
event: Err(Error::UnexpectedFolder),
|
||||
};
|
||||
continue;
|
||||
};
|
||||
let Some((s_str, e_str)) = s_e_str.split_once('E') else {
|
||||
yield Item {
|
||||
path: path.to_owned(),
|
||||
event: Err(Error::UnexpectedFolder),
|
||||
};
|
||||
continue;
|
||||
};
|
||||
|
||||
let Ok(season_number) = s_str.parse::<SeasonNumber>() else {
|
||||
yield Item {
|
||||
path: path.to_owned(),
|
||||
event: Err(Error::UnexpectedFolder),
|
||||
};
|
||||
continue;
|
||||
};
|
||||
if season_number != season {
|
||||
yield Item {
|
||||
path: path.to_owned(),
|
||||
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: path.to_owned(),
|
||||
event: Err(Error::UnexpectedFolder),
|
||||
};
|
||||
continue;
|
||||
};
|
||||
let Ok(episode_numbers) = EpisodeNumbers::try_from(episode_numbers.as_ref()) else {
|
||||
yield Item {
|
||||
path: path.to_owned(),
|
||||
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());
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
//! 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 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() {
|
||||
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: path.to_owned(),
|
||||
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: path.to_owned(),
|
||||
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: path.to_owned(),
|
||||
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: path.to_owned(),
|
||||
event: Err(Error::UnexpectedFolder),
|
||||
};
|
||||
continue;
|
||||
};
|
||||
|
||||
for await event in season::Scanner::scan_season(&season_dir, id, season_number) {
|
||||
yield event.map(|e| e.into());
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
[package]
|
||||
name = "flix-model"
|
||||
version = "0.0.10"
|
||||
|
||||
categories = []
|
||||
description = "Core types for flix data"
|
||||
repository = "https://github.com/QuantumShade/flix"
|
||||
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
license-file.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
default = []
|
||||
serde = ["dep:serde"]
|
||||
|
||||
[dependencies]
|
||||
seamantic = { workspace = true }
|
||||
|
||||
serde = { workspace = true, optional = true, features = ["std", "derive"] }
|
||||
thiserror = { workspace = true }
|
||||
@@ -0,0 +1,5 @@
|
||||
# flix-model
|
||||
|
||||
[](https://crates.io/crates/flix-model)
|
||||
|
||||
A library providing core types for flix data
|
||||
@@ -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>;
|
||||
@@ -0,0 +1,6 @@
|
||||
//! flix-model provides core types for flix data
|
||||
|
||||
#![cfg_attr(docsrs, feature(doc_cfg))]
|
||||
|
||||
pub mod id;
|
||||
pub mod numbers;
|
||||
@@ -0,0 +1,60 @@
|
||||
//! This module contains season and episode numbers and related errors
|
||||
|
||||
use core::ops::RangeInclusive;
|
||||
use std::collections::HashSet;
|
||||
|
||||
/// Type alias for representing season numbers
|
||||
pub type SeasonNumber = u32;
|
||||
/// Type alias for representing episode numbers
|
||||
pub type EpisodeNumber = u32;
|
||||
|
||||
/// 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)]
|
||||
#[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.saturating_sub(min).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 {
|
||||
/// Get the range of episodes
|
||||
pub fn as_range(&self) -> &RangeInclusive<EpisodeNumber> {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
+18
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "flix-tmdb"
|
||||
version = "0.0.2"
|
||||
version = "0.0.10"
|
||||
|
||||
categories = []
|
||||
description = "Clients and models for fetching data from TMDB"
|
||||
@@ -11,13 +11,30 @@ edition.workspace = true
|
||||
license-file.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
default = []
|
||||
sea-orm = ["dep:sea-orm"]
|
||||
|
||||
[dependencies]
|
||||
flix-model = { workspace = true }
|
||||
|
||||
chrono = { workspace = true, features = ["serde"] }
|
||||
governor = { workspace = true, features = ["std", "jitter"] }
|
||||
nonzero_ext = { workspace = true }
|
||||
reqwest = { workspace = true, features = ["json", "rustls-tls"] }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
thiserror = { workspace = true }
|
||||
url = { workspace = true }
|
||||
url-macro = { workspace = true }
|
||||
|
||||
sea-orm = { workspace = true, optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_test = { workspace = true }
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
//! Collections API
|
||||
|
||||
use core::time::Duration;
|
||||
use std::rc::Rc;
|
||||
|
||||
use governor::Jitter;
|
||||
|
||||
use crate::Config;
|
||||
use crate::model::{Collection, CollectionId};
|
||||
use crate::model::Collection;
|
||||
use crate::model::id::CollectionId;
|
||||
|
||||
use super::{Error, make_request};
|
||||
|
||||
@@ -24,12 +30,20 @@ impl Client {
|
||||
id: impl Into<CollectionId>,
|
||||
language: Option<&str>,
|
||||
) -> Result<Collection, Error> {
|
||||
self.config
|
||||
.limiter
|
||||
.until_ready_with_jitter(Jitter::new(
|
||||
Duration::from_millis(0),
|
||||
Duration::from_millis(50),
|
||||
))
|
||||
.await;
|
||||
|
||||
Ok(self
|
||||
.config
|
||||
.client
|
||||
.execute(make_request(
|
||||
&self.config,
|
||||
&format!("/3/collection/{}", id.into()),
|
||||
&format!("/3/collection/{}", id.into().into_raw()),
|
||||
language,
|
||||
)?)
|
||||
.await?
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
//! Episodes API
|
||||
|
||||
use core::time::Duration;
|
||||
use std::rc::Rc;
|
||||
|
||||
use flix_model::numbers::{EpisodeNumber, SeasonNumber};
|
||||
|
||||
use governor::Jitter;
|
||||
|
||||
use crate::Config;
|
||||
use crate::model::{Episode, ShowId};
|
||||
use crate::model::Episode;
|
||||
use crate::model::id::ShowId;
|
||||
|
||||
use super::{Error, make_request};
|
||||
|
||||
@@ -22,10 +30,18 @@ impl Client {
|
||||
pub async fn get_details(
|
||||
&self,
|
||||
id: impl Into<ShowId>,
|
||||
season: impl Into<i32>,
|
||||
episode: impl Into<i32>,
|
||||
season: impl Into<SeasonNumber>,
|
||||
episode: impl Into<EpisodeNumber>,
|
||||
language: Option<&str>,
|
||||
) -> Result<Episode, Error> {
|
||||
self.config
|
||||
.limiter
|
||||
.until_ready_with_jitter(Jitter::new(
|
||||
Duration::from_millis(0),
|
||||
Duration::from_millis(50),
|
||||
))
|
||||
.await;
|
||||
|
||||
Ok(self
|
||||
.config
|
||||
.client
|
||||
@@ -33,7 +49,7 @@ impl Client {
|
||||
&self.config,
|
||||
&format!(
|
||||
"/3/tv/{}/season/{}/episode/{}",
|
||||
id.into(),
|
||||
id.into().into_raw(),
|
||||
season.into(),
|
||||
episode.into()
|
||||
),
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user