You've already forked flix
Throw away flix files in favor of a flix database
This commit is contained in:
+11
-6
@@ -1,9 +1,9 @@
|
||||
[package]
|
||||
name = "flix-cli"
|
||||
version = "0.0.8"
|
||||
version = "0.0.9"
|
||||
|
||||
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,8 +50,9 @@ clap = { workspace = true, features = [
|
||||
"suggestions",
|
||||
"usage",
|
||||
] }
|
||||
home = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
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>
|
||||
```
|
||||
|
||||
+40
-22
@@ -1,5 +1,6 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::{Result, anyhow};
|
||||
use clap::{Parser, Subcommand};
|
||||
|
||||
pub mod tmdb;
|
||||
@@ -11,18 +12,35 @@ pub struct Cli {
|
||||
#[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,
|
||||
}
|
||||
|
||||
impl Cli {
|
||||
pub fn config_path(&self) -> PathBuf {
|
||||
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(_) => self.config.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn database_path(&self) -> Result<String> {
|
||||
self.database
|
||||
.as_os_str()
|
||||
.to_str()
|
||||
.map(ToOwned::to_owned)
|
||||
.ok_or_else(|| anyhow!(".as_os_str().to_str()"))
|
||||
}
|
||||
|
||||
pub fn command(self) -> Command {
|
||||
self.command
|
||||
}
|
||||
@@ -30,30 +48,35 @@ impl Cli {
|
||||
|
||||
#[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", default_value = "flix.toml")]
|
||||
output: PathBuf,
|
||||
|
||||
#[command(subcommand)]
|
||||
command: BackendCommand,
|
||||
},
|
||||
/// Update a flix manifest
|
||||
/// 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")]
|
||||
#[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)]
|
||||
@@ -70,8 +93,3 @@ impl From<tmdb::Command> for BackendCommand {
|
||||
Self::Tmdb { command: value }
|
||||
}
|
||||
}
|
||||
|
||||
fn expect_home_dir() -> PathBuf {
|
||||
#[allow(clippy::expect_used)]
|
||||
home::home_dir().expect("you do not have a home directory")
|
||||
}
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
use flix::model::numbers::{EpisodeNumber, SeasonNumber};
|
||||
use flix::tmdb::model::id::RawId;
|
||||
|
||||
use clap::Subcommand;
|
||||
|
||||
#[derive(Subcommand)]
|
||||
@@ -5,35 +8,35 @@ pub enum Command {
|
||||
/// Process a TMDB collection
|
||||
Collection {
|
||||
#[arg(value_name = "TMDB_ID")]
|
||||
id: u32,
|
||||
id: RawId,
|
||||
},
|
||||
/// Process a TMDB movie
|
||||
Movie {
|
||||
#[arg(value_name = "TMDB_ID")]
|
||||
id: u32,
|
||||
id: RawId,
|
||||
},
|
||||
/// Process a TMDB show
|
||||
Show {
|
||||
#[arg(value_name = "TMDB_ID")]
|
||||
id: u32,
|
||||
id: RawId,
|
||||
},
|
||||
/// Process a TMDB season
|
||||
Season {
|
||||
#[arg(value_name = "TMDB_ID")]
|
||||
id: u32,
|
||||
id: RawId,
|
||||
#[arg(value_name = "SEASON_NUM")]
|
||||
season: u32,
|
||||
season: SeasonNumber,
|
||||
},
|
||||
/// Process a TMDB episode
|
||||
#[command(trailing_var_arg = true)]
|
||||
Episode {
|
||||
#[arg(value_name = "TMDB_ID")]
|
||||
id: u32,
|
||||
id: RawId,
|
||||
#[arg(value_name = "SEASON_NUM")]
|
||||
season: u32,
|
||||
season: SeasonNumber,
|
||||
#[arg(value_name = "EPISODE_NUM")]
|
||||
episode: u32,
|
||||
episode: EpisodeNumber,
|
||||
#[arg(value_name = "...")]
|
||||
episodes: Vec<u32>,
|
||||
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))]
|
||||
+48
-44
@@ -1,11 +1,10 @@
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use flix_tmdb::Client;
|
||||
use flix::tmdb::Client;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use clap::Parser;
|
||||
use tokio::fs;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
|
||||
mod cli;
|
||||
use cli::{BackendCommand, Cli, Command};
|
||||
@@ -13,8 +12,8 @@ use cli::{BackendCommand, Cli, Command};
|
||||
mod config;
|
||||
use config::Config;
|
||||
|
||||
mod db;
|
||||
mod run;
|
||||
use run::flix::FlixObject;
|
||||
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
async fn main() -> Result<()> {
|
||||
@@ -25,67 +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 } => exec_print(client, command).await?,
|
||||
Command::Write {
|
||||
force,
|
||||
output,
|
||||
command,
|
||||
} => exec_write(client, force, &output, command).await?,
|
||||
Command::Update { output } => exec_update(client, &output).await?,
|
||||
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_print(client: Client, command: BackendCommand) -> Result<()> {
|
||||
async fn exec_init(database_path: String) -> Result<()> {
|
||||
db::open_new(database_path).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn exec_add(client: Client, database_path: String, command: BackendCommand) -> Result<()> {
|
||||
let database = db::open(database_path).await?;
|
||||
|
||||
match command {
|
||||
BackendCommand::Tmdb { command } => {
|
||||
let object = run::tmdb::TmdbObject::fetch(&client, command).await?;
|
||||
println!("{}", object.serialize().context("failed to serialize")?)
|
||||
run::tmdb::add(client, database.as_ref(), command).await?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn exec_write(
|
||||
client: Client,
|
||||
force: bool,
|
||||
output: &Path,
|
||||
command: BackendCommand,
|
||||
) -> Result<()> {
|
||||
async fn exec_update(client: Client, database_path: String, command: BackendCommand) -> Result<()> {
|
||||
let database = db::open(database_path).await?;
|
||||
|
||||
match command {
|
||||
BackendCommand::Tmdb { command } => {
|
||||
let object = run::tmdb::TmdbObject::fetch(&client, command).await?;
|
||||
|
||||
let mut file = if force {
|
||||
fs::File::create(output).await
|
||||
} else {
|
||||
fs::File::create_new(output).await
|
||||
}
|
||||
.with_context(|| format!("could not create file at path {}", output.display()))?;
|
||||
file.write_all(
|
||||
object
|
||||
.serialize()
|
||||
.context("failed to serialize tmdb object")?
|
||||
.as_bytes(),
|
||||
)
|
||||
.await
|
||||
.with_context(|| format!("could not write to file at path {}", output.display()))?;
|
||||
run::tmdb::update(client, database.as_ref(), command).await?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn exec_update(client: Client, output: &Path) -> Result<()> {
|
||||
let content = fs::read_to_string(output)
|
||||
.await
|
||||
.with_context(|| format!("failed to read file at path: {}", output.display()))?;
|
||||
let object: FlixObject = toml::from_str(&content)
|
||||
.with_context(|| format!("failed to deserialize flix file: {}", output.display()))?;
|
||||
async fn exec_delete(client: Client, database_path: String, command: BackendCommand) -> Result<()> {
|
||||
let database = db::open(database_path).await?;
|
||||
|
||||
let command = object.backend_command()?;
|
||||
exec_write(client, true, output, command).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!()
|
||||
}
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
use flix::model::{Collection, Episode, Movie, Season, Show, Verse};
|
||||
|
||||
use anyhow::{Result, anyhow, bail};
|
||||
|
||||
use crate::cli::BackendCommand;
|
||||
use crate::cli::tmdb;
|
||||
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum FlixObject {
|
||||
Collection(Collection),
|
||||
Movie(Movie),
|
||||
Show(Show),
|
||||
Season(Season),
|
||||
Episode(Episode),
|
||||
// DEAD CODE: The TMDB backend does not support Verses
|
||||
#[allow(dead_code)]
|
||||
Verse(Verse),
|
||||
}
|
||||
|
||||
impl FlixObject {
|
||||
pub fn backend_command(&self) -> Result<BackendCommand> {
|
||||
Ok(match self {
|
||||
FlixObject::Collection(collection) => {
|
||||
let Some(ref tmdb) = collection.tmdb else {
|
||||
bail!("missing tmdb data")
|
||||
};
|
||||
tmdb::Command::Collection { id: tmdb.id.into() }.into()
|
||||
}
|
||||
FlixObject::Movie(movie) => {
|
||||
let Some(ref tmdb) = movie.tmdb else {
|
||||
bail!("missing tmdb data")
|
||||
};
|
||||
tmdb::Command::Movie { id: tmdb.id.into() }.into()
|
||||
}
|
||||
FlixObject::Show(show) => {
|
||||
let Some(ref tmdb) = show.tmdb else {
|
||||
bail!("missing tmdb data")
|
||||
};
|
||||
tmdb::Command::Show { id: tmdb.id.into() }.into()
|
||||
}
|
||||
FlixObject::Season(season) => {
|
||||
let Some(ref tmdb) = season.tmdb else {
|
||||
bail!("missing tmdb data")
|
||||
};
|
||||
tmdb::Command::Season {
|
||||
id: tmdb.show_id.into(),
|
||||
season: season.season.number,
|
||||
}
|
||||
.into()
|
||||
}
|
||||
FlixObject::Episode(episode) => {
|
||||
let Some(ref tmdb) = episode.tmdb else {
|
||||
bail!("missing tmdb data")
|
||||
};
|
||||
tmdb::Command::Episode {
|
||||
id: tmdb.show_id.into(),
|
||||
season: episode.episode.season,
|
||||
episode: episode
|
||||
.episode
|
||||
.number
|
||||
.primary_episode_number()
|
||||
.ok_or_else(|| {
|
||||
anyhow!("the episode does not have a primary episode number")
|
||||
})?,
|
||||
episodes: episode.episode.number.additional_episode_numbers(),
|
||||
}
|
||||
.into()
|
||||
}
|
||||
FlixObject::Verse(_) => {
|
||||
bail!("verses are not handled")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,2 +1 @@
|
||||
pub mod flix;
|
||||
pub mod tmdb;
|
||||
|
||||
+489
-139
@@ -1,157 +1,507 @@
|
||||
use flix::model::{
|
||||
Collection, Episode, EpisodeNumber, GenericCollection, GenericEpisode, GenericMovie,
|
||||
GenericSeason, GenericShow, Movie, Season, Show, TmdbCollection, TmdbEpisode, TmdbMovie,
|
||||
TmdbSeason, TmdbShow,
|
||||
};
|
||||
use flix_tmdb::Client;
|
||||
use flix_tmdb::model::{
|
||||
Collection as TCollection, Episode as TEpisode, Movie as TMovie, Season as TSeason,
|
||||
Show as TShow, ShowId,
|
||||
use std::collections::HashMap;
|
||||
|
||||
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 futures::{StreamExt, TryStreamExt, stream};
|
||||
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, ShowId),
|
||||
Episode(TEpisode, Vec<u32>, u32, ShowId),
|
||||
}
|
||||
pub async fn add(client: Client, db: &DatabaseConnection, command: Command) -> Result<()> {
|
||||
match command {
|
||||
Command::Collection { id } => {
|
||||
let id = TmdbCollectionId::from_raw(id);
|
||||
|
||||
impl TmdbObject {
|
||||
pub fn serialize(self) -> Result<String> {
|
||||
Ok(match self {
|
||||
TmdbObject::Collection(tmdb) => toml::to_string(&Collection {
|
||||
collection: GenericCollection {
|
||||
title: tmdb.title,
|
||||
overview: tmdb.overview,
|
||||
},
|
||||
tmdb: Some(TmdbCollection { id: tmdb.id }),
|
||||
})?,
|
||||
TmdbObject::Movie(tmdb) => toml::to_string(&Movie {
|
||||
movie: GenericMovie {
|
||||
title: tmdb.title,
|
||||
overview: tmdb.overview,
|
||||
genres: tmdb.genres.iter().cloned().map(|g| g.name).collect(),
|
||||
release_date: tmdb.release_date,
|
||||
},
|
||||
tmdb: Some(TmdbMovie {
|
||||
id: tmdb.id,
|
||||
genres: tmdb.genres.iter().map(|g| g.id).collect(),
|
||||
}),
|
||||
})?,
|
||||
TmdbObject::Show(tmdb) => toml::to_string(&Show {
|
||||
show: GenericShow {
|
||||
title: tmdb.title,
|
||||
overview: tmdb.overview,
|
||||
genres: tmdb.genres.iter().cloned().map(|g| g.name).collect(),
|
||||
air_date: tmdb.first_air_date,
|
||||
},
|
||||
tmdb: Some(TmdbShow {
|
||||
id: tmdb.id,
|
||||
genres: tmdb.genres.iter().map(|g| g.id).collect(),
|
||||
}),
|
||||
})?,
|
||||
TmdbObject::Season(tmdb, show_id) => toml::to_string(&Season {
|
||||
season: GenericSeason {
|
||||
number: tmdb.season_number,
|
||||
title: tmdb.title,
|
||||
overview: tmdb.overview,
|
||||
air_date: tmdb.air_date,
|
||||
},
|
||||
tmdb: Some(TmdbSeason { show_id }),
|
||||
})?,
|
||||
TmdbObject::Episode(tmdb, mut episode_numbers, season_number, show_id) => {
|
||||
toml::to_string(&Episode {
|
||||
episode: GenericEpisode {
|
||||
number: if episode_numbers.is_empty() {
|
||||
EpisodeNumber::Single {
|
||||
number: tmdb.episode_number,
|
||||
}
|
||||
} else {
|
||||
episode_numbers.insert(0, tmdb.episode_number);
|
||||
EpisodeNumber::Multiple {
|
||||
numbers: episode_numbers,
|
||||
}
|
||||
},
|
||||
season: season_number,
|
||||
title: tmdb.title,
|
||||
overview: tmdb.overview,
|
||||
air_date: tmdb.air_date,
|
||||
},
|
||||
tmdb: Some(TmdbEpisode { show_id }),
|
||||
})?
|
||||
let collection = entity::tmdb::collections::Entity::find_by_id(id)
|
||||
.one(db)
|
||||
.await?;
|
||||
if collection.is_some() {
|
||||
bail!("collection already exists");
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TmdbObject {
|
||||
pub async fn fetch(client: &Client, command: Command) -> Result<Self> {
|
||||
Ok(match command {
|
||||
Command::Collection { id } => Self::Collection(
|
||||
client
|
||||
.collections()
|
||||
.get_details(id, None)
|
||||
.await
|
||||
.with_context(|| format!("could not get collection details for '{id}'"))?,
|
||||
),
|
||||
Command::Movie { id } => Self::Movie(
|
||||
client
|
||||
.movies()
|
||||
.get_details(id, None)
|
||||
.await
|
||||
.with_context(|| format!("could not get movie details for '{id}'"))?,
|
||||
),
|
||||
Command::Show { id } => Self::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
|
||||
let collection = client
|
||||
.collections()
|
||||
.get_details(id, None)
|
||||
.await
|
||||
.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!("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!("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}"))?,
|
||||
id.into(),
|
||||
),
|
||||
Command::Episode {
|
||||
id,
|
||||
season,
|
||||
episode,
|
||||
episodes,
|
||||
} => {
|
||||
let mut episode = client
|
||||
.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, episode, None)
|
||||
.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,
|
||||
episodes,
|
||||
} => {
|
||||
let id = TmdbShowId::from_raw(id);
|
||||
let season_number = season;
|
||||
|
||||
let Some(show) = entity::tmdb::shows::Entity::find_by_id(id).one(db).await? else {
|
||||
bail!("show does not exists");
|
||||
};
|
||||
let Some(_) = entity::tmdb::seasons::Entity::find_by_id((id, season))
|
||||
.one(db)
|
||||
.await?
|
||||
else {
|
||||
bail!("season does not exists");
|
||||
};
|
||||
|
||||
async fn fetch_episode(
|
||||
client: &Client,
|
||||
db: &DatabaseConnection,
|
||||
flix_id: ShowId,
|
||||
tmdb_id: TmdbShowId,
|
||||
id: TmdbShowId,
|
||||
season: SeasonNumber,
|
||||
episode: EpisodeNumber,
|
||||
) -> Result<()> {
|
||||
let episode_number = episode;
|
||||
|
||||
let episode = entity::tmdb::episodes::Entity::find_by_id((id, season, episode))
|
||||
.one(db)
|
||||
.await?;
|
||||
if episode.is_some() {
|
||||
bail!("episode already exists");
|
||||
}
|
||||
|
||||
let episode = client
|
||||
.episodes()
|
||||
.get_details(id, season, episode_number, None)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!("could not get show details for '{id}' S{season}E{episode}")
|
||||
format!("episodes().get_details({}, {})", id.into_raw(), season)
|
||||
})?;
|
||||
let title = stream::once(async { Ok(episode.title) })
|
||||
.chain(stream::iter(episodes.clone()).then(|episode| async move {
|
||||
client
|
||||
.episodes()
|
||||
.get_details(id, season, episode, None)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!("could not get show details for '{id}' S{season}E{episode}")
|
||||
})
|
||||
.map(|episode| episode.title)
|
||||
}))
|
||||
.try_collect::<Vec<_>>()
|
||||
.await?
|
||||
.join(" + ");
|
||||
episode.title = title;
|
||||
Self::Episode(episode, episodes, season, id.into())
|
||||
|
||||
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")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user