From 89be8ac4296a72df4f877348892e7a6b27f1850f Mon Sep 17 00:00:00 2001
From: bytedream
Date: Mon, 25 Mar 2024 13:30:40 +0100
Subject: [PATCH 01/82] Update README.md
---
README.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/README.md b/README.md
index 46bee72..7636dc1 100644
--- a/README.md
+++ b/README.md
@@ -1,3 +1,5 @@
+# This project has been sunset as Crunchyroll moved to a DRM-only system. See [#362](https://github.com/crunchy-labs/crunchy-cli/issues/362).
+
# crunchy-cli
👇 A Command-line downloader for [Crunchyroll](https://www.crunchyroll.com).
From ba8028737dbd5e99f7cc7d40d432e0f34505d9fa Mon Sep 17 00:00:00 2001
From: Amelia
Date: Wed, 3 Apr 2024 06:49:51 -0700
Subject: [PATCH 02/82] Update missing fonts (#360)
* Update missing fonts
* Compile fix
---
crunchy-cli-core/src/utils/download.rs | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/crunchy-cli-core/src/utils/download.rs b/crunchy-cli-core/src/utils/download.rs
index 7f87583..736f9e6 100644
--- a/crunchy-cli-core/src/utils/download.rs
+++ b/crunchy-cli-core/src/utils/download.rs
@@ -1015,7 +1015,7 @@ fn get_video_stats(path: &Path) -> Result<(NaiveTime, f64)> {
}
// all subtitle fonts (extracted from javascript)
-const FONTS: [(&str, &str); 66] = [
+const FONTS: [(&str, &str); 68] = [
("Adobe Arabic", "AdobeArabic-Bold.woff2"),
("Andale Mono", "andalemo.woff2"),
("Arial", "arial.woff2"),
@@ -1073,6 +1073,8 @@ const FONTS: [(&str, &str); 66] = [
("Impact", "impact.woff2"),
("Mangal", "MANGAL.woff2"),
("Meera Inimai", "MeeraInimai-Regular.woff2"),
+ ("Noto Sans Tamil", "NotoSansTamil.woff2"),
+ ("Noto Sans Telugu", "NotoSansTelegu.woff2"),
("Noto Sans Thai", "NotoSansThai.woff2"),
("Rubik", "Rubik-Regular.woff2"),
("Rubik Black", "Rubik-Black.woff2"),
From e694046b07fbcabf40714e62d1ac7a98f511fcdd Mon Sep 17 00:00:00 2001
From: bytedream
Date: Wed, 3 Apr 2024 15:48:15 +0200
Subject: [PATCH 03/82] Move to new, DRM-free, endpoint
---
Cargo.lock | 404 ++++++++++-------------
crunchy-cli-core/Cargo.toml | 6 +-
crunchy-cli-core/src/archive/command.rs | 2 +-
crunchy-cli-core/src/download/command.rs | 2 +-
crunchy-cli-core/src/search/format.rs | 36 +-
crunchy-cli-core/src/utils/download.rs | 57 ++--
crunchy-cli-core/src/utils/format.rs | 31 +-
crunchy-cli-core/src/utils/video.rs | 38 +--
8 files changed, 245 insertions(+), 331 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index 113b430..b7617b1 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -17,17 +17,6 @@ version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe"
-[[package]]
-name = "aes"
-version = "0.8.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
-dependencies = [
- "cfg-if",
- "cipher",
- "cpufeatures",
-]
-
[[package]]
name = "aho-corasick"
version = "1.1.2"
@@ -156,13 +145,19 @@ version = "0.21.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567"
+[[package]]
+name = "base64"
+version = "0.22.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9475866fec1451be56a3c2400fd081ff546538961565ccb5b7142cbd22bc7a51"
+
[[package]]
name = "base64-serde"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba368df5de76a5bea49aaf0cf1b39ccfbbef176924d1ba5db3e4135216cbe3c7"
dependencies = [
- "base64",
+ "base64 0.21.7",
"serde",
]
@@ -178,15 +173,6 @@ version = "2.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed570934406eb16438a4e976b1b4500774099c13b8cb96eec99f620f05090ddf"
-[[package]]
-name = "block-padding"
-version = "0.3.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93"
-dependencies = [
- "generic-array",
-]
-
[[package]]
name = "bumpalo"
version = "3.15.4"
@@ -199,15 +185,6 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2bd12c1caf447e69cd4528f47f94d203fd2582878ecb9e9465484c4148a8223"
-[[package]]
-name = "cbc"
-version = "0.1.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6"
-dependencies = [
- "cipher",
-]
-
[[package]]
name = "cc"
version = "1.0.90"
@@ -228,9 +205,9 @@ checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e"
[[package]]
name = "chrono"
-version = "0.4.35"
+version = "0.4.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8eaf5903dcbc0a39312feb77df2ff4c76387d591b9fc7b04a238dcf8bb62639a"
+checksum = "8a0d04d43504c61aa6c7531f1871dd0d418d91130162063b789da00fd7057a5e"
dependencies = [
"android-tzdata",
"iana-time-zone",
@@ -241,16 +218,6 @@ dependencies = [
"windows-targets 0.52.4",
]
-[[package]]
-name = "cipher"
-version = "0.4.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
-dependencies = [
- "crypto-common",
- "inout",
-]
-
[[package]]
name = "clap"
version = "4.5.2"
@@ -373,15 +340,6 @@ version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f"
-[[package]]
-name = "cpufeatures"
-version = "0.2.12"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "53fe5e26ff1b7aef8bca9c6080520cfb8d9333c7568e1829cef191a9723e5504"
-dependencies = [
- "libc",
-]
-
[[package]]
name = "crunchy-cli"
version = "3.3.1"
@@ -432,20 +390,17 @@ dependencies = [
[[package]]
name = "crunchyroll-rs"
-version = "0.8.6"
+version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0f99fcd7627d214fd57cd1d030e8c859a773e19aa29fb0d15017aa84efaba353"
+checksum = "05fcd99a09d001333ab482412473aaa03c84f980d451845b4c43d58986b6eb64"
dependencies = [
- "aes",
"async-trait",
- "cbc",
"chrono",
"crunchyroll-rs-internal",
"dash-mpd",
"futures-util",
"jsonwebtoken",
"lazy_static",
- "m3u8-rs",
"regex",
"reqwest",
"rustls",
@@ -455,30 +410,20 @@ dependencies = [
"smart-default",
"tokio",
"tower-service",
- "webpki-roots 0.26.1",
+ "webpki-roots",
]
[[package]]
name = "crunchyroll-rs-internal"
-version = "0.8.6"
+version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d2dd269b2df82ebbec9e8164e9950c6ad14a01cfcbb85eceeb3f3ef26c7da90c"
+checksum = "d406a27eca9ceab379b601101cd96b0f7bfff34e93487ca58d54118a8b4fbf91"
dependencies = [
"darling",
"quote",
"syn",
]
-[[package]]
-name = "crypto-common"
-version = "0.1.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"
-dependencies = [
- "generic-array",
- "typenum",
-]
-
[[package]]
name = "ctrlc"
version = "3.4.4"
@@ -526,11 +471,11 @@ dependencies = [
[[package]]
name = "dash-mpd"
-version = "0.15.0"
+version = "0.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "18c18f28b58beade78e0f61a846a63a122cb92c5f5ed6bad29d7ad13287c7526"
+checksum = "6cafa2c33eff2857e1a14c38aa9a432aa565a01e77804a541fce7aec3affb8f8"
dependencies = [
- "base64",
+ "base64 0.22.0",
"base64-serde",
"chrono",
"fs-err",
@@ -614,15 +559,6 @@ version = "0.3.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f"
-[[package]]
-name = "encoding_rs"
-version = "0.8.33"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7268b386296a025e474d5140678f75d6de9493ae55a5d709eeb9dd08149945e1"
-dependencies = [
- "cfg-if",
-]
-
[[package]]
name = "equivalent"
version = "1.0.1"
@@ -761,16 +697,6 @@ dependencies = [
"slab",
]
-[[package]]
-name = "generic-array"
-version = "0.14.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
-dependencies = [
- "typenum",
- "version_check",
-]
-
[[package]]
name = "getrandom"
version = "0.2.12"
@@ -790,25 +716,6 @@ version = "0.28.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4271d37baee1b8c7e4b708028c57d816cf9d2434acb33a549475f78c181f6253"
-[[package]]
-name = "h2"
-version = "0.3.24"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bb2c4422095b67ee78da96fbb51a4cc413b3b25883c7717ff7ca1ab31022c9c9"
-dependencies = [
- "bytes",
- "fnv",
- "futures-core",
- "futures-sink",
- "futures-util",
- "http",
- "indexmap 2.2.5",
- "slab",
- "tokio",
- "tokio-util",
- "tracing",
-]
-
[[package]]
name = "hashbrown"
version = "0.12.3"
@@ -841,9 +748,9 @@ checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "http"
-version = "0.2.12"
+version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1"
+checksum = "21b9ddb458710bc376481b842f5da65cdf31522de232c1ca8146abce2a358258"
dependencies = [
"bytes",
"fnv",
@@ -852,12 +759,24 @@ dependencies = [
[[package]]
name = "http-body"
-version = "0.4.6"
+version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2"
+checksum = "1cac85db508abc24a2e48553ba12a996e87244a0395ce011e62b37158745d643"
dependencies = [
"bytes",
"http",
+]
+
+[[package]]
+name = "http-body-util"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0475f8b2ac86659c21b64320d5d653f9efe42acd2a4e560073ec61a155a34f1d"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "http",
+ "http-body",
"pin-project-lite",
]
@@ -867,61 +786,76 @@ version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904"
-[[package]]
-name = "httpdate"
-version = "1.0.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
-
[[package]]
name = "hyper"
-version = "0.14.28"
+version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bf96e135eb83a2a8ddf766e426a841d8ddd7449d5f00d34ea02b41d2f19eef80"
+checksum = "186548d73ac615b32a73aafe38fb4f56c0d340e110e5a200bcadbaf2e199263a"
dependencies = [
"bytes",
"futures-channel",
- "futures-core",
"futures-util",
- "h2",
"http",
"http-body",
"httparse",
- "httpdate",
"itoa",
"pin-project-lite",
- "socket2",
+ "smallvec",
"tokio",
- "tower-service",
- "tracing",
"want",
]
[[package]]
name = "hyper-rustls"
-version = "0.24.2"
+version = "0.26.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ec3efd23720e2049821a693cbc7e65ea87c72f1c58ff2f9522ff332b1491e590"
+checksum = "a0bea761b46ae2b24eb4aef630d8d1c398157b6fc29e6350ecf090a0b70c952c"
dependencies = [
"futures-util",
"http",
"hyper",
+ "hyper-util",
"rustls",
+ "rustls-pki-types",
"tokio",
"tokio-rustls",
+ "tower-service",
]
[[package]]
name = "hyper-tls"
-version = "0.5.0"
+version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d6183ddfa99b85da61a140bea0efc93fdf56ceaa041b37d553518030827f9905"
+checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0"
dependencies = [
"bytes",
+ "http-body-util",
"hyper",
+ "hyper-util",
"native-tls",
"tokio",
"tokio-native-tls",
+ "tower-service",
+]
+
+[[package]]
+name = "hyper-util"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ca38ef113da30126bbff9cd1705f9273e15d45498615d138b0c20279ac7a76aa"
+dependencies = [
+ "bytes",
+ "futures-channel",
+ "futures-util",
+ "http",
+ "http-body",
+ "hyper",
+ "pin-project-lite",
+ "socket2",
+ "tokio",
+ "tower",
+ "tower-service",
+ "tracing",
]
[[package]]
@@ -1008,16 +942,6 @@ dependencies = [
"unicode-width",
]
-[[package]]
-name = "inout"
-version = "0.1.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a0c10553d664a4d0bcff9f4215d0aac67a639cc68ef660840afe309b807bc9f5"
-dependencies = [
- "block-padding",
- "generic-array",
-]
-
[[package]]
name = "instant"
version = "0.1.12"
@@ -1059,11 +983,11 @@ dependencies = [
[[package]]
name = "jsonwebtoken"
-version = "9.2.0"
+version = "9.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5c7ea04a7c5c055c175f189b6dc6ba036fd62306b58c66c9f6389036c503a3f4"
+checksum = "b9ae10193d25051e74945f1ea2d0b42e03cc3b890f7e4cc5faa44997d808193f"
dependencies = [
- "base64",
+ "base64 0.21.7",
"js-sys",
"ring",
"serde",
@@ -1105,16 +1029,6 @@ version = "0.4.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c"
-[[package]]
-name = "m3u8-rs"
-version = "6.0.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f03cd3335fb5f2447755d45cda9c70f76013626a9db44374973791b0926a86c3"
-dependencies = [
- "chrono",
- "nom",
-]
-
[[package]]
name = "memchr"
version = "2.7.1"
@@ -1127,6 +1041,16 @@ version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
+[[package]]
+name = "mime_guess"
+version = "2.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4192263c238a5f0d0c6bfd21f336a313a4ce1c450542449ca191bb657b4642ef"
+dependencies = [
+ "mime",
+ "unicase",
+]
+
[[package]]
name = "minimal-lexical"
version = "0.2.1"
@@ -1303,6 +1227,26 @@ version = "2.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e"
+[[package]]
+name = "pin-project"
+version = "1.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6bf43b791c5b9e34c3d182969b4abb522f9343702850a2e57f460d00d09b4b3"
+dependencies = [
+ "pin-project-internal",
+]
+
+[[package]]
+name = "pin-project-internal"
+version = "1.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
[[package]]
name = "pin-project-lite"
version = "0.2.13"
@@ -1399,9 +1343,9 @@ dependencies = [
[[package]]
name = "regex"
-version = "1.10.3"
+version = "1.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b62dbe01f0b06f9d8dc7d49e05a0785f153b00b2c227856282f671e0318c9b15"
+checksum = "c117dbdfde9c8308975b6a18d71f3f385c89461f7b3fb054288ecf2a2058ba4c"
dependencies = [
"aho-corasick",
"memchr",
@@ -1428,38 +1372,39 @@ checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f"
[[package]]
name = "reqwest"
-version = "0.11.25"
+version = "0.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0eea5a9eb898d3783f17c6407670e3592fd174cb81a10e51d4c37f49450b9946"
+checksum = "2d66674f2b6fb864665eea7a3c1ac4e3dfacd2fda83cf6f935a612e01b0e3338"
dependencies = [
- "base64",
+ "base64 0.21.7",
"bytes",
"cookie",
"cookie_store",
- "encoding_rs",
"futures-core",
"futures-util",
- "h2",
"http",
"http-body",
+ "http-body-util",
"hyper",
"hyper-rustls",
"hyper-tls",
+ "hyper-util",
"ipnet",
"js-sys",
"log",
"mime",
+ "mime_guess",
"native-tls",
"once_cell",
"percent-encoding",
"pin-project-lite",
"rustls",
"rustls-pemfile 1.0.4",
+ "rustls-pki-types",
"serde",
"serde_json",
"serde_urlencoded",
"sync_wrapper",
- "system-configuration",
"tokio",
"tokio-native-tls",
"tokio-rustls",
@@ -1471,7 +1416,7 @@ dependencies = [
"wasm-bindgen-futures",
"wasm-streams",
"web-sys",
- "webpki-roots 0.25.4",
+ "webpki-roots",
"winreg",
]
@@ -1517,14 +1462,16 @@ dependencies = [
[[package]]
name = "rustls"
-version = "0.21.10"
+version = "0.22.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f9d5a6813c0759e4609cd494e8e725babae6a2ca7b62a5536a13daaec6fcb7ba"
+checksum = "99008d7ad0bbbea527ec27bddbc0e432c5b87d8175178cee68d2eec9c4a1813c"
dependencies = [
"log",
"ring",
+ "rustls-pki-types",
"rustls-webpki",
- "sct",
+ "subtle",
+ "zeroize",
]
[[package]]
@@ -1546,7 +1493,7 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c74cae0a4cf6ccbbf5f359f08efdf8ee7e1dc532573bf0db71968cb56b1448c"
dependencies = [
- "base64",
+ "base64 0.21.7",
]
[[package]]
@@ -1555,7 +1502,7 @@ version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f48172685e6ff52a556baa527774f61fcaa884f59daf3375c62a3f1cd2549dab"
dependencies = [
- "base64",
+ "base64 0.21.7",
"rustls-pki-types",
]
@@ -1567,11 +1514,12 @@ checksum = "5ede67b28608b4c60685c7d54122d4400d90f62b40caee7700e700380a390fa8"
[[package]]
name = "rustls-webpki"
-version = "0.101.7"
+version = "0.102.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8b6275d1ee7a1cd780b64aca7726599a1dbc893b1e64144529e55c3c2f745765"
+checksum = "faaa0a62740bedb9b2ef5afa303da42764c012f743917351dc9a237ea1663610"
dependencies = [
"ring",
+ "rustls-pki-types",
"untrusted",
]
@@ -1590,16 +1538,6 @@ dependencies = [
"windows-sys 0.52.0",
]
-[[package]]
-name = "sct"
-version = "0.7.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "da046153aa2352493d6cb7da4b6e5c0c057d8a1d0a9aa8560baffdd945acd414"
-dependencies = [
- "ring",
- "untrusted",
-]
-
[[package]]
name = "security-framework"
version = "2.9.2"
@@ -1687,11 +1625,11 @@ dependencies = [
[[package]]
name = "serde_with"
-version = "3.6.1"
+version = "3.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "15d167997bd841ec232f5b2b8e0e26606df2e7caa4c31b95ea9ca52b200bd270"
+checksum = "ee80b0e361bbf88fd2f6e242ccd19cfda072cb0faa6ae694ecee08199938569a"
dependencies = [
- "base64",
+ "base64 0.21.7",
"chrono",
"hex",
"indexmap 1.9.3",
@@ -1705,9 +1643,9 @@ dependencies = [
[[package]]
name = "serde_with_macros"
-version = "3.6.1"
+version = "3.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "865f9743393e638991566a8b7a479043c2c8da94a33e0a31f18214c9cae0a64d"
+checksum = "6561dc161a9224638a31d876ccdfefbc1df91d3f3a8342eddb35f055d48c7655"
dependencies = [
"darling",
"proc-macro2",
@@ -1736,6 +1674,12 @@ dependencies = [
"autocfg",
]
+[[package]]
+name = "smallvec"
+version = "1.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67"
+
[[package]]
name = "smart-default"
version = "0.7.1"
@@ -1775,6 +1719,12 @@ version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ee073c9e4cd00e28217186dbe12796d692868f432bf2e97ee73bed0c56dfa01"
+[[package]]
+name = "subtle"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "81cdd64d312baedb58e21336b31bc043b77e01cc99033ce76ef539f78e965ebc"
+
[[package]]
name = "syn"
version = "2.0.52"
@@ -1801,27 +1751,6 @@ dependencies = [
"libc",
]
-[[package]]
-name = "system-configuration"
-version = "0.6.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "658bc6ee10a9b4fcf576e9b0819d95ec16f4d2c02d39fd83ac1c8789785c4a42"
-dependencies = [
- "bitflags 2.4.2",
- "core-foundation",
- "system-configuration-sys",
-]
-
-[[package]]
-name = "system-configuration-sys"
-version = "0.6.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4"
-dependencies = [
- "core-foundation-sys",
- "libc",
-]
-
[[package]]
name = "tempfile"
version = "3.10.1"
@@ -1836,18 +1765,18 @@ dependencies = [
[[package]]
name = "thiserror"
-version = "1.0.57"
+version = "1.0.58"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1e45bcbe8ed29775f228095caf2cd67af7a4ccf756ebff23a306bf3e8b47b24b"
+checksum = "03468839009160513471e86a034bb2c5c0e4baae3b43f79ffc55c4a5427b3297"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
-version = "1.0.57"
+version = "1.0.58"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a953cb265bef375dae3de6663da4d3804eee9682ea80d8e2542529b73c531c81"
+checksum = "c61f3ba182994efc43764a46c018c347bc492c79f024e705f46567b418f6d4f7"
dependencies = [
"proc-macro2",
"quote",
@@ -1902,9 +1831,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "tokio"
-version = "1.36.0"
+version = "1.37.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "61285f6515fa018fb2d1e46eb21223fff441ee8db5d0f1435e8ab4f5cdb80931"
+checksum = "1adbebffeca75fcfd058afa480fb6c0b81e165a0323f9c9d39c9697e37c46787"
dependencies = [
"backtrace",
"bytes",
@@ -1940,11 +1869,12 @@ dependencies = [
[[package]]
name = "tokio-rustls"
-version = "0.24.1"
+version = "0.25.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c28327cf380ac148141087fbfb9de9d7bd4e84ab5d2c28fbc911d753de8a7081"
+checksum = "775e0c0f0adb3a2f22a00c4745d728b479985fc15ee7ca6a2608388c5569860f"
dependencies = [
"rustls",
+ "rustls-pki-types",
"tokio",
]
@@ -1974,6 +1904,28 @@ dependencies = [
"tracing",
]
+[[package]]
+name = "tower"
+version = "0.4.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8fa9be0de6cf49e536ce1851f987bd21a43b771b09473c3549a6c853db37c1c"
+dependencies = [
+ "futures-core",
+ "futures-util",
+ "pin-project",
+ "pin-project-lite",
+ "tokio",
+ "tower-layer",
+ "tower-service",
+ "tracing",
+]
+
+[[package]]
+name = "tower-layer"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c20c8dbed6283a09604c3e69b4b7eeb54e298b8a600d4d5ecb5ad39de609f1d0"
+
[[package]]
name = "tower-service"
version = "0.3.2"
@@ -1986,6 +1938,7 @@ version = "0.1.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef"
dependencies = [
+ "log",
"pin-project-lite",
"tracing-attributes",
"tracing-core",
@@ -2018,10 +1971,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
[[package]]
-name = "typenum"
-version = "1.17.0"
+name = "unicase"
+version = "2.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825"
+checksum = "f7d2d4dafb69621809a81864c9c1b864479e1235c0dd4e199924b9742439ed89"
+dependencies = [
+ "version_check",
+]
[[package]]
name = "unicode-bidi"
@@ -2189,12 +2145,6 @@ dependencies = [
"wasm-bindgen",
]
-[[package]]
-name = "webpki-roots"
-version = "0.25.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5f20c57d8d7db6d3b86154206ae5d8fba62dd39573114de97c2cb0578251f8e1"
-
[[package]]
name = "webpki-roots"
version = "0.26.1"
@@ -2387,3 +2337,9 @@ dependencies = [
"linux-raw-sys",
"rustix",
]
+
+[[package]]
+name = "zeroize"
+version = "1.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "525b4ec142c6b68a2d10f01f7bbf6755599ca3f81ea53b8431b7dd348f5fdb2d"
diff --git a/crunchy-cli-core/Cargo.toml b/crunchy-cli-core/Cargo.toml
index 0242606..7617c58 100644
--- a/crunchy-cli-core/Cargo.toml
+++ b/crunchy-cli-core/Cargo.toml
@@ -16,20 +16,20 @@ anyhow = "1.0"
async-speed-limit = "0.4"
clap = { version = "4.5", features = ["derive", "string"] }
chrono = "0.4"
-crunchyroll-rs = { version = "0.8.6", features = ["dash-stream", "experimental-stabilizations", "tower"] }
+crunchyroll-rs = { version = "0.10.0", features = ["experimental-stabilizations", "tower"] }
ctrlc = "3.4"
dialoguer = { version = "0.11", default-features = false }
dirs = "5.0"
derive_setters = "0.1"
futures-util = { version = "0.3", features = ["io"] }
fs2 = "0.4"
-http = "0.2"
+http = "1.1"
indicatif = "0.17"
lazy_static = "1.4"
log = { version = "0.4", features = ["std"] }
num_cpus = "1.16"
regex = "1.10"
-reqwest = { version = "0.11", default-features = false, features = ["socks", "stream"] }
+reqwest = { version = "0.12", default-features = false, features = ["socks", "stream"] }
serde = "1.0"
serde_json = "1.0"
serde_plain = "1.0"
diff --git a/crunchy-cli-core/src/archive/command.rs b/crunchy-cli-core/src/archive/command.rs
index f7bea0e..0dc0b86 100644
--- a/crunchy-cli-core/src/archive/command.rs
+++ b/crunchy-cli-core/src/archive/command.rs
@@ -487,7 +487,7 @@ async fn get_format(
single_format.audio == Locale::ja_JP || stream.subtitles.len() > 1,
)
});
- let cc = stream.closed_captions.get(s).cloned().map(|l| (l, false));
+ let cc = stream.captions.get(s).cloned().map(|l| (l, false));
subtitles
.into_iter()
diff --git a/crunchy-cli-core/src/download/command.rs b/crunchy-cli-core/src/download/command.rs
index 843f5cd..47b29c9 100644
--- a/crunchy-cli-core/src/download/command.rs
+++ b/crunchy-cli-core/src/download/command.rs
@@ -389,7 +389,7 @@ async fn get_format(
.get(subtitle_locale)
.cloned()
// use closed captions as fallback if no actual subtitles are found
- .or_else(|| stream.closed_captions.get(subtitle_locale).cloned())
+ .or_else(|| stream.captions.get(subtitle_locale).cloned())
} else {
None
};
diff --git a/crunchy-cli-core/src/search/format.rs b/crunchy-cli-core/src/search/format.rs
index 156bd95..10eefd8 100644
--- a/crunchy-cli-core/src/search/format.rs
+++ b/crunchy-cli-core/src/search/format.rs
@@ -163,37 +163,15 @@ impl From<&Concert> for FormatConcert {
struct FormatStream {
pub locale: Locale,
pub dash_url: String,
- pub drm_dash_url: String,
- pub hls_url: String,
- pub drm_hls_url: String,
+ pub is_drm: bool,
}
impl From<&Stream> for FormatStream {
fn from(value: &Stream) -> Self {
- let (dash_url, drm_dash_url, hls_url, drm_hls_url) =
- value.variants.get(&Locale::Custom("".to_string())).map_or(
- (
- "".to_string(),
- "".to_string(),
- "".to_string(),
- "".to_string(),
- ),
- |v| {
- (
- v.adaptive_dash.clone().unwrap_or_default().url,
- v.drm_adaptive_dash.clone().unwrap_or_default().url,
- v.adaptive_hls.clone().unwrap_or_default().url,
- v.drm_adaptive_hls.clone().unwrap_or_default().url,
- )
- },
- );
-
Self {
locale: value.audio_locale.clone(),
- dash_url,
- drm_dash_url,
- hls_url,
- drm_hls_url,
+ dash_url: value.url.clone(),
+ is_drm: value.session.uses_stream_limits,
}
}
}
@@ -441,7 +419,7 @@ impl Format {
if !stream_empty {
for (_, episodes) in tree.iter_mut() {
for (episode, streams) in episodes {
- streams.push(episode.stream().await?)
+ streams.push(episode.stream_maybe_without_drm().await?)
}
}
} else {
@@ -510,7 +488,7 @@ impl Format {
}
if !stream_empty {
for (movie, streams) in tree.iter_mut() {
- streams.push(movie.stream().await?)
+ streams.push(movie.stream_maybe_without_drm().await?)
}
} else {
for (_, streams) in tree.iter_mut() {
@@ -548,7 +526,7 @@ impl Format {
let stream_empty = self.check_pattern_count_empty(Scope::Stream);
let music_video = must_match_if_true!(!music_video_empty => media_collection|MediaCollection::MusicVideo(music_video) => music_video.clone()).unwrap_or_default();
- let stream = must_match_if_true!(!stream_empty => media_collection|MediaCollection::MusicVideo(music_video) => music_video.stream().await?).unwrap_or_default();
+ let stream = must_match_if_true!(!stream_empty => media_collection|MediaCollection::MusicVideo(music_video) => music_video.stream_maybe_without_drm().await?).unwrap_or_default();
let music_video_map = self.serializable_to_json_map(FormatMusicVideo::from(&music_video));
let stream_map = self.serializable_to_json_map(FormatStream::from(&stream));
@@ -570,7 +548,7 @@ impl Format {
let stream_empty = self.check_pattern_count_empty(Scope::Stream);
let concert = must_match_if_true!(!concert_empty => media_collection|MediaCollection::Concert(concert) => concert.clone()).unwrap_or_default();
- let stream = must_match_if_true!(!stream_empty => media_collection|MediaCollection::Concert(concert) => concert.stream().await?).unwrap_or_default();
+ let stream = must_match_if_true!(!stream_empty => media_collection|MediaCollection::Concert(concert) => concert.stream_maybe_without_drm().await?).unwrap_or_default();
let concert_map = self.serializable_to_json_map(FormatConcert::from(&concert));
let stream_map = self.serializable_to_json_map(FormatStream::from(&stream));
diff --git a/crunchy-cli-core/src/utils/download.rs b/crunchy-cli-core/src/utils/download.rs
index 736f9e6..8a1fe66 100644
--- a/crunchy-cli-core/src/utils/download.rs
+++ b/crunchy-cli-core/src/utils/download.rs
@@ -4,7 +4,7 @@ use crate::utils::os::{cache_dir, is_special_file, temp_directory, temp_named_pi
use crate::utils::rate_limit::RateLimiterService;
use anyhow::{bail, Result};
use chrono::NaiveTime;
-use crunchyroll_rs::media::{SkipEvents, SkipEventsEvent, Subtitle, VariantData, VariantSegment};
+use crunchyroll_rs::media::{SkipEvents, SkipEventsEvent, StreamData, StreamSegment, Subtitle};
use crunchyroll_rs::Locale;
use indicatif::{ProgressBar, ProgressDrawTarget, ProgressFinish, ProgressStyle};
use log::{debug, warn, LevelFilter};
@@ -117,8 +117,8 @@ struct FFmpegMeta {
}
pub struct DownloadFormat {
- pub video: (VariantData, Locale),
- pub audios: Vec<(VariantData, Locale)>,
+ pub video: (StreamData, Locale),
+ pub audios: Vec<(StreamData, Locale)>,
pub subtitles: Vec<(Subtitle, bool)>,
pub metadata: DownloadFormatMetadata,
}
@@ -671,20 +671,17 @@ impl Downloader {
&self,
dst: &Path,
) -> Result<(Option<(PathBuf, u64)>, Option<(PathBuf, u64)>)> {
- let mut all_variant_data = vec![];
+ let mut all_stream_data = vec![];
for format in &self.formats {
- all_variant_data.push(&format.video.0);
- all_variant_data.extend(format.audios.iter().map(|(a, _)| a))
+ all_stream_data.push(&format.video.0);
+ all_stream_data.extend(format.audios.iter().map(|(a, _)| a))
}
let mut estimated_required_space: u64 = 0;
- for variant_data in all_variant_data {
- // nearly no overhead should be generated with this call(s) as we're using dash as
- // stream provider and generating the dash segments does not need any fetching of
- // additional (http) resources as hls segments would
- let segments = variant_data.segments().await?;
+ for stream_data in all_stream_data {
+ let segments = stream_data.segments();
// sum the length of all streams up
- estimated_required_space += estimate_variant_file_size(variant_data, &segments);
+ estimated_required_space += estimate_variant_file_size(stream_data, &segments);
}
let tmp_stat = fs2::statvfs(temp_directory()).unwrap();
@@ -730,29 +727,21 @@ impl Downloader {
Ok((tmp_required, dst_required))
}
- async fn download_video(
- &self,
- variant_data: &VariantData,
- message: String,
- ) -> Result {
+ async fn download_video(&self, stream_data: &StreamData, message: String) -> Result {
let tempfile = tempfile(".mp4")?;
let (mut file, path) = tempfile.into_parts();
- self.download_segments(&mut file, message, variant_data)
+ self.download_segments(&mut file, message, stream_data)
.await?;
Ok(path)
}
- async fn download_audio(
- &self,
- variant_data: &VariantData,
- message: String,
- ) -> Result {
+ async fn download_audio(&self, stream_data: &StreamData, message: String) -> Result {
let tempfile = tempfile(".m4a")?;
let (mut file, path) = tempfile.into_parts();
- self.download_segments(&mut file, message, variant_data)
+ self.download_segments(&mut file, message, stream_data)
.await?;
Ok(path)
@@ -806,15 +795,15 @@ impl Downloader {
&self,
writer: &mut impl Write,
message: String,
- variant_data: &VariantData,
+ stream_data: &StreamData,
) -> Result<()> {
- let segments = variant_data.segments().await?;
+ let segments = stream_data.segments();
let total_segments = segments.len();
let count = Arc::new(Mutex::new(0));
let progress = if log::max_level() == LevelFilter::Info {
- let estimated_file_size = estimate_variant_file_size(variant_data, &segments);
+ let estimated_file_size = estimate_variant_file_size(stream_data, &segments);
let progress = ProgressBar::new(estimated_file_size)
.with_style(
@@ -832,7 +821,7 @@ impl Downloader {
};
let cpus = self.download_threads;
- let mut segs: Vec> = Vec::with_capacity(cpus);
+ let mut segs: Vec> = Vec::with_capacity(cpus);
for _ in 0..cpus {
segs.push(vec![])
}
@@ -858,7 +847,7 @@ impl Downloader {
let download = || async move {
for (i, segment) in thread_segments.into_iter().enumerate() {
let mut retry_count = 0;
- let mut buf = loop {
+ let buf = loop {
let request = thread_client
.get(&segment.url)
.timeout(Duration::from_secs(60));
@@ -884,11 +873,9 @@ impl Downloader {
retry_count += 1;
};
- buf = VariantSegment::decrypt(&mut buf, segment.key)?.to_vec();
-
let mut c = thread_count.lock().await;
debug!(
- "Downloaded and decrypted segment [{}/{} {:.2}%] {}",
+ "Downloaded segment [{}/{} {:.2}%] {}",
num + (i * cpus) + 1,
total_segments,
((*c + 1) as f64 / total_segments as f64) * 100f64,
@@ -928,7 +915,7 @@ impl Downloader {
if let Some(p) = &progress {
let progress_len = p.length().unwrap();
- let estimated_segment_len = (variant_data.bandwidth / 8)
+ let estimated_segment_len = (stream_data.bandwidth / 8)
* segments.get(pos as usize).unwrap().length.as_secs();
let bytes_len = bytes.len() as u64;
@@ -977,8 +964,8 @@ impl Downloader {
}
}
-fn estimate_variant_file_size(variant_data: &VariantData, segments: &[VariantSegment]) -> u64 {
- (variant_data.bandwidth / 8) * segments.iter().map(|s| s.length.as_secs()).sum::()
+fn estimate_variant_file_size(stream_data: &StreamData, segments: &[StreamSegment]) -> u64 {
+ (stream_data.bandwidth / 8) * segments.iter().map(|s| s.length.as_secs()).sum::()
}
/// Get the length and fps of a video.
diff --git a/crunchy-cli-core/src/utils/format.rs b/crunchy-cli-core/src/utils/format.rs
index 7146a55..df79d64 100644
--- a/crunchy-cli-core/src/utils/format.rs
+++ b/crunchy-cli-core/src/utils/format.rs
@@ -2,9 +2,9 @@ use crate::utils::filter::real_dedup_vec;
use crate::utils::locale::LanguageTagging;
use crate::utils::log::tab_info;
use crate::utils::os::{is_special_file, sanitize};
-use anyhow::Result;
+use anyhow::{bail, Result};
use chrono::{Datelike, Duration};
-use crunchyroll_rs::media::{Resolution, SkipEvents, Stream, Subtitle, VariantData};
+use crunchyroll_rs::media::{Resolution, SkipEvents, Stream, StreamData, Subtitle};
use crunchyroll_rs::{Concert, Episode, Locale, MediaCollection, Movie, MusicVideo};
use log::{debug, info};
use std::cmp::Ordering;
@@ -167,12 +167,17 @@ impl SingleFormat {
pub async fn stream(&self) -> Result {
let stream = match &self.source {
- MediaCollection::Episode(e) => e.stream().await?,
- MediaCollection::Movie(m) => m.stream().await?,
- MediaCollection::MusicVideo(mv) => mv.stream().await?,
- MediaCollection::Concert(c) => c.stream().await?,
+ MediaCollection::Episode(e) => e.stream_maybe_without_drm().await?,
+ MediaCollection::Movie(m) => m.stream_maybe_without_drm().await?,
+ MediaCollection::MusicVideo(mv) => mv.stream_maybe_without_drm().await?,
+ MediaCollection::Concert(c) => c.stream_maybe_without_drm().await?,
_ => unreachable!(),
};
+
+ if stream.session.uses_stream_limits {
+ bail!("Found a stream which probably uses DRM. DRM downloads aren't supported")
+ }
+
Ok(stream)
}
@@ -331,9 +336,7 @@ impl Iterator for SingleFormatCollectionIterator {
type Item = Vec;
fn next(&mut self) -> Option {
- let Some((_, episodes)) = self.0 .0.iter_mut().next() else {
- return None;
- };
+ let (_, episodes) = self.0 .0.iter_mut().next()?;
let value = episodes.pop_first().unwrap().1;
if episodes.is_empty() {
@@ -377,7 +380,7 @@ pub struct Format {
impl Format {
#[allow(clippy::type_complexity)]
pub fn from_single_formats(
- mut single_formats: Vec<(SingleFormat, VariantData, Vec<(Subtitle, bool)>)>,
+ mut single_formats: Vec<(SingleFormat, StreamData, Vec<(Subtitle, bool)>)>,
) -> Self {
let locales: Vec<(Locale, Vec)> = single_formats
.iter()
@@ -397,10 +400,10 @@ impl Format {
title: first_format.title,
description: first_format.description,
locales,
- resolution: first_stream.resolution.clone(),
- width: first_stream.resolution.width,
- height: first_stream.resolution.height,
- fps: first_stream.fps,
+ resolution: first_stream.resolution().unwrap(),
+ width: first_stream.resolution().unwrap().width,
+ height: first_stream.resolution().unwrap().height,
+ fps: first_stream.fps().unwrap(),
release_year: first_format.release_year,
release_month: first_format.release_month,
release_day: first_format.release_day,
diff --git a/crunchy-cli-core/src/utils/video.rs b/crunchy-cli-core/src/utils/video.rs
index 0ae4ba4..7f7d73e 100644
--- a/crunchy-cli-core/src/utils/video.rs
+++ b/crunchy-cli-core/src/utils/video.rs
@@ -1,17 +1,17 @@
use anyhow::{bail, Result};
-use crunchyroll_rs::media::{Resolution, Stream, VariantData};
+use crunchyroll_rs::media::{Resolution, Stream, StreamData};
use crunchyroll_rs::Locale;
pub async fn variant_data_from_stream(
stream: &Stream,
resolution: &Resolution,
subtitle: Option,
-) -> Result> {
+) -> Result > {
// sometimes Crunchyroll marks episodes without real subtitles that they have subtitles and
// reports that only hardsub episode are existing. the following lines are trying to prevent
// potential errors which might get caused by this incorrect reporting
// (https://github.com/crunchy-labs/crunchy-cli/issues/231)
- let mut hardsub_locales = stream.streaming_hardsub_locales();
+ let mut hardsub_locales: Vec = stream.hard_subs.keys().cloned().collect();
let (hardsub_locale, mut contains_hardsub) = if !hardsub_locales
.contains(&Locale::Custom("".to_string()))
&& !hardsub_locales.contains(&Locale::Custom(":".to_string()))
@@ -29,39 +29,29 @@ pub async fn variant_data_from_stream(
(subtitle, hardsubs_requested)
};
- let mut streaming_data = match stream.dash_streaming_data(hardsub_locale).await {
+ let (mut videos, mut audios) = match stream.stream_data(hardsub_locale).await {
Ok(data) => data,
Err(e) => {
// the error variant is only `crunchyroll_rs::error::Error::Input` when the requested
// hardsub is not available
if let crunchyroll_rs::error::Error::Input { .. } = e {
contains_hardsub = false;
- stream.dash_streaming_data(None).await?
+ stream.stream_data(None).await?
} else {
bail!(e)
}
}
- };
- streaming_data
- .0
- .sort_by(|a, b| a.bandwidth.cmp(&b.bandwidth).reverse());
- streaming_data
- .1
- .sort_by(|a, b| a.bandwidth.cmp(&b.bandwidth).reverse());
+ }
+ .unwrap();
+ videos.sort_by(|a, b| a.bandwidth.cmp(&b.bandwidth).reverse());
+ audios.sort_by(|a, b| a.bandwidth.cmp(&b.bandwidth).reverse());
let video_variant = match resolution.height {
- u64::MAX => Some(streaming_data.0.into_iter().next().unwrap()),
- u64::MIN => Some(streaming_data.0.into_iter().last().unwrap()),
- _ => streaming_data
- .0
+ u64::MAX => Some(videos.into_iter().next().unwrap()),
+ u64::MIN => Some(videos.into_iter().last().unwrap()),
+ _ => videos
.into_iter()
- .find(|v| resolution.height == v.resolution.height),
+ .find(|v| resolution.height == v.resolution().unwrap().height),
};
- Ok(video_variant.map(|v| {
- (
- v,
- streaming_data.1.first().unwrap().clone(),
- contains_hardsub,
- )
- }))
+ Ok(video_variant.map(|v| (v, audios.first().unwrap().clone(), contains_hardsub)))
}
From f16cd25ea4a40f48b1744c67de09549756ec8505 Mon Sep 17 00:00:00 2001
From: Amelia Frost
Date: Wed, 3 Apr 2024 16:09:33 +0200
Subject: [PATCH 04/82] Fix for some chapters being sent by CR as floats (#351)
* Fix for some chapters being sent by CR as floats.
See: https://github.com/crunchy-labs/crunchyroll-rs/commit/3f3a80f7f7205e8ecb67e15fcf82b988eb88d9b2
* Compile fix for error[E0277]: cannot multiply `f32` by `u32`
* Format
Co-authored-by: bytedream
---
crunchy-cli-core/src/utils/download.rs | 42 ++++++++++++++------------
1 file changed, 23 insertions(+), 19 deletions(-)
diff --git a/crunchy-cli-core/src/utils/download.rs b/crunchy-cli-core/src/utils/download.rs
index 8a1fe66..d7904f3 100644
--- a/crunchy-cli-core/src/utils/download.rs
+++ b/crunchy-cli-core/src/utils/download.rs
@@ -1214,41 +1214,45 @@ fn write_ffmpeg_chapters(
) -> Result<()> {
let video_len = video_len
.signed_duration_since(NaiveTime::MIN)
- .num_seconds() as u32;
- events.sort_by(|(_, event_a), (_, event_b)| event_a.start.cmp(&event_b.start));
+ .num_milliseconds() as f32
+ / 1000.0;
+ events.sort_by(|(_, event_a), (_, event_b)| event_a.start.total_cmp(&event_b.start));
writeln!(file, ";FFMETADATA1")?;
- let mut last_end_time = 0;
+ let mut last_end_time = 0.0;
for (name, event) in events {
- // include an extra 'Episode' chapter if the start of the current chapter is more than 10
- // seconds later than the end of the last chapter.
- // this is done before writing the actual chapter of this loop to keep the chapter
- // chronologically in order
- if event.start as i32 - last_end_time as i32 > 10 {
+ /*
+ - Convert from seconds to milliseconds for the correct timescale
+ - Include an extra 'Episode' chapter if the start of the current chapter is more than 10
+ seconds later than the end of the last chapter.
+ This is done before writing the actual chapter of this loop to keep the chapter
+ chronologically in order
+ */
+ if event.start - last_end_time > 10.0 {
writeln!(file, "[CHAPTER]")?;
- writeln!(file, "TIMEBASE=1/1")?;
- writeln!(file, "START={}", last_end_time)?;
- writeln!(file, "END={}", event.start)?;
+ writeln!(file, "TIMEBASE=1/1000")?;
+ writeln!(file, "START={}", (last_end_time * 1000.0) as u32)?;
+ writeln!(file, "END={}", (event.start * 1000.0) as u32)?;
writeln!(file, "title=Episode")?;
}
writeln!(file, "[CHAPTER]")?;
- writeln!(file, "TIMEBASE=1/1")?;
- writeln!(file, "START={}", event.start)?;
- writeln!(file, "END={}", event.end)?;
+ writeln!(file, "TIMEBASE=1/1000")?;
+ writeln!(file, "START={}", (event.start * 1000.0) as u32)?;
+ writeln!(file, "END={}", (event.end * 1000.0) as u32)?;
writeln!(file, "title={}", name)?;
last_end_time = event.end;
}
- // only add a traling chapter if the gab between the end of the last chapter and the total video
+ // only add a trailing chapter if the gap between the end of the last chapter and the total video
// length is greater than 10 seconds
- if video_len as i32 - last_end_time as i32 > 10 {
+ if video_len - last_end_time > 10.0 {
writeln!(file, "[CHAPTER]")?;
- writeln!(file, "TIMEBASE=1/1")?;
- writeln!(file, "START={}", last_end_time)?;
- writeln!(file, "END={}", video_len)?;
+ writeln!(file, "TIMEBASE=1/1000")?;
+ writeln!(file, "START={}", (last_end_time * 1000.0) as u32)?;
+ writeln!(file, "END={}", (video_len * 1000.0) as u32)?;
writeln!(file, "title=Episode")?;
}
From 111e461b302544f027f31d8b2453a268a7ab0013 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Wed, 3 Apr 2024 16:20:24 +0200
Subject: [PATCH 05/82] Update dependencies and version
---
Cargo.lock | 134 +++++++++++++++++-------------------
Cargo.toml | 4 +-
crunchy-cli-core/Cargo.toml | 4 +-
3 files changed, 66 insertions(+), 76 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index b7617b1..52bba41 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -19,9 +19,9 @@ checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe"
[[package]]
name = "aho-corasick"
-version = "1.1.2"
+version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b2969dcb958b36655471fc61f7e416fa76033bdd4bfed0678d8fee1e2d07a1f0"
+checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"
dependencies = [
"memchr",
]
@@ -91,9 +91,9 @@ dependencies = [
[[package]]
name = "anyhow"
-version = "1.0.80"
+version = "1.0.81"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5ad32ce52e4161730f7098c077cd2ed6229b5804ccf99e5366be1ab72a98b4e1"
+checksum = "0952808a6c2afd1aa8947271f3a60f1a6763c7b912d210184c5149b5cf147247"
[[package]]
name = "async-speed-limit"
@@ -109,9 +109,9 @@ dependencies = [
[[package]]
name = "async-trait"
-version = "0.1.77"
+version = "0.1.79"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c980ee35e870bd1a4d2c8294d4c04d0499e67bca1e4b5cefcc693c2fa00caea9"
+checksum = "a507401cad91ec6a857ed5513a2073c82a9b9048762b885bb98655b306964681"
dependencies = [
"proc-macro2",
"quote",
@@ -120,15 +120,15 @@ dependencies = [
[[package]]
name = "autocfg"
-version = "1.1.0"
+version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
+checksum = "f1fdabc7756949593fe60f30ec81974b613357de856987752631dea1e3394c80"
[[package]]
name = "backtrace"
-version = "0.3.69"
+version = "0.3.71"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2089b7e3f35b9dd2d0ed921ead4f6d318c27680d4a5bd167b3ee120edb105837"
+checksum = "26b05800d2e817c8b3b4b54abd461726265fa9789ae34330622f2db9ee696f9d"
dependencies = [
"addr2line",
"cc",
@@ -169,9 +169,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "bitflags"
-version = "2.4.2"
+version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ed570934406eb16438a4e976b1b4500774099c13b8cb96eec99f620f05090ddf"
+checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1"
[[package]]
name = "bumpalo"
@@ -181,9 +181,9 @@ checksum = "7ff69b9dd49fd426c69a0db9fc04dd934cdb6645ff000864d98f7e2af8830eaa"
[[package]]
name = "bytes"
-version = "1.5.0"
+version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a2bd12c1caf447e69cd4528f47f94d203fd2582878ecb9e9465484c4148a8223"
+checksum = "514de17de45fdb8dc022b1a7975556c53c86f9f0aa5f534b98977b171857c2c9"
[[package]]
name = "cc"
@@ -220,9 +220,9 @@ dependencies = [
[[package]]
name = "clap"
-version = "4.5.2"
+version = "4.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b230ab84b0ffdf890d5a10abdbc8b83ae1c4918275daea1ab8801f71536b2651"
+checksum = "90bc066a67923782aa8515dbaea16946c5bcc5addbd668bb80af688e53e548a0"
dependencies = [
"clap_builder",
"clap_derive",
@@ -237,7 +237,7 @@ dependencies = [
"anstream",
"anstyle",
"clap_lex",
- "strsim 0.11.0",
+ "strsim 0.11.1",
]
[[package]]
@@ -251,9 +251,9 @@ dependencies = [
[[package]]
name = "clap_derive"
-version = "4.5.0"
+version = "4.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "307bc0538d5f0f83b8248db3087aa92fe504e4691294d0c96c0eabc33f47ba47"
+checksum = "528131438037fd55894f62d6e9f068b8f45ac57ffa77517819645d10aed04f64"
dependencies = [
"heck",
"proc-macro2",
@@ -342,7 +342,7 @@ checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f"
[[package]]
name = "crunchy-cli"
-version = "3.3.1"
+version = "3.3.2"
dependencies = [
"chrono",
"clap",
@@ -355,7 +355,7 @@ dependencies = [
[[package]]
name = "crunchy-cli-core"
-version = "3.3.1"
+version = "3.3.2"
dependencies = [
"anyhow",
"async-speed-limit",
@@ -577,9 +577,9 @@ dependencies = [
[[package]]
name = "fastrand"
-version = "2.0.1"
+version = "2.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5"
+checksum = "658bd65b1cf4c852a3cc96f18a8ce7b5640f6b703f905c7d74532294c2a63984"
[[package]]
name = "fnv"
@@ -730,9 +730,9 @@ checksum = "290f1a1d9242c78d09ce40a5e87e7554ee637af1351968159f4952f028f75604"
[[package]]
name = "heck"
-version = "0.4.1"
+version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "hermit-abi"
@@ -920,9 +920,9 @@ dependencies = [
[[package]]
name = "indexmap"
-version = "2.2.5"
+version = "2.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7b0b929d511467233429c45a44ac1dcaa21ba0f5ba11e4879e6ed28ddb4f9df4"
+checksum = "168fb715dda47215e360912c096649d23d58bf392ac62f73919e831745e40f26"
dependencies = [
"equivalent",
"hashbrown 0.14.3",
@@ -968,9 +968,9 @@ dependencies = [
[[package]]
name = "itoa"
-version = "1.0.10"
+version = "1.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c"
+checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b"
[[package]]
name = "js-sys"
@@ -1008,13 +1008,12 @@ checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd"
[[package]]
name = "libredox"
-version = "0.0.1"
+version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "85c833ca1e66078851dba29046874e38f08b2c883700aa29a03ddd3b23814ee8"
+checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d"
dependencies = [
- "bitflags 2.4.2",
+ "bitflags 2.5.0",
"libc",
- "redox_syscall",
]
[[package]]
@@ -1031,9 +1030,9 @@ checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c"
[[package]]
name = "memchr"
-version = "2.7.1"
+version = "2.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "523dc4f511e55ab87b694dc30d0f820d60906ef06413f93d4d7a1385599cc149"
+checksum = "6c8640c5d730cb13ebd907d8d04b52f55ac9a2eec55b440c8892f40d56c76c1d"
[[package]]
name = "mime"
@@ -1099,7 +1098,7 @@ version = "0.28.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ab2156c4fce2f8df6c499cc1c763e4394b7482525bf2a9701c9d79d215f519e4"
dependencies = [
- "bitflags 2.4.2",
+ "bitflags 2.5.0",
"cfg-if",
"cfg_aliases",
"libc",
@@ -1167,7 +1166,7 @@ version = "0.10.64"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95a0481286a310808298130d22dd1fef0fa571e05a8f44ec801801e84b216b1f"
dependencies = [
- "bitflags 2.4.2",
+ "bitflags 2.5.0",
"cfg-if",
"foreign-types",
"libc",
@@ -1204,9 +1203,9 @@ dependencies = [
[[package]]
name = "openssl-sys"
-version = "0.9.101"
+version = "0.9.102"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dda2b0f344e78efc2facf7d195d098df0dd72151b26ab98da807afc26c198dff"
+checksum = "c597637d56fbc83893a35eb0dd04b2b8e7a50c91e64e9493e398b5df4fb45fa2"
dependencies = [
"cc",
"libc",
@@ -1249,9 +1248,9 @@ dependencies = [
[[package]]
name = "pin-project-lite"
-version = "0.2.13"
+version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8afb450f006bf6385ca15ef45d71d2288452bc3683ce2e2cacc0d18e4be60b58"
+checksum = "bda66fc9667c18cb2758a2ac84d1167245054bcf85d5d1aaa6923f45801bdd02"
[[package]]
name = "pin-utils"
@@ -1279,9 +1278,9 @@ checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
[[package]]
name = "proc-macro2"
-version = "1.0.78"
+version = "1.0.79"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e2422ad645d89c99f8f3e6b88a9fdeca7fabeac836b1002371c4367c8f984aae"
+checksum = "e835ff2298f5721608eb1a980ecaee1aef2c132bf95ecc026a11b7bf3c01c02e"
dependencies = [
"unicode-ident",
]
@@ -1321,20 +1320,11 @@ dependencies = [
"proc-macro2",
]
-[[package]]
-name = "redox_syscall"
-version = "0.4.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa"
-dependencies = [
- "bitflags 1.3.2",
-]
-
[[package]]
name = "redox_users"
-version = "0.4.4"
+version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a18479200779601e498ada4e8c1e1f50e3ee19deb0259c25825a98b5603b2cb4"
+checksum = "bd283d9651eeda4b2a83a43c1c91b266c40fd76ecd39a50a8c630ae69dc72891"
dependencies = [
"getrandom",
"libredox",
@@ -1366,9 +1356,9 @@ dependencies = [
[[package]]
name = "regex-syntax"
-version = "0.8.2"
+version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f"
+checksum = "adad44e29e4c806119491a7f06f03de4d1af22c3a680dd47f1e6e179439d1f56"
[[package]]
name = "reqwest"
@@ -1449,11 +1439,11 @@ checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76"
[[package]]
name = "rustix"
-version = "0.38.31"
+version = "0.38.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6ea3e1a662af26cd7a3ba09c0297a31af215563ecf42817c98df621387f4e949"
+checksum = "65e04861e65f21776e67888bfbea442b3642beaa0138fdb1dd7a84a52dffdb89"
dependencies = [
- "bitflags 2.4.2",
+ "bitflags 2.5.0",
"errno",
"libc",
"linux-raw-sys",
@@ -1508,9 +1498,9 @@ dependencies = [
[[package]]
name = "rustls-pki-types"
-version = "1.3.1"
+version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5ede67b28608b4c60685c7d54122d4400d90f62b40caee7700e700380a390fa8"
+checksum = "ecd36cc4259e3e4514335c4a138c6b43171a8d61d8f5c9348f9fc7529416f247"
[[package]]
name = "rustls-webpki"
@@ -1540,9 +1530,9 @@ dependencies = [
[[package]]
name = "security-framework"
-version = "2.9.2"
+version = "2.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "05b64fb303737d99b81884b2c63433e9ae28abebe5eb5045dcdd175dc2ecf4de"
+checksum = "770452e37cad93e0a50d5abc3990d2bc351c36d0328f86cefec2f2fb206eaef6"
dependencies = [
"bitflags 1.3.2",
"core-foundation",
@@ -1553,9 +1543,9 @@ dependencies = [
[[package]]
name = "security-framework-sys"
-version = "2.9.1"
+version = "2.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e932934257d3b408ed8f30db49d85ea163bfe74961f017f405b025af298f0c7a"
+checksum = "41f3cc463c0ef97e11c3461a9d3787412d30e8e7eb907c79180c4a57bf7c04ef"
dependencies = [
"core-foundation-sys",
"libc",
@@ -1583,9 +1573,9 @@ dependencies = [
[[package]]
name = "serde_json"
-version = "1.0.114"
+version = "1.0.115"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c5f09b1bd632ef549eaa9f60a1f8de742bdbc698e6cee2095fc84dde5f549ae0"
+checksum = "12dc5c46daa8e9fdf4f5e71b6cf9a53f2487da0e86e55808e2d35539666497dd"
dependencies = [
"itoa",
"ryu",
@@ -1633,7 +1623,7 @@ dependencies = [
"chrono",
"hex",
"indexmap 1.9.3",
- "indexmap 2.2.5",
+ "indexmap 2.2.6",
"serde",
"serde_derive",
"serde_json",
@@ -1715,9 +1705,9 @@ checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
[[package]]
name = "strsim"
-version = "0.11.0"
+version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5ee073c9e4cd00e28217186dbe12796d692868f432bf2e97ee73bed0c56dfa01"
+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "subtle"
@@ -1727,9 +1717,9 @@ checksum = "81cdd64d312baedb58e21336b31bc043b77e01cc99033ce76ef539f78e965ebc"
[[package]]
name = "syn"
-version = "2.0.52"
+version = "2.0.58"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b699d15b36d1f02c3e7c69f8ffef53de37aefae075d8488d4ba1a7788d574a07"
+checksum = "44cfb93f38070beee36b3fef7d4f5a16f27751d94b187b666a5cc5e9b0d30687"
dependencies = [
"proc-macro2",
"quote",
diff --git a/Cargo.toml b/Cargo.toml
index 681fe73..159b3cd 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli"
authors = ["Crunchy Labs Maintainers"]
-version = "3.3.1"
+version = "3.3.2"
edition = "2021"
license = "MIT"
@@ -14,7 +14,7 @@ openssl-tls = ["dep:native-tls-crate", "native-tls-crate/openssl", "crunchy-cli-
openssl-tls-static = ["dep:native-tls-crate", "native-tls-crate/openssl", "crunchy-cli-core/openssl-tls-static"]
[dependencies]
-tokio = { version = "1.36", features = ["macros", "rt-multi-thread", "time"], default-features = false }
+tokio = { version = "1.37", features = ["macros", "rt-multi-thread", "time"], default-features = false }
native-tls-crate = { package = "native-tls", version = "0.2.11", optional = true }
diff --git a/crunchy-cli-core/Cargo.toml b/crunchy-cli-core/Cargo.toml
index 7617c58..f3e8b5f 100644
--- a/crunchy-cli-core/Cargo.toml
+++ b/crunchy-cli-core/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli-core"
authors = ["Crunchy Labs Maintainers"]
-version = "3.3.1"
+version = "3.3.2"
edition = "2021"
license = "MIT"
@@ -36,7 +36,7 @@ serde_plain = "1.0"
shlex = "1.3"
sys-locale = "0.3"
tempfile = "3.10"
-tokio = { version = "1.36", features = ["io-util", "macros", "net", "rt-multi-thread", "time"] }
+tokio = { version = "1.37", features = ["io-util", "macros", "net", "rt-multi-thread", "time"] }
tokio-util = "0.7"
tower-service = "0.3"
rustls-native-certs = { version = "0.7", optional = true }
From c0f334684679665a06cb6dc247017f63d52e2090 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Wed, 3 Apr 2024 16:46:49 +0200
Subject: [PATCH 06/82] Update README.md
---
README.md | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/README.md b/README.md
index 7636dc1..5463e30 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,6 @@
-# This project has been sunset as Crunchyroll moved to a DRM-only system. See [#362](https://github.com/crunchy-labs/crunchy-cli/issues/362).
+> ~~This project has been sunset as Crunchyroll moved to a DRM-only system. See [#362](https://github.com/crunchy-labs/crunchy-cli/issues/362).~~
+>
+> Well there is one endpoint which still has DRM-free streams, I guess I still have a bit time until (finally) everything is DRM-only.
# crunchy-cli
From af8ab248261c7d3b56930363fa6956ed01a8be9d Mon Sep 17 00:00:00 2001
From: bytedream
Date: Wed, 3 Apr 2024 17:13:44 +0200
Subject: [PATCH 07/82] Update search command url help
---
crunchy-cli-core/src/search/command.rs | 4 +---
1 file changed, 1 insertion(+), 3 deletions(-)
diff --git a/crunchy-cli-core/src/search/command.rs b/crunchy-cli-core/src/search/command.rs
index 226e242..f683e24 100644
--- a/crunchy-cli-core/src/search/command.rs
+++ b/crunchy-cli-core/src/search/command.rs
@@ -88,9 +88,7 @@ pub struct Search {
///
/// stream.locale → Stream locale/language
/// stream.dash_url → Stream url in DASH format
- /// stream.drm_dash_url → Stream url in DRM protected DASH format
- /// stream.hls_url → Stream url in HLS format
- /// stream.drm_hls_url → Stream url in DRM protected HLS format
+ /// stream.is_drm → If `stream.is_drm` is DRM encrypted
///
/// subtitle.locale → Subtitle locale/language
/// subtitle.url → Url to the subtitle
From 8c1868f2fd9fb6348a09313f8cdf6f41239d58b3 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Wed, 3 Apr 2024 17:14:07 +0200
Subject: [PATCH 08/82] Update dependencies and version
---
Cargo.lock | 65 +++++++++++++++++++++++++++++++++----
Cargo.toml | 2 +-
crunchy-cli-core/Cargo.toml | 6 ++--
3 files changed, 63 insertions(+), 10 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index 52bba41..54d364c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -342,7 +342,7 @@ checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f"
[[package]]
name = "crunchy-cli"
-version = "3.3.2"
+version = "3.3.3"
dependencies = [
"chrono",
"clap",
@@ -355,7 +355,7 @@ dependencies = [
[[package]]
name = "crunchy-cli-core"
-version = "3.3.2"
+version = "3.3.3"
dependencies = [
"anyhow",
"async-speed-limit",
@@ -390,9 +390,9 @@ dependencies = [
[[package]]
name = "crunchyroll-rs"
-version = "0.10.0"
+version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "05fcd99a09d001333ab482412473aaa03c84f980d451845b4c43d58986b6eb64"
+checksum = "b9dba87354272cbe34eea8c27cab75b5104d7334aa6374db4807bd145f77a5ac"
dependencies = [
"async-trait",
"chrono",
@@ -415,9 +415,9 @@ dependencies = [
[[package]]
name = "crunchyroll-rs-internal"
-version = "0.10.0"
+version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d406a27eca9ceab379b601101cd96b0f7bfff34e93487ca58d54118a8b4fbf91"
+checksum = "7f7727afdfa43dcc8981a83c299a2e416262053402dc0586b15bfe0488f05e23"
dependencies = [
"darling",
"quote",
@@ -559,6 +559,15 @@ version = "0.3.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f"
+[[package]]
+name = "encoding_rs"
+version = "0.8.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7268b386296a025e474d5140678f75d6de9493ae55a5d709eeb9dd08149945e1"
+dependencies = [
+ "cfg-if",
+]
+
[[package]]
name = "equivalent"
version = "1.0.1"
@@ -716,6 +725,25 @@ version = "0.28.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4271d37baee1b8c7e4b708028c57d816cf9d2434acb33a549475f78c181f6253"
+[[package]]
+name = "h2"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "51ee2dd2e4f378392eeff5d51618cd9a63166a2513846bbc55f21cfacd9199d4"
+dependencies = [
+ "bytes",
+ "fnv",
+ "futures-core",
+ "futures-sink",
+ "futures-util",
+ "http",
+ "indexmap 2.2.6",
+ "slab",
+ "tokio",
+ "tokio-util",
+ "tracing",
+]
+
[[package]]
name = "hashbrown"
version = "0.12.3"
@@ -795,6 +823,7 @@ dependencies = [
"bytes",
"futures-channel",
"futures-util",
+ "h2",
"http",
"http-body",
"httparse",
@@ -1370,8 +1399,10 @@ dependencies = [
"bytes",
"cookie",
"cookie_store",
+ "encoding_rs",
"futures-core",
"futures-util",
+ "h2",
"http",
"http-body",
"http-body-util",
@@ -1395,6 +1426,7 @@ dependencies = [
"serde_json",
"serde_urlencoded",
"sync_wrapper",
+ "system-configuration",
"tokio",
"tokio-native-tls",
"tokio-rustls",
@@ -1741,6 +1773,27 @@ dependencies = [
"libc",
]
+[[package]]
+name = "system-configuration"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ba3a3adc5c275d719af8cb4272ea1c4a6d668a777f37e115f6d11ddbc1c8e0e7"
+dependencies = [
+ "bitflags 1.3.2",
+ "core-foundation",
+ "system-configuration-sys",
+]
+
+[[package]]
+name = "system-configuration-sys"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a75fb188eb626b924683e3b95e3a48e63551fcfb51949de2f06a9d91dbee93c9"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
[[package]]
name = "tempfile"
version = "3.10.1"
diff --git a/Cargo.toml b/Cargo.toml
index 159b3cd..3a86a3d 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli"
authors = ["Crunchy Labs Maintainers"]
-version = "3.3.2"
+version = "3.3.3"
edition = "2021"
license = "MIT"
diff --git a/crunchy-cli-core/Cargo.toml b/crunchy-cli-core/Cargo.toml
index f3e8b5f..9d175d8 100644
--- a/crunchy-cli-core/Cargo.toml
+++ b/crunchy-cli-core/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli-core"
authors = ["Crunchy Labs Maintainers"]
-version = "3.3.2"
+version = "3.3.3"
edition = "2021"
license = "MIT"
@@ -16,7 +16,7 @@ anyhow = "1.0"
async-speed-limit = "0.4"
clap = { version = "4.5", features = ["derive", "string"] }
chrono = "0.4"
-crunchyroll-rs = { version = "0.10.0", features = ["experimental-stabilizations", "tower"] }
+crunchyroll-rs = { version = "0.10.1", features = ["experimental-stabilizations", "tower"] }
ctrlc = "3.4"
dialoguer = { version = "0.11", default-features = false }
dirs = "5.0"
@@ -29,7 +29,7 @@ lazy_static = "1.4"
log = { version = "0.4", features = ["std"] }
num_cpus = "1.16"
regex = "1.10"
-reqwest = { version = "0.12", default-features = false, features = ["socks", "stream"] }
+reqwest = { version = "0.12", features = ["socks", "stream"] }
serde = "1.0"
serde_json = "1.0"
serde_plain = "1.0"
From 6b6d24a575ab4a4e873b93d11127d201f0efebb8 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Thu, 4 Apr 2024 21:01:34 +0200
Subject: [PATCH 09/82] Update dependencies and version
---
Cargo.lock | 16 ++++++++--------
Cargo.toml | 2 +-
crunchy-cli-core/Cargo.toml | 4 ++--
3 files changed, 11 insertions(+), 11 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index 54d364c..f584cee 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -342,7 +342,7 @@ checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f"
[[package]]
name = "crunchy-cli"
-version = "3.3.3"
+version = "3.3.4"
dependencies = [
"chrono",
"clap",
@@ -355,7 +355,7 @@ dependencies = [
[[package]]
name = "crunchy-cli-core"
-version = "3.3.3"
+version = "3.3.4"
dependencies = [
"anyhow",
"async-speed-limit",
@@ -390,9 +390,9 @@ dependencies = [
[[package]]
name = "crunchyroll-rs"
-version = "0.10.1"
+version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b9dba87354272cbe34eea8c27cab75b5104d7334aa6374db4807bd145f77a5ac"
+checksum = "0010e5dded0388e3a1e69105c2e65637d092eff049ba10f132f216c8e26a2473"
dependencies = [
"async-trait",
"chrono",
@@ -415,9 +415,9 @@ dependencies = [
[[package]]
name = "crunchyroll-rs-internal"
-version = "0.10.1"
+version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7f7727afdfa43dcc8981a83c299a2e416262053402dc0586b15bfe0488f05e23"
+checksum = "7e5226275711b3d1dc6afdc5e2241a45bb5d4dc1a813902265d628ccfe1ab67d"
dependencies = [
"darling",
"quote",
@@ -727,9 +727,9 @@ checksum = "4271d37baee1b8c7e4b708028c57d816cf9d2434acb33a549475f78c181f6253"
[[package]]
name = "h2"
-version = "0.4.3"
+version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "51ee2dd2e4f378392eeff5d51618cd9a63166a2513846bbc55f21cfacd9199d4"
+checksum = "816ec7294445779408f36fe57bc5b7fc1cf59664059096c65f905c1c61f58069"
dependencies = [
"bytes",
"fnv",
diff --git a/Cargo.toml b/Cargo.toml
index 3a86a3d..221db3f 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli"
authors = ["Crunchy Labs Maintainers"]
-version = "3.3.3"
+version = "3.3.4"
edition = "2021"
license = "MIT"
diff --git a/crunchy-cli-core/Cargo.toml b/crunchy-cli-core/Cargo.toml
index 9d175d8..0bbf493 100644
--- a/crunchy-cli-core/Cargo.toml
+++ b/crunchy-cli-core/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli-core"
authors = ["Crunchy Labs Maintainers"]
-version = "3.3.3"
+version = "3.3.4"
edition = "2021"
license = "MIT"
@@ -16,7 +16,7 @@ anyhow = "1.0"
async-speed-limit = "0.4"
clap = { version = "4.5", features = ["derive", "string"] }
chrono = "0.4"
-crunchyroll-rs = { version = "0.10.1", features = ["experimental-stabilizations", "tower"] }
+crunchyroll-rs = { version = "0.10.2", features = ["experimental-stabilizations", "tower"] }
ctrlc = "3.4"
dialoguer = { version = "0.11", default-features = false }
dirs = "5.0"
From c40ea8b1320eda6b2243147ec345161d7b81b53a Mon Sep 17 00:00:00 2001
From: bytedream
Date: Fri, 5 Apr 2024 22:31:39 +0200
Subject: [PATCH 10/82] Update dependencies and version
---
Cargo.lock | 35 +++++++++++++----------------------
Cargo.toml | 2 +-
crunchy-cli-core/Cargo.toml | 4 ++--
3 files changed, 16 insertions(+), 25 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index f584cee..7d0b7e1 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -342,7 +342,7 @@ checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f"
[[package]]
name = "crunchy-cli"
-version = "3.3.4"
+version = "3.3.5"
dependencies = [
"chrono",
"clap",
@@ -355,7 +355,7 @@ dependencies = [
[[package]]
name = "crunchy-cli-core"
-version = "3.3.4"
+version = "3.3.5"
dependencies = [
"anyhow",
"async-speed-limit",
@@ -390,9 +390,9 @@ dependencies = [
[[package]]
name = "crunchyroll-rs"
-version = "0.10.2"
+version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0010e5dded0388e3a1e69105c2e65637d092eff049ba10f132f216c8e26a2473"
+checksum = "2eae6c95ec38118d02ef2ca738e245d8afc404f05e502051013dc37e0295bb32"
dependencies = [
"async-trait",
"chrono",
@@ -415,9 +415,9 @@ dependencies = [
[[package]]
name = "crunchyroll-rs-internal"
-version = "0.10.2"
+version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7e5226275711b3d1dc6afdc5e2241a45bb5d4dc1a813902265d628ccfe1ab67d"
+checksum = "2f589713700c948db9a976d3f83816ab12efebdf759044a7bb963dad62000c12"
dependencies = [
"darling",
"quote",
@@ -1391,11 +1391,11 @@ checksum = "adad44e29e4c806119491a7f06f03de4d1af22c3a680dd47f1e6e179439d1f56"
[[package]]
name = "reqwest"
-version = "0.12.2"
+version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2d66674f2b6fb864665eea7a3c1ac4e3dfacd2fda83cf6f935a612e01b0e3338"
+checksum = "3e6cc1e89e689536eb5aeede61520e874df5a4707df811cd5da4aa5fbb2aae19"
dependencies = [
- "base64 0.21.7",
+ "base64 0.22.0",
"bytes",
"cookie",
"cookie_store",
@@ -1420,7 +1420,7 @@ dependencies = [
"percent-encoding",
"pin-project-lite",
"rustls",
- "rustls-pemfile 1.0.4",
+ "rustls-pemfile",
"rustls-pki-types",
"serde",
"serde_json",
@@ -1503,21 +1503,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f1fb85efa936c42c6d5fc28d2629bb51e4b2f4b8a5211e297d599cc5a093792"
dependencies = [
"openssl-probe",
- "rustls-pemfile 2.1.1",
+ "rustls-pemfile",
"rustls-pki-types",
"schannel",
"security-framework",
]
-[[package]]
-name = "rustls-pemfile"
-version = "1.0.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1c74cae0a4cf6ccbbf5f359f08efdf8ee7e1dc532573bf0db71968cb56b1448c"
-dependencies = [
- "base64 0.21.7",
-]
-
[[package]]
name = "rustls-pemfile"
version = "2.1.1"
@@ -2362,9 +2353,9 @@ checksum = "32b752e52a2da0ddfbdbcc6fceadfeede4c939ed16d13e648833a61dfb611ed8"
[[package]]
name = "winreg"
-version = "0.50.0"
+version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "524e57b2c537c0f9b1e69f1965311ec12182b4122e45035b1508cd24d2adadb1"
+checksum = "a277a57398d4bfa075df44f501a17cfdf8542d224f0d36095a2adc7aee4ef0a5"
dependencies = [
"cfg-if",
"windows-sys 0.48.0",
diff --git a/Cargo.toml b/Cargo.toml
index 221db3f..c49244b 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli"
authors = ["Crunchy Labs Maintainers"]
-version = "3.3.4"
+version = "3.3.5"
edition = "2021"
license = "MIT"
diff --git a/crunchy-cli-core/Cargo.toml b/crunchy-cli-core/Cargo.toml
index 0bbf493..07973e1 100644
--- a/crunchy-cli-core/Cargo.toml
+++ b/crunchy-cli-core/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli-core"
authors = ["Crunchy Labs Maintainers"]
-version = "3.3.4"
+version = "3.3.5"
edition = "2021"
license = "MIT"
@@ -16,7 +16,7 @@ anyhow = "1.0"
async-speed-limit = "0.4"
clap = { version = "4.5", features = ["derive", "string"] }
chrono = "0.4"
-crunchyroll-rs = { version = "0.10.2", features = ["experimental-stabilizations", "tower"] }
+crunchyroll-rs = { version = "0.10.3", features = ["experimental-stabilizations", "tower"] }
ctrlc = "3.4"
dialoguer = { version = "0.11", default-features = false }
dirs = "5.0"
From 4b74299733732ee07f94dcc503d1c64920c888f2 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Fri, 5 Apr 2024 22:53:53 +0200
Subject: [PATCH 11/82] Only run ci action on branch push
---
.github/workflows/ci.yml | 2 ++
1 file changed, 2 insertions(+)
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 6991cad..70f4400 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -2,6 +2,8 @@ name: ci
on:
push:
+ branches:
+ - '*'
pull_request:
workflow_dispatch:
From 25cde6163c8c0a5b13459274f4239b1b7f99181a Mon Sep 17 00:00:00 2001
From: bytedream
Date: Sat, 6 Apr 2024 21:23:21 +0200
Subject: [PATCH 12/82] Add account scope for search command
---
crunchy-cli-core/src/lib.rs | 2 -
crunchy-cli-core/src/search/command.rs | 13 ++++--
crunchy-cli-core/src/search/format.rs | 59 ++++++++++++++++++++++++--
3 files changed, 65 insertions(+), 9 deletions(-)
diff --git a/crunchy-cli-core/src/lib.rs b/crunchy-cli-core/src/lib.rs
index 8067c42..483cb63 100644
--- a/crunchy-cli-core/src/lib.rs
+++ b/crunchy-cli-core/src/lib.rs
@@ -225,8 +225,6 @@ async fn execute_executor(executor: impl Execute, ctx: Context) {
if let Some(crunchy_error) = err.downcast_mut::() {
if let Error::Block { message, .. } = crunchy_error {
*message = "Triggered Cloudflare bot protection. Try again later or use a VPN or proxy to spoof your location".to_string()
- } else if let Error::Request { message, .. } = crunchy_error {
- *message = "You've probably hit a rate limit. Try again later, generally after 10-20 minutes the rate limit is over and you can continue to use the cli".to_string()
}
error!("An error occurred: {}", crunchy_error)
diff --git a/crunchy-cli-core/src/search/command.rs b/crunchy-cli-core/src/search/command.rs
index f683e24..c29ce34 100644
--- a/crunchy-cli-core/src/search/command.rs
+++ b/crunchy-cli-core/src/search/command.rs
@@ -8,6 +8,7 @@ use crunchyroll_rs::common::StreamExt;
use crunchyroll_rs::search::QueryResults;
use crunchyroll_rs::{Episode, Locale, MediaCollection, MovieListing, MusicVideo, Series};
use log::warn;
+use std::sync::Arc;
#[derive(Debug, clap::Parser)]
#[clap(about = "Search in videos")]
@@ -87,11 +88,16 @@ pub struct Search {
/// concert.premium_only → If the concert is only available with Crunchyroll premium
///
/// stream.locale → Stream locale/language
- /// stream.dash_url → Stream url in DASH format
- /// stream.is_drm → If `stream.is_drm` is DRM encrypted
+ /// stream.dash_url → Stream url in DASH format. You need to set the `Authorization` header to `Bearer ` when requesting this url
+ /// stream.is_drm → If `stream.dash_url` is DRM encrypted
///
/// subtitle.locale → Subtitle locale/language
/// subtitle.url → Url to the subtitle
+ ///
+ /// account.token → Access token to make request to restricted endpoints. This token is only valid for a max. of 5 minutes
+ /// account.id → Internal ID of the user account
+ /// account.profile_name → Profile name of the account
+ /// account.email → Email address of the account
#[arg(short, long, verbatim_doc_comment)]
#[arg(default_value = "S{{season.number}}E{{episode.number}} - {{episode.title}}")]
output: String,
@@ -143,13 +149,14 @@ impl Execute for Search {
output
};
+ let crunchy_arc = Arc::new(ctx.crunchy);
for (media_collection, url_filter) in input {
let filter_options = FilterOptions {
audio: self.audio.clone(),
url_filter,
};
- let format = Format::new(self.output.clone(), filter_options)?;
+ let format = Format::new(self.output.clone(), filter_options, crunchy_arc.clone())?;
println!("{}", format.parse(media_collection).await?);
}
diff --git a/crunchy-cli-core/src/search/format.rs b/crunchy-cli-core/src/search/format.rs
index 10eefd8..7ea84d8 100644
--- a/crunchy-cli-core/src/search/format.rs
+++ b/crunchy-cli-core/src/search/format.rs
@@ -2,13 +2,15 @@ use crate::search::filter::FilterOptions;
use anyhow::{bail, Result};
use crunchyroll_rs::media::{Stream, Subtitle};
use crunchyroll_rs::{
- Concert, Episode, Locale, MediaCollection, Movie, MovieListing, MusicVideo, Season, Series,
+ Concert, Crunchyroll, Episode, Locale, MediaCollection, Movie, MovieListing, MusicVideo,
+ Season, Series,
};
use regex::Regex;
use serde::Serialize;
use serde_json::{Map, Value};
use std::collections::HashMap;
use std::ops::Range;
+use std::sync::Arc;
#[derive(Default, Serialize)]
struct FormatSeries {
@@ -191,6 +193,27 @@ impl From<&Subtitle> for FormatSubtitle {
}
}
+#[derive(Default, Serialize)]
+struct FormatAccount {
+ pub token: String,
+ pub id: String,
+ pub profile_name: String,
+ pub email: String,
+}
+
+impl FormatAccount {
+ pub async fn async_from(value: &Crunchyroll) -> Result {
+ let account = value.account().await?;
+
+ Ok(Self {
+ token: value.access_token().await,
+ id: account.account_id,
+ profile_name: account.profile_name,
+ email: account.email,
+ })
+ }
+}
+
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
enum Scope {
Series,
@@ -202,6 +225,7 @@ enum Scope {
Concert,
Stream,
Subtitle,
+ Account,
}
macro_rules! must_match_if_true {
@@ -230,10 +254,15 @@ pub struct Format {
pattern_count: HashMap,
input: String,
filter_options: FilterOptions,
+ crunchyroll: Arc,
}
impl Format {
- pub fn new(input: String, filter_options: FilterOptions) -> Result {
+ pub fn new(
+ input: String,
+ filter_options: FilterOptions,
+ crunchyroll: Arc,
+ ) -> Result {
let scope_regex = Regex::new(r"(?m)\{\{\s*(?P\w+)\.(?P\w+)\s*}}").unwrap();
let mut pattern = vec![];
let mut pattern_count = HashMap::new();
@@ -260,6 +289,7 @@ impl Format {
Scope::Concert => FormatConcert
Scope::Stream => FormatStream
Scope::Subtitle => FormatSubtitle
+ Scope::Account => FormatAccount
);
for capture in scope_regex.captures_iter(&input) {
@@ -277,6 +307,7 @@ impl Format {
"concert" => Scope::Concert,
"stream" => Scope::Stream,
"subtitle" => Scope::Subtitle,
+ "account" => Scope::Account,
_ => bail!("'{}.{}' is not a valid keyword", scope, field),
};
@@ -302,6 +333,7 @@ impl Format {
pattern_count,
input,
filter_options,
+ crunchyroll,
})
}
@@ -316,6 +348,7 @@ impl Format {
Scope::Episode,
Scope::Stream,
Scope::Subtitle,
+ Scope::Account,
])?;
self.parse_series(media_collection).await
@@ -326,17 +359,28 @@ impl Format {
Scope::Movie,
Scope::Stream,
Scope::Subtitle,
+ Scope::Account,
])?;
self.parse_movie_listing(media_collection).await
}
MediaCollection::MusicVideo(_) => {
- self.check_scopes(vec![Scope::MusicVideo, Scope::Stream, Scope::Subtitle])?;
+ self.check_scopes(vec![
+ Scope::MusicVideo,
+ Scope::Stream,
+ Scope::Subtitle,
+ Scope::Account,
+ ])?;
self.parse_music_video(media_collection).await
}
MediaCollection::Concert(_) => {
- self.check_scopes(vec![Scope::Concert, Scope::Stream, Scope::Subtitle])?;
+ self.check_scopes(vec![
+ Scope::Concert,
+ Scope::Stream,
+ Scope::Subtitle,
+ Scope::Account,
+ ])?;
self.parse_concert(media_collection).await
}
@@ -349,6 +393,7 @@ impl Format {
let episode_empty = self.check_pattern_count_empty(Scope::Episode);
let stream_empty = self.check_pattern_count_empty(Scope::Stream)
&& self.check_pattern_count_empty(Scope::Subtitle);
+ let account_empty = self.check_pattern_count_empty(Scope::Account);
#[allow(clippy::type_complexity)]
let mut tree: Vec<(Season, Vec<(Episode, Vec)>)> = vec![];
@@ -431,6 +476,11 @@ impl Format {
}
let mut output = vec![];
+ let account_map = if !account_empty {
+ self.serializable_to_json_map(FormatAccount::async_from(&self.crunchyroll).await?)
+ } else {
+ Map::default()
+ };
let series_map = self.serializable_to_json_map(FormatSeries::from(&series));
for (season, episodes) in tree {
let season_map = self.serializable_to_json_map(FormatSeason::from(&season));
@@ -442,6 +492,7 @@ impl Format {
output.push(
self.replace_all(
HashMap::from([
+ (Scope::Account, &account_map),
(Scope::Series, &series_map),
(Scope::Season, &season_map),
(Scope::Episode, &episode_map),
From fe49161e933e739784393a5ba92e29291025b803 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Mon, 8 Apr 2024 00:37:19 +0200
Subject: [PATCH 13/82] End ffmpeg progress always with at least 100%
---
crunchy-cli-core/src/utils/download.rs | 26 +++++++++++++-------------
1 file changed, 13 insertions(+), 13 deletions(-)
diff --git a/crunchy-cli-core/src/utils/download.rs b/crunchy-cli-core/src/utils/download.rs
index d7904f3..cee89e2 100644
--- a/crunchy-cli-core/src/utils/download.rs
+++ b/crunchy-cli-core/src/utils/download.rs
@@ -1285,21 +1285,11 @@ async fn ffmpeg_progress(
let reader = BufReader::new(stats);
let mut lines = reader.lines();
+ let mut frame = 0;
loop {
select! {
- // when gracefully canceling this future, set the progress to 100% (finished). sometimes
- // ffmpeg is too fast or already finished when the reading process of 'stats' starts
- // which causes the progress to be stuck at 0%
_ = cancellation_token.cancelled() => {
- if let Some(p) = &progress {
- p.set_position(total_frames)
- }
- debug!(
- "Processed frame [{}/{} 100%]",
- total_frames,
- total_frames
- );
- return Ok(())
+ break
}
line = lines.next_line() => {
let Some(line) = line? else {
@@ -1314,7 +1304,7 @@ async fn ffmpeg_progress(
let Some(frame_str) = frame_cap.name("frame") else {
break
};
- let frame: u64 = frame_str.as_str().parse()?;
+ frame = frame_str.as_str().parse()?;
if let Some(p) = &progress {
p.set_position(frame)
@@ -1330,5 +1320,15 @@ async fn ffmpeg_progress(
}
}
+ // when this future is gracefully cancelled or if ffmpeg is too fast or already finished when
+ // reading process of 'stats' starts (which causes the progress to be stuck at 0%), the progress
+ // is manually set to 100% here
+ if frame < total_frames {
+ if let Some(p) = &progress {
+ p.set_position(frame)
+ }
+ debug!("Processed frame [{}/{} 100%]", total_frames, total_frames);
+ }
+
Ok(())
}
From 1a511e12f95e7e4e76d97a4624306387909c6590 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Mon, 8 Apr 2024 13:57:06 +0200
Subject: [PATCH 14/82] Add archive start sync flag
---
Cargo.lock | 122 +++++
crunchy-cli-core/Cargo.toml | 2 +
crunchy-cli-core/src/archive/command.rs | 35 +-
crunchy-cli-core/src/download/command.rs | 4 +-
crunchy-cli-core/src/lib.rs | 33 +-
crunchy-cli-core/src/utils/download.rs | 653 +++++++++++++++++------
crunchy-cli-core/src/utils/os.rs | 20 +-
crunchy-cli-core/src/utils/video.rs | 2 +-
8 files changed, 692 insertions(+), 179 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index 7d0b7e1..c1f24f4 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -179,6 +179,18 @@ version = "3.15.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ff69b9dd49fd426c69a0db9fc04dd934cdb6645ff000864d98f7e2af8830eaa"
+[[package]]
+name = "bytemuck"
+version = "1.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d6d68c57235a3a081186990eca2867354726650f42f7516ca50c28d6281fd15"
+
+[[package]]
+name = "byteorder"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
+
[[package]]
name = "bytes"
version = "1.6.0"
@@ -369,6 +381,8 @@ dependencies = [
"fs2",
"futures-util",
"http",
+ "image",
+ "image_hasher",
"indicatif",
"lazy_static",
"log",
@@ -936,6 +950,32 @@ dependencies = [
"unicode-normalization",
]
+[[package]]
+name = "image"
+version = "0.25.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fd54d660e773627692c524beaad361aca785a4f9f5730ce91f42aabe5bce3d11"
+dependencies = [
+ "bytemuck",
+ "byteorder",
+ "num-traits",
+ "zune-core",
+ "zune-jpeg",
+]
+
+[[package]]
+name = "image_hasher"
+version = "2.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9481465fe767d92494987319b0b447a5829edf57f09c52bf8639396abaaeaf78"
+dependencies = [
+ "base64 0.22.0",
+ "image",
+ "rustdct",
+ "serde",
+ "transpose",
+]
+
[[package]]
name = "indexmap"
version = "1.9.3"
@@ -1143,12 +1183,30 @@ dependencies = [
"minimal-lexical",
]
+[[package]]
+name = "num-complex"
+version = "0.4.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23c6602fda94a57c990fe0df199a035d83576b496aa29f4e634a8ac6004e68a6"
+dependencies = [
+ "num-traits",
+]
+
[[package]]
name = "num-conv"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9"
+[[package]]
+name = "num-integer"
+version = "0.1.46"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"
+dependencies = [
+ "num-traits",
+]
+
[[package]]
name = "num-traits"
version = "0.2.18"
@@ -1305,6 +1363,15 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
+[[package]]
+name = "primal-check"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9df7f93fd637f083201473dab4fee2db4c429d32e55e3299980ab3957ab916a0"
+dependencies = [
+ "num-integer",
+]
+
[[package]]
name = "proc-macro2"
version = "1.0.79"
@@ -1469,6 +1536,30 @@ version = "0.1.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76"
+[[package]]
+name = "rustdct"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b61555105d6a9bf98797c063c362a1d24ed8ab0431655e38f1cf51e52089551"
+dependencies = [
+ "rustfft",
+]
+
+[[package]]
+name = "rustfft"
+version = "6.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "43806561bc506d0c5d160643ad742e3161049ac01027b5e6d7524091fd401d86"
+dependencies = [
+ "num-complex",
+ "num-integer",
+ "num-traits",
+ "primal-check",
+ "strength_reduce",
+ "transpose",
+ "version_check",
+]
+
[[package]]
name = "rustix"
version = "0.38.32"
@@ -1720,6 +1811,12 @@ version = "0.9.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67"
+[[package]]
+name = "strength_reduce"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82"
+
[[package]]
name = "strsim"
version = "0.10.0"
@@ -1998,6 +2095,16 @@ dependencies = [
"once_cell",
]
+[[package]]
+name = "transpose"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ad61aed86bc3faea4300c7aee358b4c6d0c8d6ccc36524c96e4c92ccf26e77e"
+dependencies = [
+ "num-integer",
+ "strength_reduce",
+]
+
[[package]]
name = "try-lock"
version = "0.2.5"
@@ -2377,3 +2484,18 @@ name = "zeroize"
version = "1.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "525b4ec142c6b68a2d10f01f7bbf6755599ca3f81ea53b8431b7dd348f5fdb2d"
+
+[[package]]
+name = "zune-core"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f423a2c17029964870cfaabb1f13dfab7d092a62a29a89264f4d36990ca414a"
+
+[[package]]
+name = "zune-jpeg"
+version = "0.4.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec866b44a2a1fd6133d363f073ca1b179f438f99e7e5bfb1e33f7181facfe448"
+dependencies = [
+ "zune-core",
+]
diff --git a/crunchy-cli-core/Cargo.toml b/crunchy-cli-core/Cargo.toml
index 07973e1..bd47aba 100644
--- a/crunchy-cli-core/Cargo.toml
+++ b/crunchy-cli-core/Cargo.toml
@@ -24,6 +24,8 @@ derive_setters = "0.1"
futures-util = { version = "0.3", features = ["io"] }
fs2 = "0.4"
http = "1.1"
+image = { version = "0.25", features = ["jpeg"], default-features = false }
+image_hasher = "2.0"
indicatif = "0.17"
lazy_static = "1.4"
log = { version = "0.4", features = ["std"] }
diff --git a/crunchy-cli-core/src/archive/command.rs b/crunchy-cli-core/src/archive/command.rs
index 0dc0b86..64ad66a 100644
--- a/crunchy-cli-core/src/archive/command.rs
+++ b/crunchy-cli-core/src/archive/command.rs
@@ -10,7 +10,7 @@ use crate::utils::locale::{all_locale_in_locales, resolve_locales, LanguageTaggi
use crate::utils::log::progress;
use crate::utils::os::{free_file, has_ffmpeg, is_special_file};
use crate::utils::parse::parse_url;
-use crate::utils::video::variant_data_from_stream;
+use crate::utils::video::stream_data_from_stream;
use crate::Execute;
use anyhow::bail;
use anyhow::Result;
@@ -89,6 +89,17 @@ pub struct Archive {
#[arg(value_parser = crate::utils::clap::clap_parse_resolution)]
pub(crate) resolution: Resolution,
+ #[arg(help = "Tries to sync the timing of all downloaded audios to match one video")]
+ #[arg(
+ long_help = "Tries to sync the timing of all downloaded audios to match one video. \
+ This is done by downloading the first few segments/frames of all video tracks that differ in length and comparing them frame by frame. \
+ The value of this flag determines how accurate the syncing is, generally speaking everything over 15 begins to be more inaccurate and everything below 6 is too accurate (and won't succeed). \
+ If you want to provide a custom value to this flag, you have to set it with an equals (e.g. `--sync-start=10` instead of `--sync-start 10`). \
+ When the syncing fails, the command is continued as if `--sync-start` wasn't provided for this episode
+ "
+ )]
+ #[arg(long, require_equals = true, num_args = 0..=1, default_missing_value = "7.5")]
+ pub(crate) sync_start: Option,
#[arg(
help = "Sets the behavior of the stream merging. Valid behaviors are 'auto', 'audio' and 'video'"
)]
@@ -216,8 +227,19 @@ impl Execute for Archive {
}
}
- if self.include_chapters && !matches!(self.merge, MergeBehavior::Audio) {
- bail!("`--include-chapters` can only be used if `--merge` is set to 'audio'")
+ if self.include_chapters
+ && !matches!(self.merge, MergeBehavior::Audio)
+ && self.sync_start.is_none()
+ {
+ bail!("`--include-chapters` can only be used if `--merge` is set to 'audio' or `--sync-start` is set")
+ }
+
+ if !matches!(self.merge, MergeBehavior::Auto) && self.sync_start.is_some() {
+ bail!("`--sync-start` can only be used if `--merge` is set to `auto`")
+ }
+
+ if self.sync_start.is_some() && self.ffmpeg_preset.is_none() {
+ warn!("Using `--sync-start` without `--ffmpeg-preset` might produce worse sync results than with `--ffmpeg-preset` set")
}
if self.output.contains("{resolution}")
@@ -294,6 +316,7 @@ impl Execute for Archive {
.audio_sort(Some(self.audio.clone()))
.subtitle_sort(Some(self.subtitle.clone()))
.no_closed_caption(self.no_closed_caption)
+ .sync_start_value(self.sync_start)
.threads(self.threads)
.audio_locale_output_map(
zip(self.audio.clone(), self.output_audio_locales.clone()).collect(),
@@ -450,7 +473,7 @@ async fn get_format(
for single_format in single_formats {
let stream = single_format.stream().await?;
let Some((video, audio, _)) =
- variant_data_from_stream(&stream, &archive.resolution, None).await?
+ stream_data_from_stream(&stream, &archive.resolution, None).await?
else {
if single_format.is_episode() {
bail!(
@@ -569,7 +592,9 @@ async fn get_format(
video: (video, single_format.audio.clone()),
audios: vec![(audio, single_format.audio.clone())],
subtitles,
- metadata: DownloadFormatMetadata { skip_events: None },
+ metadata: DownloadFormatMetadata {
+ skip_events: single_format.skip_events().await?,
+ },
},
));
}
diff --git a/crunchy-cli-core/src/download/command.rs b/crunchy-cli-core/src/download/command.rs
index 47b29c9..fd29030 100644
--- a/crunchy-cli-core/src/download/command.rs
+++ b/crunchy-cli-core/src/download/command.rs
@@ -8,7 +8,7 @@ use crate::utils::locale::{resolve_locales, LanguageTagging};
use crate::utils::log::progress;
use crate::utils::os::{free_file, has_ffmpeg, is_special_file};
use crate::utils::parse::parse_url;
-use crate::utils::video::variant_data_from_stream;
+use crate::utils::video::stream_data_from_stream;
use crate::Execute;
use anyhow::bail;
use anyhow::Result;
@@ -351,7 +351,7 @@ async fn get_format(
try_peer_hardsubs: bool,
) -> Result<(DownloadFormat, Format)> {
let stream = single_format.stream().await?;
- let Some((video, audio, contains_hardsub)) = variant_data_from_stream(
+ let Some((video, audio, contains_hardsub)) = stream_data_from_stream(
&stream,
&download.resolution,
if try_peer_hardsubs {
diff --git a/crunchy-cli-core/src/lib.rs b/crunchy-cli-core/src/lib.rs
index 483cb63..d8d5ec5 100644
--- a/crunchy-cli-core/src/lib.rs
+++ b/crunchy-cli-core/src/lib.rs
@@ -184,16 +184,29 @@ pub async fn main(args: &[String]) {
.unwrap_or_default()
.starts_with(".crunchy-cli_")
{
- let result = fs::remove_file(file.path());
- debug!(
- "Ctrl-c removed temporary file {} {}",
- file.path().to_string_lossy(),
- if result.is_ok() {
- "successfully"
- } else {
- "not successfully"
- }
- )
+ if file.file_type().map_or(true, |ft| ft.is_file()) {
+ let result = fs::remove_file(file.path());
+ debug!(
+ "Ctrl-c removed temporary file {} {}",
+ file.path().to_string_lossy(),
+ if result.is_ok() {
+ "successfully"
+ } else {
+ "not successfully"
+ }
+ )
+ } else {
+ let result = fs::remove_dir_all(file.path());
+ debug!(
+ "Ctrl-c removed temporary directory {} {}",
+ file.path().to_string_lossy(),
+ if result.is_ok() {
+ "successfully"
+ } else {
+ "not successfully"
+ }
+ )
+ }
}
}
}
diff --git a/crunchy-cli-core/src/utils/download.rs b/crunchy-cli-core/src/utils/download.rs
index cee89e2..fe0e84a 100644
--- a/crunchy-cli-core/src/utils/download.rs
+++ b/crunchy-cli-core/src/utils/download.rs
@@ -1,11 +1,15 @@
use crate::utils::ffmpeg::FFmpegPreset;
use crate::utils::filter::real_dedup_vec;
-use crate::utils::os::{cache_dir, is_special_file, temp_directory, temp_named_pipe, tempfile};
+use crate::utils::log::progress;
+use crate::utils::os::{
+ cache_dir, is_special_file, temp_directory, temp_named_pipe, tempdir, tempfile,
+};
use crate::utils::rate_limit::RateLimiterService;
use anyhow::{bail, Result};
-use chrono::NaiveTime;
+use chrono::{NaiveTime, TimeDelta};
use crunchyroll_rs::media::{SkipEvents, SkipEventsEvent, StreamData, StreamSegment, Subtitle};
use crunchyroll_rs::Locale;
+use image_hasher::{Hasher, HasherConfig, ImageHash};
use indicatif::{ProgressBar, ProgressDrawTarget, ProgressFinish, ProgressStyle};
use log::{debug, warn, LevelFilter};
use regex::Regex;
@@ -59,6 +63,7 @@ pub struct DownloadBuilder {
force_hardsub: bool,
download_fonts: bool,
no_closed_caption: bool,
+ sync_start_value: Option,
threads: usize,
ffmpeg_threads: Option,
audio_locale_output_map: HashMap,
@@ -78,6 +83,7 @@ impl DownloadBuilder {
force_hardsub: false,
download_fonts: false,
no_closed_caption: false,
+ sync_start_value: None,
threads: num_cpus::get(),
ffmpeg_threads: None,
audio_locale_output_map: HashMap::new(),
@@ -99,6 +105,8 @@ impl DownloadBuilder {
download_fonts: self.download_fonts,
no_closed_caption: self.no_closed_caption,
+ sync_start_value: self.sync_start_value,
+
download_threads: self.threads,
ffmpeg_threads: self.ffmpeg_threads,
@@ -110,10 +118,23 @@ impl DownloadBuilder {
}
}
-struct FFmpegMeta {
+struct FFmpegVideoMeta {
path: TempPath,
- language: Locale,
- title: String,
+ length: TimeDelta,
+ start_time: Option,
+}
+
+struct FFmpegAudioMeta {
+ path: TempPath,
+ locale: Locale,
+ start_time: Option,
+}
+
+struct FFmpegSubtitleMeta {
+ path: TempPath,
+ locale: Locale,
+ cc: bool,
+ start_time: Option,
}
pub struct DownloadFormat {
@@ -141,6 +162,8 @@ pub struct Downloader {
download_fonts: bool,
no_closed_caption: bool,
+ sync_start_value: Option,
+
download_threads: usize,
ffmpeg_threads: Option,
@@ -216,13 +239,16 @@ impl Downloader {
}
}
+ let mut video_offset = None;
+ let mut audio_offsets = HashMap::new();
+ let mut subtitle_offsets = HashMap::new();
let mut videos = vec![];
let mut audios = vec![];
let mut subtitles = vec![];
let mut fonts = vec![];
let mut chapters = None;
- let mut max_len = NaiveTime::MIN;
- let mut max_frames = 0f64;
+ let mut max_len = TimeDelta::min_value();
+ let mut max_frames = 0;
let fmt_space = self
.formats
.iter()
@@ -234,115 +260,252 @@ impl Downloader {
.max()
.unwrap();
- for (i, format) in self.formats.iter().enumerate() {
- let video_path = self
- .download_video(
- &format.video.0,
- format!("{:<1$}", format!("Downloading video #{}", i + 1), fmt_space),
- )
- .await?;
- for (variant_data, locale) in format.audios.iter() {
- let audio_path = self
- .download_audio(
- variant_data,
- format!("{:<1$}", format!("Downloading {} audio", locale), fmt_space),
+ if self.formats.len() > 1 && self.sync_start_value.is_some() {
+ let all_segments_count: Vec = self
+ .formats
+ .iter()
+ .map(|f| f.video.0.segments().len())
+ .collect();
+ let sync_segments = 11.max(
+ all_segments_count.iter().max().unwrap() - all_segments_count.iter().min().unwrap(),
+ );
+ let mut sync_vids = vec![];
+ for (i, format) in self.formats.iter().enumerate() {
+ let path = self
+ .download_video(
+ &format.video.0,
+ format!("Downloading video #{} sync segments", i + 1),
+ Some(sync_segments),
)
.await?;
- audios.push(FFmpegMeta {
- path: audio_path,
- language: locale.clone(),
- title: if i == 0 {
- locale.to_human_readable()
- } else {
- format!("{} [Video: #{}]", locale.to_human_readable(), i + 1)
- },
+ sync_vids.push(SyncVideo {
+ path,
+ length: len_from_segments(&format.video.0.segments()),
+ available_frames: (len_from_segments(
+ &format.video.0.segments()[0..sync_segments],
+ )
+ .num_milliseconds() as f64
+ * format.video.0.fps().unwrap()
+ / 1000.0) as u64,
+ idx: i,
})
}
- let (len, fps) = get_video_stats(&video_path)?;
+ let _progress_handler =
+ progress!("Syncing video start times (this might take some time)");
+ let mut offsets = sync_videos(sync_vids, self.sync_start_value.unwrap())?;
+ drop(_progress_handler);
+
+ let mut offset_pre_checked = false;
+ if let Some(tmp_offsets) = &offsets {
+ let formats_with_offset: Vec = self
+ .formats
+ .iter()
+ .enumerate()
+ .map(|(i, f)| {
+ len_from_segments(&f.video.0.segments())
+ - TimeDelta::milliseconds(
+ tmp_offsets
+ .get(&i)
+ .map(|o| (*o as f64 / f.video.0.fps().unwrap() * 1000.0) as i64)
+ .unwrap_or_default(),
+ )
+ })
+ .collect();
+ let min = formats_with_offset.iter().min().unwrap();
+ let max = formats_with_offset.iter().max().unwrap();
+
+ if max.num_seconds() - min.num_seconds() > 15 {
+ warn!("Found difference of >15 seconds after sync, skipping applying it");
+ offsets = None;
+ offset_pre_checked = true
+ }
+ }
+
+ if let Some(offsets) = offsets {
+ let mut root_format_idx = 0;
+ let mut root_format_length = 0;
+ let mut audio_count: usize = 0;
+ let mut subtitle_count: usize = 0;
+ for (i, format) in self.formats.iter().enumerate() {
+ let format_fps = format.video.0.fps().unwrap();
+ let format_len = format
+ .video
+ .0
+ .segments()
+ .iter()
+ .map(|s| s.length.as_millis())
+ .sum::() as u64
+ - offsets.get(&i).map_or(0, |o| *o);
+ if format_len > root_format_length {
+ root_format_idx = i;
+ root_format_length = format_len;
+ }
+
+ for _ in &format.audios {
+ if let Some(offset) = &offsets.get(&i) {
+ audio_offsets.insert(
+ audio_count,
+ TimeDelta::milliseconds(
+ (**offset as f64 / format_fps * 1000.0) as i64,
+ ),
+ );
+ }
+ audio_count += 1
+ }
+ for _ in &format.subtitles {
+ if let Some(offset) = &offsets.get(&i) {
+ subtitle_offsets.insert(
+ subtitle_count,
+ TimeDelta::milliseconds(
+ (**offset as f64 / format_fps * 1000.0) as i64,
+ ),
+ );
+ }
+ subtitle_count += 1
+ }
+ }
+
+ let mut root_format = self.formats.remove(root_format_idx);
+
+ let mut audio_prepend = vec![];
+ let mut subtitle_prepend = vec![];
+ let mut audio_append = vec![];
+ let mut subtitle_append = vec![];
+ for (i, format) in self.formats.into_iter().enumerate() {
+ if i < root_format_idx {
+ audio_prepend.extend(format.audios);
+ subtitle_prepend.extend(format.subtitles);
+ } else {
+ audio_append.extend(format.audios);
+ subtitle_append.extend(format.subtitles);
+ }
+ }
+ root_format.audios.splice(0..0, audio_prepend);
+ root_format.subtitles.splice(0..0, subtitle_prepend);
+ root_format.audios.extend(audio_append);
+ root_format.subtitles.extend(subtitle_append);
+
+ self.formats = vec![root_format];
+ video_offset = offsets.get(&root_format_idx).map(|o| {
+ TimeDelta::milliseconds(
+ (*o as f64 / self.formats[0].video.0.fps().unwrap() * 1000.0) as i64,
+ )
+ })
+ } else if !offset_pre_checked {
+ warn!("Couldn't find reliable sync positions")
+ }
+ }
+
+ // downloads all videos
+ for (i, format) in self.formats.iter().enumerate() {
+ let path = self
+ .download_video(
+ &format.video.0,
+ format!("{:<1$}", format!("Downloading video #{}", i + 1), fmt_space),
+ None,
+ )
+ .await?;
+
+ let (len, fps) = get_video_stats(&path)?;
if max_len < len {
max_len = len
}
- let frames = len.signed_duration_since(NaiveTime::MIN).num_seconds() as f64 * fps;
- if frames > max_frames {
- max_frames = frames;
+ let frames = ((len.num_milliseconds() as f64
+ - video_offset.unwrap_or_default().num_milliseconds() as f64)
+ / 1000.0
+ * fps) as u64;
+ if max_frames < frames {
+ max_frames = frames
}
- if !format.subtitles.is_empty() {
- let progress_spinner = if log::max_level() == LevelFilter::Info {
- let progress_spinner = ProgressBar::new_spinner()
- .with_style(
- ProgressStyle::with_template(
- format!(
- ":: {:<1$} {{msg}} {{spinner}}",
- "Downloading subtitles", fmt_space
- )
- .as_str(),
+ videos.push(FFmpegVideoMeta {
+ path,
+ length: len,
+ start_time: video_offset,
+ })
+ }
+
+ // downloads all audios
+ for format in &self.formats {
+ for (j, (stream_data, locale)) in format.audios.iter().enumerate() {
+ let path = self
+ .download_audio(
+ stream_data,
+ format!("{:<1$}", format!("Downloading {} audio", locale), fmt_space),
+ )
+ .await?;
+ audios.push(FFmpegAudioMeta {
+ path,
+ locale: locale.clone(),
+ start_time: audio_offsets.get(&j).cloned(),
+ })
+ }
+ }
+
+ for (i, format) in self.formats.iter().enumerate() {
+ if format.subtitles.is_empty() {
+ continue;
+ }
+
+ let progress_spinner = if log::max_level() == LevelFilter::Info {
+ let progress_spinner = ProgressBar::new_spinner()
+ .with_style(
+ ProgressStyle::with_template(
+ format!(
+ ":: {:<1$} {{msg}} {{spinner}}",
+ "Downloading subtitles", fmt_space
)
- .unwrap()
- .tick_strings(&["—", "\\", "|", "/", ""]),
+ .as_str(),
)
- .with_finish(ProgressFinish::Abandon);
- progress_spinner.enable_steady_tick(Duration::from_millis(100));
- Some(progress_spinner)
- } else {
- None
- };
+ .unwrap()
+ .tick_strings(&["—", "\\", "|", "/", ""]),
+ )
+ .with_finish(ProgressFinish::Abandon);
+ progress_spinner.enable_steady_tick(Duration::from_millis(100));
+ Some(progress_spinner)
+ } else {
+ None
+ };
- for (subtitle, not_cc) in format.subtitles.iter() {
- if !not_cc && self.no_closed_caption {
- continue;
- }
-
- if let Some(pb) = &progress_spinner {
- let mut progress_message = pb.message();
- if !progress_message.is_empty() {
- progress_message += ", "
- }
- progress_message += &subtitle.locale.to_string();
- if !not_cc {
- progress_message += " (CC)";
- }
- if i != 0 {
- progress_message += &format!(" [Video: #{}]", i + 1);
- }
- pb.set_message(progress_message)
- }
-
- let mut subtitle_title = subtitle.locale.to_human_readable();
- if !not_cc {
- subtitle_title += " (CC)"
- }
- if i != 0 {
- subtitle_title += &format!(" [Video: #{}]", i + 1)
- }
-
- let subtitle_path = self.download_subtitle(subtitle.clone(), len).await?;
- debug!(
- "Downloaded {} subtitles{}{}",
- subtitle.locale,
- (!not_cc).then_some(" (cc)").unwrap_or_default(),
- (i != 0)
- .then_some(format!(" for video {}", i))
- .unwrap_or_default()
- );
- subtitles.push(FFmpegMeta {
- path: subtitle_path,
- language: subtitle.locale.clone(),
- title: subtitle_title,
- })
+ for (j, (subtitle, not_cc)) in format.subtitles.iter().enumerate() {
+ if !not_cc && self.no_closed_caption {
+ continue;
}
- }
- videos.push(FFmpegMeta {
- path: video_path,
- language: format.video.1.clone(),
- title: if self.formats.len() == 1 {
- "Default".to_string()
- } else {
- format!("#{}", i + 1)
- },
- });
+ if let Some(pb) = &progress_spinner {
+ let mut progress_message = pb.message();
+ if !progress_message.is_empty() {
+ progress_message += ", "
+ }
+ progress_message += &subtitle.locale.to_string();
+ if !not_cc {
+ progress_message += " (CC)";
+ }
+ if i.min(videos.len() - 1) != 0 {
+ progress_message += &format!(" [Video: #{}]", i + 1);
+ }
+ pb.set_message(progress_message)
+ }
+
+ let path = self
+ .download_subtitle(subtitle.clone(), videos[i.min(videos.len() - 1)].length)
+ .await?;
+ debug!(
+ "Downloaded {} subtitles{}",
+ subtitle.locale,
+ (!not_cc).then_some(" (cc)").unwrap_or_default(),
+ );
+ subtitles.push(FFmpegSubtitleMeta {
+ path,
+ locale: subtitle.locale.clone(),
+ cc: !not_cc,
+ start_time: subtitle_offsets.get(&j).cloned(),
+ })
+ }
+ }
+
+ for format in self.formats.iter() {
if let Some(skip_events) = &format.metadata.skip_events {
let (file, path) = tempfile(".chapter")?.into_parts();
chapters = Some((
@@ -421,17 +584,30 @@ impl Downloader {
let mut metadata = vec![];
for (i, meta) in videos.iter().enumerate() {
+ if let Some(start_time) = meta.start_time {
+ input.extend(["-ss".to_string(), format_time_delta(start_time)])
+ }
input.extend(["-i".to_string(), meta.path.to_string_lossy().to_string()]);
maps.extend(["-map".to_string(), i.to_string()]);
metadata.extend([
format!("-metadata:s:v:{}", i),
- format!("title={}", meta.title),
+ format!(
+ "title={}",
+ if videos.len() == 1 {
+ "Default".to_string()
+ } else {
+ format!("#{}", i + 1)
+ }
+ ),
]);
// the empty language metadata is created to avoid that metadata from the original track
// is copied
metadata.extend([format!("-metadata:s:v:{}", i), "language=".to_string()])
}
for (i, meta) in audios.iter().enumerate() {
+ if let Some(start_time) = meta.start_time {
+ input.extend(["-ss".to_string(), format_time_delta(start_time)])
+ }
input.extend(["-i".to_string(), meta.path.to_string_lossy().to_string()]);
maps.extend(["-map".to_string(), (i + videos.len()).to_string()]);
metadata.extend([
@@ -439,13 +615,20 @@ impl Downloader {
format!(
"language={}",
self.audio_locale_output_map
- .get(&meta.language)
- .unwrap_or(&meta.language.to_string())
+ .get(&meta.locale)
+ .unwrap_or(&meta.locale.to_string())
),
]);
metadata.extend([
format!("-metadata:s:a:{}", i),
- format!("title={}", meta.title),
+ format!(
+ "title={}",
+ if videos.len() == 1 {
+ meta.locale.to_human_readable()
+ } else {
+ format!("{} [Video: #{}]", meta.locale.to_human_readable(), i + 1,)
+ }
+ ),
]);
}
@@ -465,6 +648,9 @@ impl Downloader {
if container_supports_softsubs {
for (i, meta) in subtitles.iter().enumerate() {
+ if let Some(start_time) = meta.start_time {
+ input.extend(["-ss".to_string(), format_time_delta(start_time)])
+ }
input.extend(["-i".to_string(), meta.path.to_string_lossy().to_string()]);
maps.extend([
"-map".to_string(),
@@ -475,13 +661,22 @@ impl Downloader {
format!(
"language={}",
self.subtitle_locale_output_map
- .get(&meta.language)
- .unwrap_or(&meta.language.to_string())
+ .get(&meta.locale)
+ .unwrap_or(&meta.locale.to_string())
),
]);
metadata.extend([
format!("-metadata:s:s:{}", i),
- format!("title={}", meta.title),
+ format!("title={}", {
+ let mut title = meta.locale.to_string();
+ if meta.cc {
+ title += " (CC)"
+ }
+ if videos.len() > 1 {
+ title += &format!(" [Video: #{}]", i + 1)
+ }
+ title
+ }),
]);
}
}
@@ -523,10 +718,7 @@ impl Downloader {
// set default subtitle
if let Some(default_subtitle) = self.default_subtitle {
- if let Some(position) = subtitles
- .iter()
- .position(|m| m.language == default_subtitle)
- {
+ if let Some(position) = subtitles.iter().position(|m| m.locale == default_subtitle) {
if container_supports_softsubs {
match dst.extension().unwrap_or_default().to_str().unwrap() {
"mov" | "mp4" => output_presets.extend([
@@ -585,7 +777,7 @@ impl Downloader {
if container_supports_softsubs {
if let Some(position) = subtitles
.iter()
- .position(|meta| meta.language == default_subtitle)
+ .position(|meta| meta.locale == default_subtitle)
{
command_args.extend([
format!("-disposition:s:s:{}", position),
@@ -597,9 +789,7 @@ impl Downloader {
// set the 'forced' flag to CC subtitles
for (i, subtitle) in subtitles.iter().enumerate() {
- // well, checking if the title contains '(CC)' might not be the best solutions from a
- // performance perspective but easier than adjusting the `FFmpegMeta` struct
- if !subtitle.title.contains("(CC)") {
+ if !subtitle.cc {
continue;
}
@@ -632,7 +822,7 @@ impl Downloader {
// create parent directory if it does not exist
if let Some(parent) = dst.parent() {
if !parent.exists() {
- std::fs::create_dir_all(parent)?
+ fs::create_dir_all(parent)?
}
}
@@ -650,7 +840,7 @@ impl Downloader {
let ffmpeg_progress_cancellation_token = ffmpeg_progress_cancel.clone();
let ffmpeg_progress = tokio::spawn(async move {
ffmpeg_progress(
- max_frames as u64,
+ max_frames,
fifo,
format!("{:<1$}", "Generating output file", fmt_space + 1),
ffmpeg_progress_cancellation_token,
@@ -681,7 +871,7 @@ impl Downloader {
let segments = stream_data.segments();
// sum the length of all streams up
- estimated_required_space += estimate_variant_file_size(stream_data, &segments);
+ estimated_required_space += estimate_stream_data_file_size(stream_data, &segments);
}
let tmp_stat = fs2::statvfs(temp_directory()).unwrap();
@@ -727,11 +917,16 @@ impl Downloader {
Ok((tmp_required, dst_required))
}
- async fn download_video(&self, stream_data: &StreamData, message: String) -> Result {
+ async fn download_video(
+ &self,
+ stream_data: &StreamData,
+ message: String,
+ max_segments: Option,
+ ) -> Result {
let tempfile = tempfile(".mp4")?;
let (mut file, path) = tempfile.into_parts();
- self.download_segments(&mut file, message, stream_data)
+ self.download_segments(&mut file, message, stream_data, max_segments)
.await?;
Ok(path)
@@ -741,7 +936,7 @@ impl Downloader {
let tempfile = tempfile(".m4a")?;
let (mut file, path) = tempfile.into_parts();
- self.download_segments(&mut file, message, stream_data)
+ self.download_segments(&mut file, message, stream_data, None)
.await?;
Ok(path)
@@ -750,7 +945,7 @@ impl Downloader {
async fn download_subtitle(
&self,
subtitle: Subtitle,
- max_length: NaiveTime,
+ max_length: TimeDelta,
) -> Result {
let tempfile = tempfile(".ass")?;
let (mut file, path) = tempfile.into_parts();
@@ -796,14 +991,20 @@ impl Downloader {
writer: &mut impl Write,
message: String,
stream_data: &StreamData,
+ max_segments: Option,
) -> Result<()> {
- let segments = stream_data.segments();
+ let mut segments = stream_data.segments();
+ if let Some(max_segments) = max_segments {
+ segments = segments
+ .drain(0..max_segments.min(segments.len() - 1))
+ .collect();
+ }
let total_segments = segments.len();
let count = Arc::new(Mutex::new(0));
let progress = if log::max_level() == LevelFilter::Info {
- let estimated_file_size = estimate_variant_file_size(stream_data, &segments);
+ let estimated_file_size = estimate_stream_data_file_size(stream_data, &segments);
let progress = ProgressBar::new(estimated_file_size)
.with_style(
@@ -820,7 +1021,7 @@ impl Downloader {
None
};
- let cpus = self.download_threads;
+ let cpus = self.download_threads.min(segments.len());
let mut segs: Vec> = Vec::with_capacity(cpus);
for _ in 0..cpus {
segs.push(vec![])
@@ -964,12 +1165,12 @@ impl Downloader {
}
}
-fn estimate_variant_file_size(stream_data: &StreamData, segments: &[StreamSegment]) -> u64 {
+fn estimate_stream_data_file_size(stream_data: &StreamData, segments: &[StreamSegment]) -> u64 {
(stream_data.bandwidth / 8) * segments.iter().map(|s| s.length.as_secs()).sum::()
}
/// Get the length and fps of a video.
-fn get_video_stats(path: &Path) -> Result<(NaiveTime, f64)> {
+fn get_video_stats(path: &Path) -> Result<(TimeDelta, f64)> {
let video_length = Regex::new(r"Duration:\s(?P\d+:\d+:\d+\.\d+),")?;
let video_fps = Regex::new(r"(?P[\d/.]+)\sfps")?;
@@ -996,7 +1197,8 @@ fn get_video_stats(path: &Path) -> Result<(NaiveTime, f64)> {
Ok((
NaiveTime::parse_from_str(length_caps.name("time").unwrap().as_str(), "%H:%M:%S%.f")
- .unwrap(),
+ .unwrap()
+ .signed_duration_since(NaiveTime::MIN),
fps_caps.name("fps").unwrap().as_str().parse().unwrap(),
))
}
@@ -1125,28 +1327,12 @@ fn get_subtitle_stats(path: &Path) -> Result> {
/// players. To prevent this, the subtitle entries must be manually sorted. See
/// [crunchy-labs/crunchy-cli#208](https://github.com/crunchy-labs/crunchy-cli/issues/208) for more
/// information.
-fn fix_subtitles(raw: &mut Vec, max_length: NaiveTime) {
+fn fix_subtitles(raw: &mut Vec, max_length: TimeDelta) {
let re = Regex::new(
r"^Dialogue:\s(?P\d+),(?P\d+:\d+:\d+\.\d+),(?P\d+:\d+:\d+\.\d+),",
)
.unwrap();
- // chrono panics if we try to format NaiveTime with `%2f` and the nano seconds has more than 2
- // digits so them have to be reduced manually to avoid the panic
- fn format_naive_time(native_time: NaiveTime) -> String {
- let formatted_time = native_time.format("%f").to_string();
- format!(
- "{}.{}",
- native_time.format("%T"),
- if formatted_time.len() <= 2 {
- native_time.format("%2f").to_string()
- } else {
- formatted_time.split_at(2).0.parse().unwrap()
- }
- )
- .split_off(1) // <- in the ASS spec, the hour has only one digit
- }
-
let mut entries = (vec![], vec![]);
let mut as_lines: Vec = String::from_utf8_lossy(raw.as_slice())
@@ -1158,12 +1344,18 @@ fn fix_subtitles(raw: &mut Vec, max_length: NaiveTime) {
if line.trim() == "[Script Info]" {
line.push_str("\nScaledBorderAndShadow: yes")
} else if let Some(capture) = re.captures(line) {
- let mut start = capture.name("start").map_or(NaiveTime::default(), |s| {
- NaiveTime::parse_from_str(s.as_str(), "%H:%M:%S.%f").unwrap()
- });
- let mut end = capture.name("end").map_or(NaiveTime::default(), |e| {
- NaiveTime::parse_from_str(e.as_str(), "%H:%M:%S.%f").unwrap()
- });
+ let mut start = capture
+ .name("start")
+ .map_or(NaiveTime::default(), |s| {
+ NaiveTime::parse_from_str(s.as_str(), "%H:%M:%S.%f").unwrap()
+ })
+ .signed_duration_since(NaiveTime::MIN);
+ let mut end = capture
+ .name("end")
+ .map_or(NaiveTime::default(), |e| {
+ NaiveTime::parse_from_str(e.as_str(), "%H:%M:%S.%f").unwrap()
+ })
+ .signed_duration_since(NaiveTime::MIN);
if start > max_length || end > max_length {
let layer = capture
@@ -1183,8 +1375,8 @@ fn fix_subtitles(raw: &mut Vec, max_length: NaiveTime) {
format!(
"Dialogue: {},{},{},",
layer,
- format_naive_time(start),
- format_naive_time(end)
+ format_time_delta(start),
+ format_time_delta(end)
),
)
.to_string()
@@ -1209,13 +1401,10 @@ fn fix_subtitles(raw: &mut Vec, max_length: NaiveTime) {
fn write_ffmpeg_chapters(
file: &mut fs::File,
- video_len: NaiveTime,
+ video_len: TimeDelta,
events: &mut Vec<(&str, &SkipEventsEvent)>,
) -> Result<()> {
- let video_len = video_len
- .signed_duration_since(NaiveTime::MIN)
- .num_milliseconds() as f32
- / 1000.0;
+ let video_len = video_len.num_milliseconds() as f32 / 1000.0;
events.sort_by(|(_, event_a), (_, event_b)| event_a.start.total_cmp(&event_b.start));
writeln!(file, ";FFMETADATA1")?;
@@ -1332,3 +1521,149 @@ async fn ffmpeg_progress(
Ok(())
}
+
+struct SyncVideo {
+ path: TempPath,
+ length: TimeDelta,
+ available_frames: u64,
+ idx: usize,
+}
+
+fn sync_videos(mut sync_videos: Vec, value: f64) -> Result>> {
+ let mut result = HashMap::new();
+ let hasher = HasherConfig::new().to_hasher();
+ let start_frame = 50;
+
+ sync_videos.sort_by_key(|sv| sv.length);
+
+ let sync_base = sync_videos.remove(0);
+ let sync_hashes = extract_frame_hashes(&sync_base.path, start_frame, 100, &hasher)?;
+
+ for sync_video in sync_videos {
+ let mut highest_frame_match = f64::INFINITY;
+ let mut frame = start_frame;
+ let mut hashes = vec![];
+
+ loop {
+ if frame == sync_video.available_frames {
+ debug!(
+ "Failed to sync videos, end of stream {} reached (highest frame match: {})",
+ sync_video.idx + 1,
+ highest_frame_match
+ );
+ return Ok(None);
+ }
+
+ hashes.drain(0..(hashes.len() as i32 - sync_hashes.len() as i32).max(0) as usize);
+ hashes.extend(extract_frame_hashes(
+ &sync_video.path,
+ frame,
+ 300 - hashes.len() as u64,
+ &hasher,
+ )?);
+
+ let check_frame_windows_result = check_frame_windows(&sync_hashes, &hashes);
+ if let Some(offset) = check_frame_windows_result
+ .iter()
+ .enumerate()
+ .find_map(|(i, cfw)| (*cfw <= value).then_some(i))
+ {
+ result.insert(sync_video.idx, frame + offset as u64 - start_frame);
+ break;
+ } else {
+ let curr_highest_frame_match = *check_frame_windows_result
+ .iter()
+ .min_by(|a, b| a.total_cmp(b))
+ .unwrap();
+ if curr_highest_frame_match < highest_frame_match {
+ highest_frame_match = curr_highest_frame_match
+ }
+ }
+
+ frame = (frame + 300 - sync_hashes.len() as u64).min(sync_video.available_frames)
+ }
+ }
+
+ Ok(Some(result))
+}
+
+fn extract_frame_hashes(
+ input_file: &Path,
+ start_frame: u64,
+ frame_count: u64,
+ hasher: &Hasher,
+) -> Result> {
+ let frame_dir = tempdir(format!(
+ "{}_sync_frames",
+ input_file
+ .file_name()
+ .unwrap_or_default()
+ .to_string_lossy()
+ .trim_end_matches(
+ &input_file
+ .file_stem()
+ .unwrap_or_default()
+ .to_string_lossy()
+ .to_string()
+ )
+ ))?;
+ let extract_output = Command::new("ffmpeg")
+ .arg("-hide_banner")
+ .arg("-y")
+ .args(["-i", input_file.to_string_lossy().to_string().as_str()])
+ .args([
+ "-vf",
+ format!(
+ r#"select=between(n\,{}\,{}),setpts=PTS-STARTPTS"#,
+ start_frame,
+ start_frame + frame_count
+ )
+ .as_str(),
+ ])
+ .args(["-vframes", frame_count.to_string().as_str()])
+ .arg(format!("{}/%03d.jpg", frame_dir.path().to_string_lossy()))
+ .output()?;
+ if !extract_output.status.success() {
+ bail!(
+ "{}",
+ String::from_utf8_lossy(extract_output.stderr.as_slice())
+ )
+ }
+
+ let mut hashes = vec![];
+ for file in frame_dir.path().read_dir()? {
+ let file = file?;
+ let img = image::open(file.path())?;
+ hashes.push(hasher.hash_image(&img))
+ }
+ Ok(hashes)
+}
+
+fn check_frame_windows(base_hashes: &[ImageHash], check_hashes: &[ImageHash]) -> Vec {
+ let mut results = vec![];
+
+ for i in 0..(check_hashes.len() - base_hashes.len()) {
+ let check_window = &check_hashes[i..(base_hashes.len() + i)];
+ let sum = std::iter::zip(base_hashes, check_window)
+ .map(|(a, b)| a.dist(b))
+ .sum::();
+ results.push(sum as f64 / check_window.len() as f64);
+ }
+ results
+}
+
+fn format_time_delta(time_delta: TimeDelta) -> String {
+ let hours = time_delta.num_hours();
+ let minutes = time_delta.num_minutes() - time_delta.num_hours() * 60;
+ let seconds = time_delta.num_seconds() - time_delta.num_minutes() * 60;
+ let milliseconds = time_delta.num_milliseconds() - time_delta.num_seconds() * 1000;
+
+ format!(
+ "{}:{:0>2}:{:0>2}.{:0>3}",
+ hours, minutes, seconds, milliseconds
+ )
+}
+
+fn len_from_segments(segments: &[StreamSegment]) -> TimeDelta {
+ TimeDelta::milliseconds(segments.iter().map(|s| s.length.as_millis()).sum::() as i64)
+}
diff --git a/crunchy-cli-core/src/utils/os.rs b/crunchy-cli-core/src/utils/os.rs
index e57c4d0..b65abc2 100644
--- a/crunchy-cli-core/src/utils/os.rs
+++ b/crunchy-cli-core/src/utils/os.rs
@@ -7,7 +7,7 @@ use std::pin::Pin;
use std::process::{Command, Stdio};
use std::task::{Context, Poll};
use std::{env, fs, io};
-use tempfile::{Builder, NamedTempFile, TempPath};
+use tempfile::{Builder, NamedTempFile, TempDir, TempPath};
use tokio::io::{AsyncRead, ReadBuf};
pub fn has_ffmpeg() -> bool {
@@ -31,7 +31,7 @@ pub fn temp_directory() -> PathBuf {
}
/// Any tempfile should be created with this function. The prefix and directory of every file
-/// created with this method stays the same which is helpful to query all existing tempfiles and
+/// created with this function stays the same which is helpful to query all existing tempfiles and
/// e.g. remove them in a case of ctrl-c. Having one function also good to prevent mistakes like
/// setting the wrong prefix if done manually.
pub fn tempfile>(suffix: S) -> io::Result {
@@ -46,6 +46,22 @@ pub fn tempfile>(suffix: S) -> io::Result {
Ok(tempfile)
}
+/// Any tempdir should be created with this function. The prefix and directory of every directory
+/// created with this function stays the same which is helpful to query all existing tempdirs and
+/// e.g. remove them in a case of ctrl-c. Having one function also good to prevent mistakes like
+/// setting the wrong prefix if done manually.
+pub fn tempdir>(suffix: S) -> io::Result {
+ let tempdir = Builder::default()
+ .prefix(".crunchy-cli_")
+ .suffix(suffix.as_ref())
+ .tempdir_in(temp_directory())?;
+ debug!(
+ "Created temporary directory: {}",
+ tempdir.path().to_string_lossy()
+ );
+ Ok(tempdir)
+}
+
pub fn cache_dir>(name: S) -> io::Result {
let cache_dir = temp_directory().join(format!(".crunchy-cli_{}_cache", name.as_ref()));
fs::create_dir_all(&cache_dir)?;
diff --git a/crunchy-cli-core/src/utils/video.rs b/crunchy-cli-core/src/utils/video.rs
index 7f7d73e..07f6e76 100644
--- a/crunchy-cli-core/src/utils/video.rs
+++ b/crunchy-cli-core/src/utils/video.rs
@@ -2,7 +2,7 @@ use anyhow::{bail, Result};
use crunchyroll_rs::media::{Resolution, Stream, StreamData};
use crunchyroll_rs::Locale;
-pub async fn variant_data_from_stream(
+pub async fn stream_data_from_stream(
stream: &Stream,
resolution: &Resolution,
subtitle: Option,
From 771594a2317df3c0e33da82c711e57bec80be93e Mon Sep 17 00:00:00 2001
From: bytedream
Date: Mon, 8 Apr 2024 14:03:30 +0200
Subject: [PATCH 15/82] Remove hardcoded pixel format (#352)
---
crunchy-cli-core/src/utils/download.rs | 4 ----
1 file changed, 4 deletions(-)
diff --git a/crunchy-cli-core/src/utils/download.rs b/crunchy-cli-core/src/utils/download.rs
index fe0e84a..122d436 100644
--- a/crunchy-cli-core/src/utils/download.rs
+++ b/crunchy-cli-core/src/utils/download.rs
@@ -796,10 +796,6 @@ impl Downloader {
command_args.extend([format!("-disposition:s:s:{}", i), "forced".to_string()])
}
- // manually specifying the color model for the output file. this must be done manually
- // because some Crunchyroll episodes are encoded in a way that ffmpeg cannot re-encode
- command_args.extend(["-pix_fmt".to_string(), "yuv420p".to_string()]);
-
command_args.extend(output_presets);
if let Some(output_format) = self.output_format {
command_args.extend(["-f".to_string(), output_format]);
From 77103ff1f1f904707721930846782785d76492f1 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Mon, 8 Apr 2024 14:18:10 +0200
Subject: [PATCH 16/82] Update dependencies and version
---
Cargo.lock | 26 +++++++++++++-------------
Cargo.toml | 2 +-
crunchy-cli-core/Cargo.toml | 4 ++--
3 files changed, 16 insertions(+), 16 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index c1f24f4..c0d6f44 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -199,9 +199,9 @@ checksum = "514de17de45fdb8dc022b1a7975556c53c86f9f0aa5f534b98977b171857c2c9"
[[package]]
name = "cc"
-version = "1.0.90"
+version = "1.0.91"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8cd6604a82acf3039f1144f54b8eb34e91ffba622051189e71b781822d5ee1f5"
+checksum = "1fd97381a8cc6493395a5afc4c691c1084b3768db713b73aa215217aa245d153"
[[package]]
name = "cfg-if"
@@ -354,7 +354,7 @@ checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f"
[[package]]
name = "crunchy-cli"
-version = "3.3.5"
+version = "3.4.0"
dependencies = [
"chrono",
"clap",
@@ -367,7 +367,7 @@ dependencies = [
[[package]]
name = "crunchy-cli-core"
-version = "3.3.5"
+version = "3.4.0"
dependencies = [
"anyhow",
"async-speed-limit",
@@ -404,9 +404,9 @@ dependencies = [
[[package]]
name = "crunchyroll-rs"
-version = "0.10.3"
+version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2eae6c95ec38118d02ef2ca738e245d8afc404f05e502051013dc37e0295bb32"
+checksum = "2ec02ad9896fe71bfc53c48e8b8949aa81ab7f3cb9ff31fd197565d6cd7922ea"
dependencies = [
"async-trait",
"chrono",
@@ -429,9 +429,9 @@ dependencies = [
[[package]]
name = "crunchyroll-rs-internal"
-version = "0.10.3"
+version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2f589713700c948db9a976d3f83816ab12efebdf759044a7bb963dad62000c12"
+checksum = "24d7cdd1fa6a6303a56f45041060641d6b4446e8065a91f1bcb8aa4a8f1f483c"
dependencies = [
"darling",
"quote",
@@ -722,9 +722,9 @@ dependencies = [
[[package]]
name = "getrandom"
-version = "0.2.12"
+version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "190092ea657667030ac6a35e305e62fc4dd69fd98ac98631e5d3a2b1575a12b5"
+checksum = "94b22e06ecb0110981051723910cbf0b5f5e09a2062dd7663334ee79a9d1286c"
dependencies = [
"cfg-if",
"js-sys",
@@ -1602,11 +1602,11 @@ dependencies = [
[[package]]
name = "rustls-pemfile"
-version = "2.1.1"
+version = "2.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f48172685e6ff52a556baa527774f61fcaa884f59daf3375c62a3f1cd2549dab"
+checksum = "29993a25686778eb88d4189742cd713c9bce943bc54251a33509dc63cbacf73d"
dependencies = [
- "base64 0.21.7",
+ "base64 0.22.0",
"rustls-pki-types",
]
diff --git a/Cargo.toml b/Cargo.toml
index c49244b..2bdc3bb 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli"
authors = ["Crunchy Labs Maintainers"]
-version = "3.3.5"
+version = "3.4.0"
edition = "2021"
license = "MIT"
diff --git a/crunchy-cli-core/Cargo.toml b/crunchy-cli-core/Cargo.toml
index bd47aba..1bda9e1 100644
--- a/crunchy-cli-core/Cargo.toml
+++ b/crunchy-cli-core/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli-core"
authors = ["Crunchy Labs Maintainers"]
-version = "3.3.5"
+version = "3.4.0"
edition = "2021"
license = "MIT"
@@ -16,7 +16,7 @@ anyhow = "1.0"
async-speed-limit = "0.4"
clap = { version = "4.5", features = ["derive", "string"] }
chrono = "0.4"
-crunchyroll-rs = { version = "0.10.3", features = ["experimental-stabilizations", "tower"] }
+crunchyroll-rs = { version = "0.10.4", features = ["experimental-stabilizations", "tower"] }
ctrlc = "3.4"
dialoguer = { version = "0.11", default-features = false }
dirs = "5.0"
From 18534b259b835b74631fca5f19ff6da7e2652afe Mon Sep 17 00:00:00 2001
From: bytedream
Date: Mon, 8 Apr 2024 14:34:50 +0200
Subject: [PATCH 17/82] Remove deprecated {resolution} output format option
---
crunchy-cli-core/src/archive/command.rs | 9 ---------
crunchy-cli-core/src/download/command.rs | 9 ---------
crunchy-cli-core/src/utils/format.rs | 4 ----
3 files changed, 22 deletions(-)
diff --git a/crunchy-cli-core/src/archive/command.rs b/crunchy-cli-core/src/archive/command.rs
index 64ad66a..234bf68 100644
--- a/crunchy-cli-core/src/archive/command.rs
+++ b/crunchy-cli-core/src/archive/command.rs
@@ -242,15 +242,6 @@ impl Execute for Archive {
warn!("Using `--sync-start` without `--ffmpeg-preset` might produce worse sync results than with `--ffmpeg-preset` set")
}
- if self.output.contains("{resolution}")
- || self
- .output_specials
- .as_ref()
- .map_or(false, |os| os.contains("{resolution}"))
- {
- warn!("The '{{resolution}}' format option is deprecated and will be removed in a future version. Please use '{{width}}' and '{{height}}' instead")
- }
-
self.audio = all_locale_in_locales(self.audio.clone());
self.subtitle = all_locale_in_locales(self.subtitle.clone());
diff --git a/crunchy-cli-core/src/download/command.rs b/crunchy-cli-core/src/download/command.rs
index fd29030..58055bd 100644
--- a/crunchy-cli-core/src/download/command.rs
+++ b/crunchy-cli-core/src/download/command.rs
@@ -187,15 +187,6 @@ impl Execute for Download {
}
}
- if self.output.contains("{resolution}")
- || self
- .output_specials
- .as_ref()
- .map_or(false, |os| os.contains("{resolution}"))
- {
- warn!("The '{{resolution}}' format option is deprecated and will be removed in a future version. Please use '{{width}}' and '{{height}}' instead")
- }
-
if let Some(language_tagging) = &self.language_tagging {
self.audio = resolve_locales(&[self.audio.clone()]).remove(0);
self.subtitle = self
diff --git a/crunchy-cli-core/src/utils/format.rs b/crunchy-cli-core/src/utils/format.rs
index df79d64..17f324f 100644
--- a/crunchy-cli-core/src/utils/format.rs
+++ b/crunchy-cli-core/src/utils/format.rs
@@ -446,10 +446,6 @@ impl Format {
universal,
),
)
- .replace(
- "{resolution}",
- &sanitize(self.resolution.to_string(), true, universal),
- )
.replace(
"{width}",
&sanitize(self.resolution.width.to_string(), true, universal),
From 0115730d608c68d4b54095166d1fabafbf02c476 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Tue, 9 Apr 2024 18:36:18 +0200
Subject: [PATCH 18/82] Add archive `--sync-start` flag documentation to README
---
README.md | 12 +++++++++++-
crunchy-cli-core/src/archive/command.rs | 23 ++++++++++++-----------
2 files changed, 23 insertions(+), 12 deletions(-)
diff --git a/README.md b/README.md
index 5463e30..b30852b 100644
--- a/README.md
+++ b/README.md
@@ -468,7 +468,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
- Merge behavior
- Due to censorship, some episodes have multiple lengths for different languages.
+ Due to censorship or additional intros, some episodes have multiple lengths for different languages.
In the best case, when multiple audio & subtitle tracks are used, there is only one *video* track and all other languages can be stored as audio-only.
But, as said, this is not always the case.
With the `-m` / `--merge` flag you can define the behaviour when an episodes' video tracks differ in length.
@@ -492,6 +492,16 @@ The `archive` command lets you download episodes with multiple audios and subtit
Default are `200` milliseconds.
+- Sync start
+
+ If you want that all videos of the same episode should start at the same time and `--merge` doesn't fit your needs (e.g. one video has an intro, all other doesn't), you might consider using the `--sync-start`.
+ It tries to sync the timing of all downloaded audios to match one video.
+ This is done by downloading the first few segments/frames of all video tracks that differ in length and comparing them frame by frame.
+ The flag takes an optional value determines how accurate the syncing is, generally speaking everything over 15 begins to be more inaccurate and everything below 6 is too accurate (and won't succeed).
+ When the syncing fails, the command is continued as if `--sync-start` wasn't provided for this episode.
+
+ Default is `7.5`.
+
- Language tagging
You can force the usage of a specific language tagging in the output file with the `--language-tagging` flag.
diff --git a/crunchy-cli-core/src/archive/command.rs b/crunchy-cli-core/src/archive/command.rs
index 234bf68..1c18133 100644
--- a/crunchy-cli-core/src/archive/command.rs
+++ b/crunchy-cli-core/src/archive/command.rs
@@ -89,17 +89,6 @@ pub struct Archive {
#[arg(value_parser = crate::utils::clap::clap_parse_resolution)]
pub(crate) resolution: Resolution,
- #[arg(help = "Tries to sync the timing of all downloaded audios to match one video")]
- #[arg(
- long_help = "Tries to sync the timing of all downloaded audios to match one video. \
- This is done by downloading the first few segments/frames of all video tracks that differ in length and comparing them frame by frame. \
- The value of this flag determines how accurate the syncing is, generally speaking everything over 15 begins to be more inaccurate and everything below 6 is too accurate (and won't succeed). \
- If you want to provide a custom value to this flag, you have to set it with an equals (e.g. `--sync-start=10` instead of `--sync-start 10`). \
- When the syncing fails, the command is continued as if `--sync-start` wasn't provided for this episode
- "
- )]
- #[arg(long, require_equals = true, num_args = 0..=1, default_missing_value = "7.5")]
- pub(crate) sync_start: Option,
#[arg(
help = "Sets the behavior of the stream merging. Valid behaviors are 'auto', 'audio' and 'video'"
)]
@@ -121,6 +110,18 @@ pub struct Archive {
help = "Specified which language tagging the audio and subtitle tracks and language specific format options should have. \
Valid options are: 'default' (how Crunchyroll uses it internally), 'ietf' (according to the IETF standard)"
)]
+ #[arg(help = "Tries to sync the timing of all downloaded audios to match one video")]
+ #[arg(
+ long_help = "Tries to sync the timing of all downloaded audios to match one video. \
+ This is done by downloading the first few segments/frames of all video tracks that differ in length and comparing them frame by frame. \
+ The value of this flag determines how accurate the syncing is, generally speaking everything over 15 begins to be more inaccurate and everything below 6 is too accurate (and won't succeed). \
+ If you want to provide a custom value to this flag, you have to set it with an equals (e.g. `--sync-start=10` instead of `--sync-start 10`). \
+ When the syncing fails, the command is continued as if `--sync-start` wasn't provided for this episode
+ "
+ )]
+ #[arg(long, require_equals = true, num_args = 0..=1, default_missing_value = "7.5")]
+ pub(crate) sync_start: Option,
+
#[arg(
long_help = "Specified which language tagging the audio and subtitle tracks and language specific format options should have. \
Valid options are: 'default' (how Crunchyroll uses it internally), 'ietf' (according to the IETF standard; you might run in issues as there are multiple locales which resolve to the same IETF language code, e.g. 'es-LA' and 'es-ES' are both resolving to 'es')"
From a73773ce1deb26e8cf08fe6b7b6f358cdca9e673 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Tue, 9 Apr 2024 18:55:15 +0200
Subject: [PATCH 19/82] Add id to every flag in README
---
README.md | 98 ++++++++++++++++++++++++++++---------------------------
1 file changed, 50 insertions(+), 48 deletions(-)
diff --git a/README.md b/README.md
index b30852b..09db003 100644
--- a/README.md
+++ b/README.md
@@ -116,13 +116,13 @@ crunchy-cli requires you to log in.
Though you can use a non-premium account, you will not have access to premium content without a subscription.
You can authenticate with your credentials (email:password) or by using a refresh token.
-- Credentials
+- Credentials
```shell
$ crunchy-cli --credentials "email:password"
```
-- Refresh Token
+- Refresh Token
To obtain a refresh token, you have to log in at [crunchyroll.com](https://www.crunchyroll.com/) and extract the `etp_rt` cookie.
The easiest way to get it is via a browser extension which lets you export your cookies, like [Cookie-Editor](https://cookie-editor.cgagnier.ca/) ([Firefox](https://addons.mozilla.org/en-US/firefox/addon/cookie-editor/) / [Chrome](https://chrome.google.com/webstore/detail/cookie-editor/hlkenndednhfkekhgcdicdfddnkalmdm)).
@@ -132,7 +132,7 @@ You can authenticate with your credentials (email:password) or by using a refres
$ crunchy-cli --etp-rt "4ebf1690-53a4-491a-a2ac-488309120f5d"
```
-- Stay Anonymous
+- Stay Anonymous
Login without an account (you won't be able to access premium content):
@@ -144,7 +144,7 @@ You can authenticate with your credentials (email:password) or by using a refres
You can set specific settings which will be
-- Verbose output
+- Verbose output
If you want to include debug information in the output, use the `-v` / `--verbose` flag to show it.
@@ -152,9 +152,9 @@ You can set specific settings which will be
$ crunchy-cli -v
```
- This flag can't be used with `-q` / `--quiet`.
+ This flag can't be used in combination with `-q` / `--quiet`.
-- Quiet output
+- Quiet output
If you want to hide all output, use the `-q` / `--quiet` flag to do so.
This is especially useful if you want to pipe the output video to an external program (like a video player).
@@ -163,7 +163,9 @@ You can set specific settings which will be
$ crunchy-cli -q
```
-- Language
+ This flag can't be used in combination with `-v` / `--verbose`.
+
+- Language
By default, the resulting metadata like title or description are shown in your system language (if Crunchyroll supports it, else in English).
If you want to show the results in another language, use the `--lang` flag to set it.
@@ -172,7 +174,7 @@ You can set specific settings which will be
$ crunchy-cli --lang de-DE
```
-- Experimental fixes
+- Experimental fixes
Crunchyroll constantly changes and breaks its services or just delivers incorrect answers.
The `--experimental-fixes` flag tries to fix some of those issues.
@@ -184,7 +186,7 @@ You can set specific settings which will be
For an overview which parts this flag affects, see the [documentation](https://docs.rs/crunchyroll-rs/latest/crunchyroll_rs/crunchyroll/struct.CrunchyrollBuilder.html) of the underlying Crunchyroll library, all functions beginning with `stabilization_` are applied.
-- Proxy
+- Proxy
The `--proxy` flag supports https and socks5 proxies to route all your traffic through.
This may be helpful to bypass the geo-restrictions Crunchyroll has on certain series.
@@ -197,7 +199,7 @@ You can set specific settings which will be
Make sure that proxy can either forward TLS requests, which is needed to bypass the (cloudflare) bot protection, or that it is configured so that the proxy can bypass the protection itself.
-- User Agent
+- User Agent
There might be cases where a custom user agent is necessary, e.g. to bypass the cloudflare bot protection (#104).
In such cases, the `--user-agent` flag can be used to set a custom user agent.
@@ -208,7 +210,7 @@ You can set specific settings which will be
Default is the user agent, defined in the underlying [library](https://github.com/crunchy-labs/crunchyroll-rs).
-- Speed limit
+- Speed limit
If you want to limit how fast requests/downloads should be, you can use the `--speed-limit` flag. Allowed units are `B` (bytes), `KB` (kilobytes) and `MB` (megabytes).
@@ -247,7 +249,7 @@ The `download` command lets you download episodes with a specific audio language
**Options**
-- Audio language
+- Audio language
Set the audio language with the `-a` / `--audio` flag.
This only works if the url points to a series since episode urls are language specific.
@@ -258,7 +260,7 @@ The `download` command lets you download episodes with a specific audio language
Default is your system locale. If not supported by Crunchyroll, `en-US` (American English) is the default.
-- Subtitle language
+- Subtitle language
Besides the audio, you can specify the subtitle language by using the `-s` / `--subtitle` flag.
In formats that support it (.mp4, .mov and .mkv ), subtitles are stored as soft-subs. All other formats are hardsubbed: the subtitles will be burned into the video track (cf. [hardsub](https://www.urbandictionary.com/define.php?term=hardsub)) and thus can not be turned off.
@@ -269,7 +271,7 @@ The `download` command lets you download episodes with a specific audio language
Default is none.
-- Output template
+- Output template
Define an output template by using the `-o` / `--output` flag.
@@ -279,7 +281,7 @@ The `download` command lets you download episodes with a specific audio language
Default is `{title}.mp4`. See the [Template Options section](#output-template-options) below for more options.
-- Output template for special episodes
+- Output template for special episodes
Define an output template which only gets used when the episode is a special (episode number is 0 or has non-zero decimal places) by using the `--output-special` flag.
@@ -289,7 +291,7 @@ The `download` command lets you download episodes with a specific audio language
Default is the template, set by the `-o` / `--output` flag. See the [Template Options section](#output-template-options) below for more options.
-- Universal output
+- Universal output
The output template options can be forced to get sanitized via the `--universal-output` flag to be valid across all supported operating systems (Windows has a lot of characters which aren't allowed in filenames...).
@@ -297,7 +299,7 @@ The `download` command lets you download episodes with a specific audio language
$ crunchy-cli download --universal-output -o https://www.crunchyroll.com/watch/G7PU4XD48/tales-veldoras-journal-2
```
-- Resolution
+- Resolution
The resolution for videos can be set via the `-r` / `--resolution` flag.
@@ -307,7 +309,7 @@ The `download` command lets you download episodes with a specific audio language
Default is `best`.
-- Language tagging
+- Language tagging
You can force the usage of a specific language tagging in the output file with the `--language-tagging` flag.
This might be useful as some video players doesn't recognize the language tagging Crunchyroll uses internally.
@@ -316,7 +318,7 @@ The `download` command lets you download episodes with a specific audio language
$ crunchy-cli download --language-tagging ietf https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome
```
-- FFmpeg Preset
+- FFmpeg Preset
You can specify specific built-in presets with the `--ffmpeg-preset` flag to convert videos to a specific coding while downloading.
Multiple predefined presets how videos should be encoded (h264, h265, av1, ...) are available, you can see them with `crunchy-cli download --help`.
@@ -326,7 +328,7 @@ The `download` command lets you download episodes with a specific audio language
$ crunchy-cli download --ffmpeg-preset av1-lossless https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome
```
-- FFmpeg threads
+- FFmpeg threads
If you want to manually set how many threads FFmpeg should use, you can use the `--ffmpeg-threads` flag. This does not work with every codec/preset and is skipped entirely when specifying custom ffmpeg output arguments instead of a preset for `--ffmpeg-preset`.
@@ -334,7 +336,7 @@ The `download` command lets you download episodes with a specific audio language
$ crunchy-cli download --ffmpeg-threads 4 https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome
```
-- Skip existing
+- Skip existing
If you re-download a series but want to skip episodes you've already downloaded, the `--skip-existing` flag skips the already existing/downloaded files.
@@ -342,7 +344,7 @@ The `download` command lets you download episodes with a specific audio language
$ crunchy-cli download --skip-existing https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx
```
-- Skip specials
+- Skip specials
If you doesn't want to download special episodes, use the `--skip-specials` flag to skip the download of them.
@@ -350,7 +352,7 @@ The `download` command lets you download episodes with a specific audio language
$ crunchy-cli download --skip-specials https://www.crunchyroll.com/series/GYZJ43JMR/that-time-i-got-reincarnated-as-a-slime[S2]
```
-- Include chapters
+- Include chapters
Crunchyroll sometimes provide information about skippable events like the intro or credits.
These information can be stored as chapters in the resulting video file via the `--include-chapters` flag.
@@ -359,7 +361,7 @@ The `download` command lets you download episodes with a specific audio language
$ crunchy-cli download --include-chapters https://www.crunchyroll.com/watch/G0DUND0K2/the-journeys-end
```
-- Yes
+- Yes
Sometimes different seasons have the same season number (e.g. Sword Art Online Alicization and Alicization War of Underworld are both marked as season 3), in such cases an interactive prompt is shown which needs user further user input to decide which season to download.
The `--yes` flag suppresses this interactive prompt and just downloads all seasons.
@@ -370,7 +372,7 @@ The `download` command lets you download episodes with a specific audio language
If you've passed the `-q` / `--quiet` [global flag](#global-settings), this flag is automatically set.
-- Force hardsub
+- Force hardsub
If you want to burn-in the subtitles, even if the output format/container supports soft-subs (e.g. `.mp4`), use the `--force-hardsub` flag to do so.
@@ -378,7 +380,7 @@ The `download` command lets you download episodes with a specific audio language
$ crunchy-cli download --force-hardsub -s en-US https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome
```
-- Threads
+- Threads
To increase the download speed, video segments are downloaded simultaneously by creating multiple threads.
If you want to manually specify how many threads to use when downloading, do this with the `-t` / `--threads` flag.
@@ -406,7 +408,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
**Options**
-- Audio languages
+- Audio languages
Set the audio language with the `-a` / `--audio` flag. Can be used multiple times.
@@ -416,7 +418,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
Default is your system locale (if not supported by Crunchyroll, `en-US` (American English) and `ja-JP` (Japanese) are used).
-- Subtitle languages
+- Subtitle languages
Besides the audio, you can specify the subtitle language by using the `-s` / `--subtitle` flag.
@@ -426,7 +428,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
Default is `all` subtitles.
-- Output template
+- Output template
Define an output template by using the `-o` / `--output` flag.
_crunchy-cli_ exclusively uses the [`.mkv`](https://en.wikipedia.org/wiki/Matroska) container format, because of its ability to store multiple audio, video and subtitle tracks at once.
@@ -437,7 +439,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
Default is `{title}.mkv`. See the [Template Options section](#output-template-options) below for more options.
-- Output template for special episodes
+- Output template for special episodes
Define an output template which only gets used when the episode is a special (episode number is 0 or has non-zero decimal places) by using the `--output-special` flag.
_crunchy-cli_ exclusively uses the [`.mkv`](https://en.wikipedia.org/wiki/Matroska) container format, because of its ability to store multiple audio, video and subtitle tracks at once.
@@ -448,7 +450,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
Default is the template, set by the `-o` / `--output` flag. See the [Template Options section](#output-template-options) below for more options.
-- Universal output
+- Universal output
The output template options can be forced to get sanitized via the `--universal-output` flag to be valid across all supported operating systems (Windows has a lot of characters which aren't allowed in filenames...).
@@ -456,7 +458,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
$ crunchy-cli archive --universal-output -o https://www.crunchyroll.com/watch/G7PU4XD48/tales-veldoras-journal-2
```
-- Resolution
+- Resolution
The resolution for videos can be set via the `-r` / `--resolution` flag.
@@ -466,7 +468,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
Default is `best`.
-- Merge behavior
+- Merge behavior
Due to censorship or additional intros, some episodes have multiple lengths for different languages.
In the best case, when multiple audio & subtitle tracks are used, there is only one *video* track and all other languages can be stored as audio-only.
@@ -481,7 +483,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
Default is `auto`.
-- Merge auto tolerance
+- Merge auto tolerance
Sometimes two video tracks are downloaded with `--merge` set to `auto` even if they only differ some milliseconds in length which shouldn't be noticeable to the viewer.
To prevent this, you can specify a range in milliseconds with the `--merge-auto-tolerance` flag that only downloads one video if the length difference is in the given range.
@@ -492,7 +494,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
Default are `200` milliseconds.
-- Sync start
+- Sync start
If you want that all videos of the same episode should start at the same time and `--merge` doesn't fit your needs (e.g. one video has an intro, all other doesn't), you might consider using the `--sync-start`.
It tries to sync the timing of all downloaded audios to match one video.
@@ -502,7 +504,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
Default is `7.5`.
-- Language tagging
+- Language tagging
You can force the usage of a specific language tagging in the output file with the `--language-tagging` flag.
This might be useful as some video players doesn't recognize the language tagging Crunchyroll uses internally.
@@ -511,7 +513,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
$ crunchy-cli archive --language-tagging ietf https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx
```
-- FFmpeg Preset
+- FFmpeg Preset
You can specify specific built-in presets with the `--ffmpeg-preset` flag to convert videos to a specific coding while downloading.
Multiple predefined presets how videos should be encoded (h264, h265, av1, ...) are available, you can see them with `crunchy-cli archive --help`.
@@ -521,7 +523,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
$ crunchy-cli archive --ffmpeg-preset av1-lossless https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome
```
-- FFmpeg threads
+- FFmpeg threads
If you want to manually set how many threads FFmpeg should use, you can use the `--ffmpeg-threads` flag. This does not work with every codec/preset and is skipped entirely when specifying custom ffmpeg output arguments instead of a preset for `--ffmpeg-preset`.
@@ -529,7 +531,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
$ crunchy-cli archive --ffmpeg-threads 4 https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome
```
-- Default subtitle
+- Default subtitle
`--default-subtitle` Set which subtitle language is to be flagged as **default** and **forced**.
@@ -539,7 +541,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
Default is none.
-- Include fonts
+- Include fonts
You can include the fonts required by subtitles directly into the output file with the `--include-fonts` flag. This will use the embedded font for subtitles instead of the system font when playing the video in a video player which supports it.
@@ -547,7 +549,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
$ crunchy-cli archive --include-fonts https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx
```
-- Include chapters
+- Include chapters
Crunchyroll sometimes provide information about skippable events like the intro or credits.
These information can be stored as chapters in the resulting video file via the `--include-chapters` flag.
@@ -557,7 +559,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
$ crunchy-cli archive --include-chapters https://www.crunchyroll.com/watch/G0DUND0K2/the-journeys-end
```
-- Skip existing
+- Skip existing
If you re-download a series but want to skip episodes you've already downloaded, the `--skip-existing` flag skips the already existing/downloaded files.
@@ -565,7 +567,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
$ crunchy-cli archive --skip-existing https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx
```
-- Skip existing method
+- Skip existing method
By default, already existing files are determined by their name and the download of the corresponding episode is skipped.
But sometimes Crunchyroll adds dubs or subs to an already existing episode and these changes aren't recognized and `--skip-existing` just skips it.
@@ -575,7 +577,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
$ crunchy-cli archive --skip-existing-method audio --skip-existing-method video https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx
```
-- Skip specials
+- Skip specials
If you doesn't want to download special episodes, use the `--skip-specials` flag to skip the download of them.
@@ -583,7 +585,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
$ crunchy-cli archive --skip-specials https://www.crunchyroll.com/series/GYZJ43JMR/that-time-i-got-reincarnated-as-a-slime[S2]
```
-- Yes
+- Yes
Sometimes different seasons have the same season number (e.g. Sword Art Online Alicization and Alicization War of Underworld are both marked as season 3), in such cases an interactive prompt is shown which needs user further user input to decide which season to download.
The `--yes` flag suppresses this interactive prompt and just downloads all seasons.
@@ -594,7 +596,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
If you've passed the `-q` / `--quiet` [global flag](#global-settings), this flag is automatically set.
-- Threads
+- Threads
To increase the download speed, video segments are downloaded simultaneously by creating multiple threads.
If you want to manually specify how many threads to use when downloading, do this with the `-t` / `--threads` flag.
@@ -628,7 +630,7 @@ _Using this command with the `--anonymous` flag or a non-premium account may ret
**Options**
-- Audio
+- Audio
Set the audio language to search via the `--audio` flag. Can be used multiple times.
@@ -638,7 +640,7 @@ _Using this command with the `--anonymous` flag or a non-premium account may ret
Default is your system locale.
-- Result limit
+- Result limit
If your input is a search term instead of an url, you have multiple options to control which results to process.
The `--search-top-results-limit` flag sets the limit of top search results to process.
From ea39dcbc71b13048dcb27282527bab520ad42df1 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Tue, 9 Apr 2024 18:59:41 +0200
Subject: [PATCH 20/82] Embed chapters only to archive merge auto if
`--sync-start` flag is set
---
crunchy-cli-core/src/archive/command.rs | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)
diff --git a/crunchy-cli-core/src/archive/command.rs b/crunchy-cli-core/src/archive/command.rs
index 1c18133..cf0038f 100644
--- a/crunchy-cli-core/src/archive/command.rs
+++ b/crunchy-cli-core/src/archive/command.rs
@@ -585,7 +585,11 @@ async fn get_format(
audios: vec![(audio, single_format.audio.clone())],
subtitles,
metadata: DownloadFormatMetadata {
- skip_events: single_format.skip_events().await?,
+ skip_events: if archive.include_chapters {
+ single_format.skip_events().await?
+ } else {
+ None
+ },
},
},
));
From b9f5fadbb3ac3e6739129971e90e939d157122fa Mon Sep 17 00:00:00 2001
From: bytedream
Date: Tue, 9 Apr 2024 22:50:25 +0200
Subject: [PATCH 21/82] Fix archive `--language-tagging` sometimes causing
crash
---
crunchy-cli-core/src/archive/command.rs | 1 +
1 file changed, 1 insertion(+)
diff --git a/crunchy-cli-core/src/archive/command.rs b/crunchy-cli-core/src/archive/command.rs
index cf0038f..4210828 100644
--- a/crunchy-cli-core/src/archive/command.rs
+++ b/crunchy-cli-core/src/archive/command.rs
@@ -126,6 +126,7 @@ pub struct Archive {
long_help = "Specified which language tagging the audio and subtitle tracks and language specific format options should have. \
Valid options are: 'default' (how Crunchyroll uses it internally), 'ietf' (according to the IETF standard; you might run in issues as there are multiple locales which resolve to the same IETF language code, e.g. 'es-LA' and 'es-ES' are both resolving to 'es')"
)]
+ #[arg(long)]
#[arg(value_parser = LanguageTagging::parse)]
pub(crate) language_tagging: Option,
From 9e5feef4d41c1f3085c6009018c8b6c8f020cfa1 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Tue, 9 Apr 2024 22:58:28 +0200
Subject: [PATCH 22/82] Change archive `--sync-start` defaults
---
crunchy-cli-core/src/utils/download.rs | 36 ++++++++++++--------------
1 file changed, 17 insertions(+), 19 deletions(-)
diff --git a/crunchy-cli-core/src/utils/download.rs b/crunchy-cli-core/src/utils/download.rs
index 122d436..85fe3dc 100644
--- a/crunchy-cli-core/src/utils/download.rs
+++ b/crunchy-cli-core/src/utils/download.rs
@@ -1527,13 +1527,13 @@ struct SyncVideo {
fn sync_videos(mut sync_videos: Vec, value: f64) -> Result>> {
let mut result = HashMap::new();
- let hasher = HasherConfig::new().to_hasher();
- let start_frame = 50;
+ let hasher = HasherConfig::new().preproc_dct().to_hasher();
+ let start_frame = 300;
sync_videos.sort_by_key(|sv| sv.length);
let sync_base = sync_videos.remove(0);
- let sync_hashes = extract_frame_hashes(&sync_base.path, start_frame, 100, &hasher)?;
+ let sync_hashes = extract_frame_hashes(&sync_base.path, start_frame, 50, &hasher)?;
for sync_video in sync_videos {
let mut highest_frame_match = f64::INFINITY;
@@ -1558,22 +1558,20 @@ fn sync_videos(mut sync_videos: Vec, value: f64) -> Result =
+ check_frame_windows(&sync_hashes, &hashes)
+ .into_iter()
+ .enumerate()
+ .collect();
+ check_frame_windows_result.sort_by(|(_, a), (_, b)| a.partial_cmp(&b).unwrap());
+ if check_frame_windows_result[0].1 <= value {
+ result.insert(
+ sync_video.idx,
+ frame + check_frame_windows_result[0].0 as u64 - start_frame,
+ );
break;
- } else {
- let curr_highest_frame_match = *check_frame_windows_result
- .iter()
- .min_by(|a, b| a.total_cmp(b))
- .unwrap();
- if curr_highest_frame_match < highest_frame_match {
- highest_frame_match = curr_highest_frame_match
- }
+ } else if check_frame_windows_result[0].1 < highest_frame_match {
+ highest_frame_match = check_frame_windows_result[0].1
}
frame = (frame + 300 - sync_hashes.len() as u64).min(sync_video.available_frames)
@@ -1610,7 +1608,7 @@ fn extract_frame_hashes(
.args([
"-vf",
format!(
- r#"select=between(n\,{}\,{}),setpts=PTS-STARTPTS"#,
+ r#"select=between(n\,{}\,{}),setpts=PTS-STARTPTS,scale=-1:240"#,
start_frame,
start_frame + frame_count
)
From 0257fdea0d4128fe5c71c57c3196b93f4c133698 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Tue, 9 Apr 2024 23:00:01 +0200
Subject: [PATCH 23/82] Remove chapters if sync doesn't work
---
crunchy-cli-core/src/utils/download.rs | 8 +++++++-
1 file changed, 7 insertions(+), 1 deletion(-)
diff --git a/crunchy-cli-core/src/utils/download.rs b/crunchy-cli-core/src/utils/download.rs
index 85fe3dc..9c409d2 100644
--- a/crunchy-cli-core/src/utils/download.rs
+++ b/crunchy-cli-core/src/utils/download.rs
@@ -392,7 +392,13 @@ impl Downloader {
(*o as f64 / self.formats[0].video.0.fps().unwrap() * 1000.0) as i64,
)
})
- } else if !offset_pre_checked {
+ } else {
+ for format in &mut self.formats {
+ format.metadata.skip_events = None
+ }
+ }
+
+ if !offset_pre_checked {
warn!("Couldn't find reliable sync positions")
}
}
From 733d9f9787a9a71cad623b480cdb627b90b98cb1 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Wed, 10 Apr 2024 00:03:22 +0200
Subject: [PATCH 24/82] Update dependencies and version
---
Cargo.lock | 34 ++++++++++++++++++++++------------
Cargo.toml | 2 +-
crunchy-cli-core/Cargo.toml | 4 ++--
3 files changed, 25 insertions(+), 15 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index c0d6f44..d42e96c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -175,9 +175,9 @@ checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1"
[[package]]
name = "bumpalo"
-version = "3.15.4"
+version = "3.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7ff69b9dd49fd426c69a0db9fc04dd934cdb6645ff000864d98f7e2af8830eaa"
+checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c"
[[package]]
name = "bytemuck"
@@ -199,9 +199,9 @@ checksum = "514de17de45fdb8dc022b1a7975556c53c86f9f0aa5f534b98977b171857c2c9"
[[package]]
name = "cc"
-version = "1.0.91"
+version = "1.0.92"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1fd97381a8cc6493395a5afc4c691c1084b3768db713b73aa215217aa245d153"
+checksum = "2678b2e3449475e95b0aa6f9b506a28e61b3dc8996592b983695e8ebb58a8b41"
[[package]]
name = "cfg-if"
@@ -254,9 +254,9 @@ dependencies = [
[[package]]
name = "clap_complete"
-version = "4.5.1"
+version = "4.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "885e4d7d5af40bfb99ae6f9433e292feac98d452dcb3ec3d25dfe7552b77da8c"
+checksum = "dd79504325bf38b10165b02e89b4347300f855f273c4cb30c4a3209e6583275e"
dependencies = [
"clap",
]
@@ -354,7 +354,7 @@ checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f"
[[package]]
name = "crunchy-cli"
-version = "3.4.0"
+version = "3.4.1"
dependencies = [
"chrono",
"clap",
@@ -367,7 +367,7 @@ dependencies = [
[[package]]
name = "crunchy-cli-core"
-version = "3.4.0"
+version = "3.4.1"
dependencies = [
"anyhow",
"async-speed-limit",
@@ -404,9 +404,9 @@ dependencies = [
[[package]]
name = "crunchyroll-rs"
-version = "0.10.4"
+version = "0.10.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2ec02ad9896fe71bfc53c48e8b8949aa81ab7f3cb9ff31fd197565d6cd7922ea"
+checksum = "e8aa954631407844404a4b1fd2d957b101b8b8653f2884a726b4240175355234"
dependencies = [
"async-trait",
"chrono",
@@ -424,14 +424,15 @@ dependencies = [
"smart-default",
"tokio",
"tower-service",
+ "uuid",
"webpki-roots",
]
[[package]]
name = "crunchyroll-rs-internal"
-version = "0.10.4"
+version = "0.10.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "24d7cdd1fa6a6303a56f45041060641d6b4446e8065a91f1bcb8aa4a8f1f483c"
+checksum = "fc0b9e242c063f13048a53031b49a370c864db3fc6e12d573a8b297bd268b1c4"
dependencies = [
"darling",
"quote",
@@ -2170,6 +2171,15 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a"
+[[package]]
+name = "uuid"
+version = "1.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a183cf7feeba97b4dd1c0d46788634f6221d87fa961b305bed08c851829efcc0"
+dependencies = [
+ "getrandom",
+]
+
[[package]]
name = "vcpkg"
version = "0.2.15"
diff --git a/Cargo.toml b/Cargo.toml
index 2bdc3bb..7960a98 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli"
authors = ["Crunchy Labs Maintainers"]
-version = "3.4.0"
+version = "3.4.1"
edition = "2021"
license = "MIT"
diff --git a/crunchy-cli-core/Cargo.toml b/crunchy-cli-core/Cargo.toml
index 1bda9e1..d006831 100644
--- a/crunchy-cli-core/Cargo.toml
+++ b/crunchy-cli-core/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli-core"
authors = ["Crunchy Labs Maintainers"]
-version = "3.4.0"
+version = "3.4.1"
edition = "2021"
license = "MIT"
@@ -16,7 +16,7 @@ anyhow = "1.0"
async-speed-limit = "0.4"
clap = { version = "4.5", features = ["derive", "string"] }
chrono = "0.4"
-crunchyroll-rs = { version = "0.10.4", features = ["experimental-stabilizations", "tower"] }
+crunchyroll-rs = { version = "0.10.5", features = ["experimental-stabilizations", "tower"] }
ctrlc = "3.4"
dialoguer = { version = "0.11", default-features = false }
dirs = "5.0"
From dbbb445c5521afb0aaf2214d059014d7aedb2fa2 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Wed, 10 Apr 2024 00:19:12 +0200
Subject: [PATCH 25/82] Fix invalid 0% generate video file progress bar
---
crunchy-cli-core/src/utils/download.rs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/crunchy-cli-core/src/utils/download.rs b/crunchy-cli-core/src/utils/download.rs
index 9c409d2..daae9a5 100644
--- a/crunchy-cli-core/src/utils/download.rs
+++ b/crunchy-cli-core/src/utils/download.rs
@@ -1516,7 +1516,7 @@ async fn ffmpeg_progress(
// is manually set to 100% here
if frame < total_frames {
if let Some(p) = &progress {
- p.set_position(frame)
+ p.set_position(total_frames)
}
debug!("Processed frame [{}/{} 100%]", total_frames, total_frames);
}
From d7dac2acd44396067b35466dd59792adcd9fa504 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Thu, 11 Apr 2024 17:06:43 +0200
Subject: [PATCH 26/82] Update dependencies and version
---
Cargo.lock | 32 ++++++++++++++++----------------
Cargo.toml | 2 +-
crunchy-cli-core/Cargo.toml | 4 ++--
3 files changed, 19 insertions(+), 19 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index d42e96c..a0d0c8b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -91,9 +91,9 @@ dependencies = [
[[package]]
name = "anyhow"
-version = "1.0.81"
+version = "1.0.82"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0952808a6c2afd1aa8947271f3a60f1a6763c7b912d210184c5149b5cf147247"
+checksum = "f538837af36e6f6a9be0faa67f9a314f8119e4e4b5867c6ab40ed60360142519"
[[package]]
name = "async-speed-limit"
@@ -354,7 +354,7 @@ checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f"
[[package]]
name = "crunchy-cli"
-version = "3.4.1"
+version = "3.4.2"
dependencies = [
"chrono",
"clap",
@@ -367,7 +367,7 @@ dependencies = [
[[package]]
name = "crunchy-cli-core"
-version = "3.4.1"
+version = "3.4.2"
dependencies = [
"anyhow",
"async-speed-limit",
@@ -404,9 +404,9 @@ dependencies = [
[[package]]
name = "crunchyroll-rs"
-version = "0.10.5"
+version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e8aa954631407844404a4b1fd2d957b101b8b8653f2884a726b4240175355234"
+checksum = "93e6c52101e3afd7246a099478945ee01f0a5f07ee75cf44398a752e74b2bc90"
dependencies = [
"async-trait",
"chrono",
@@ -430,9 +430,9 @@ dependencies = [
[[package]]
name = "crunchyroll-rs-internal"
-version = "0.10.5"
+version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fc0b9e242c063f13048a53031b49a370c864db3fc6e12d573a8b297bd268b1c4"
+checksum = "6cc8e8098c9cc87b88c8026c2dbc3bbd68ba69d26ce04dbc89963e9c2e69c7cd"
dependencies = [
"darling",
"quote",
@@ -576,9 +576,9 @@ checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f"
[[package]]
name = "encoding_rs"
-version = "0.8.33"
+version = "0.8.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7268b386296a025e474d5140678f75d6de9493ae55a5d709eeb9dd08149945e1"
+checksum = "b45de904aa0b010bce2ab45264d0631681847fa7b6f2eaa7dab7619943bc4f59"
dependencies = [
"cfg-if",
]
@@ -1410,9 +1410,9 @@ dependencies = [
[[package]]
name = "quote"
-version = "1.0.35"
+version = "1.0.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef"
+checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7"
dependencies = [
"proc-macro2",
]
@@ -1917,9 +1917,9 @@ dependencies = [
[[package]]
name = "time"
-version = "0.3.34"
+version = "0.3.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c8248b6521bb14bc45b4067159b9b6ad792e2d6d754d6c41fb50e29fefe38749"
+checksum = "5dfd88e563464686c916c7e46e623e520ddc6d79fa6641390f2e3fa86e83e885"
dependencies = [
"deranged",
"itoa",
@@ -1938,9 +1938,9 @@ checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3"
[[package]]
name = "time-macros"
-version = "0.2.17"
+version = "0.2.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7ba3a3ef41e6672a2f0f001392bb5dcd3ff0a9992d618ca761a11c3121547774"
+checksum = "3f252a68540fde3a3877aeea552b832b40ab9a69e318efd078774a01ddee1ccf"
dependencies = [
"num-conv",
"time-core",
diff --git a/Cargo.toml b/Cargo.toml
index 7960a98..356fba8 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli"
authors = ["Crunchy Labs Maintainers"]
-version = "3.4.1"
+version = "3.4.2"
edition = "2021"
license = "MIT"
diff --git a/crunchy-cli-core/Cargo.toml b/crunchy-cli-core/Cargo.toml
index d006831..952adc4 100644
--- a/crunchy-cli-core/Cargo.toml
+++ b/crunchy-cli-core/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli-core"
authors = ["Crunchy Labs Maintainers"]
-version = "3.4.1"
+version = "3.4.2"
edition = "2021"
license = "MIT"
@@ -16,7 +16,7 @@ anyhow = "1.0"
async-speed-limit = "0.4"
clap = { version = "4.5", features = ["derive", "string"] }
chrono = "0.4"
-crunchyroll-rs = { version = "0.10.5", features = ["experimental-stabilizations", "tower"] }
+crunchyroll-rs = { version = "0.10.6", features = ["experimental-stabilizations", "tower"] }
ctrlc = "3.4"
dialoguer = { version = "0.11", default-features = false }
dirs = "5.0"
From cdad7fc0006230ac401b505b9fef556c6958efab Mon Sep 17 00:00:00 2001
From: bytedream
Date: Sun, 14 Apr 2024 21:18:13 +0200
Subject: [PATCH 27/82] Skip premium episode if account has no premium
subscription
---
crunchy-cli-core/src/archive/command.rs | 13 ++++++++----
crunchy-cli-core/src/archive/filter.rs | 27 ++++++++++++++++++++++++
crunchy-cli-core/src/download/command.rs | 13 ++++++++----
crunchy-cli-core/src/download/filter.rs | 24 +++++++++++++++++++++
4 files changed, 69 insertions(+), 8 deletions(-)
diff --git a/crunchy-cli-core/src/archive/command.rs b/crunchy-cli-core/src/archive/command.rs
index 4210828..7fe3796 100644
--- a/crunchy-cli-core/src/archive/command.rs
+++ b/crunchy-cli-core/src/archive/command.rs
@@ -286,10 +286,15 @@ impl Execute for Archive {
for (i, (media_collection, url_filter)) in parsed_urls.into_iter().enumerate() {
let progress_handler = progress!("Fetching series details");
- let single_format_collection =
- ArchiveFilter::new(url_filter, self.clone(), !self.yes, self.skip_specials)
- .visit(media_collection)
- .await?;
+ let single_format_collection = ArchiveFilter::new(
+ url_filter,
+ self.clone(),
+ !self.yes,
+ self.skip_specials,
+ ctx.crunchy.premium().await,
+ )
+ .visit(media_collection)
+ .await?;
if single_format_collection.is_empty() {
progress_handler.stop(format!("Skipping url {} (no matching videos found)", i + 1));
diff --git a/crunchy-cli-core/src/archive/filter.rs b/crunchy-cli-core/src/archive/filter.rs
index 90ab373..287bcc0 100644
--- a/crunchy-cli-core/src/archive/filter.rs
+++ b/crunchy-cli-core/src/archive/filter.rs
@@ -7,6 +7,7 @@ use anyhow::Result;
use crunchyroll_rs::{Concert, Episode, Locale, Movie, MovieListing, MusicVideo, Season, Series};
use log::{info, warn};
use std::collections::{BTreeMap, HashMap};
+use std::ops::Not;
enum Visited {
Series,
@@ -21,6 +22,7 @@ pub(crate) struct ArchiveFilter {
skip_special: bool,
season_episodes: HashMap>,
season_subtitles_missing: Vec,
+ seasons_with_premium: Option>,
season_sorting: Vec,
visited: Visited,
}
@@ -31,6 +33,7 @@ impl ArchiveFilter {
archive: Archive,
interactive_input: bool,
skip_special: bool,
+ is_premium: bool,
) -> Self {
Self {
url_filter,
@@ -39,6 +42,7 @@ impl ArchiveFilter {
skip_special,
season_episodes: HashMap::new(),
season_subtitles_missing: vec![],
+ seasons_with_premium: is_premium.not().then_some(vec![]),
season_sorting: vec![],
visited: Visited::None,
}
@@ -310,6 +314,29 @@ impl Filter for ArchiveFilter {
episodes.push((episode.clone(), episode.subtitle_locales.clone()))
}
+ if self.seasons_with_premium.is_some() {
+ let episode_len_before = episodes.len();
+ episodes.retain(|(e, _)| !e.is_premium_only);
+ if episode_len_before < episodes.len()
+ && !self
+ .seasons_with_premium
+ .as_ref()
+ .unwrap()
+ .contains(&episode.season_number)
+ {
+ warn!(
+ "Skipping premium episodes in season {}",
+ episode.season_number
+ );
+ self.seasons_with_premium
+ .as_mut()
+ .unwrap()
+ .push(episode.season_number)
+ }
+
+ return Ok(None);
+ }
+
let mut relative_episode_number = None;
let mut relative_sequence_number = None;
// get the relative episode number. only done if the output string has the pattern to include
diff --git a/crunchy-cli-core/src/download/command.rs b/crunchy-cli-core/src/download/command.rs
index 58055bd..87c0e07 100644
--- a/crunchy-cli-core/src/download/command.rs
+++ b/crunchy-cli-core/src/download/command.rs
@@ -246,10 +246,15 @@ impl Execute for Download {
for (i, (media_collection, url_filter)) in parsed_urls.into_iter().enumerate() {
let progress_handler = progress!("Fetching series details");
- let single_format_collection =
- DownloadFilter::new(url_filter, self.clone(), !self.yes, self.skip_specials)
- .visit(media_collection)
- .await?;
+ let single_format_collection = DownloadFilter::new(
+ url_filter,
+ self.clone(),
+ !self.yes,
+ self.skip_specials,
+ ctx.crunchy.premium().await,
+ )
+ .visit(media_collection)
+ .await?;
if single_format_collection.is_empty() {
progress_handler.stop(format!("Skipping url {} (no matching videos found)", i + 1));
diff --git a/crunchy-cli-core/src/download/filter.rs b/crunchy-cli-core/src/download/filter.rs
index 5076a33..1c62920 100644
--- a/crunchy-cli-core/src/download/filter.rs
+++ b/crunchy-cli-core/src/download/filter.rs
@@ -7,6 +7,7 @@ use anyhow::{bail, Result};
use crunchyroll_rs::{Concert, Episode, Movie, MovieListing, MusicVideo, Season, Series};
use log::{error, info, warn};
use std::collections::HashMap;
+use std::ops::Not;
pub(crate) struct DownloadFilter {
url_filter: UrlFilter,
@@ -15,6 +16,7 @@ pub(crate) struct DownloadFilter {
skip_special: bool,
season_episodes: HashMap>,
season_subtitles_missing: Vec,
+ seasons_with_premium: Option>,
season_visited: bool,
}
@@ -24,6 +26,7 @@ impl DownloadFilter {
download: Download,
interactive_input: bool,
skip_special: bool,
+ is_premium: bool,
) -> Self {
Self {
url_filter,
@@ -32,6 +35,7 @@ impl DownloadFilter {
skip_special,
season_episodes: HashMap::new(),
season_subtitles_missing: vec![],
+ seasons_with_premium: is_premium.not().then_some(vec![]),
season_visited: false,
}
}
@@ -201,6 +205,26 @@ impl Filter for DownloadFilter {
}
}
+ if self.seasons_with_premium.is_some() && episode.is_premium_only {
+ if !self
+ .seasons_with_premium
+ .as_ref()
+ .unwrap()
+ .contains(&episode.season_number)
+ {
+ warn!(
+ "Skipping premium episodes in season {}",
+ episode.season_number
+ );
+ self.seasons_with_premium
+ .as_mut()
+ .unwrap()
+ .push(episode.season_number)
+ }
+
+ return Ok(None);
+ }
+
let mut relative_episode_number = None;
let mut relative_sequence_number = None;
// get the relative episode number. only done if the output string has the pattern to include
From fe17f3951ea3e9d39973deffb80ea1126de89172 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Sun, 14 Apr 2024 21:25:17 +0200
Subject: [PATCH 28/82] Update dependencies and version
---
Cargo.lock | 83 ++++++++++++++++++++-----------------
Cargo.toml | 2 +-
crunchy-cli-core/Cargo.toml | 4 +-
3 files changed, 48 insertions(+), 41 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index a0d0c8b..682b85d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -109,9 +109,9 @@ dependencies = [
[[package]]
name = "async-trait"
-version = "0.1.79"
+version = "0.1.80"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a507401cad91ec6a857ed5513a2073c82a9b9048762b885bb98655b306964681"
+checksum = "c6fa2087f2753a7da8cc1c0dbfcf89579dd57458e36769de5ac750b4671737ca"
dependencies = [
"proc-macro2",
"quote",
@@ -199,9 +199,9 @@ checksum = "514de17de45fdb8dc022b1a7975556c53c86f9f0aa5f534b98977b171857c2c9"
[[package]]
name = "cc"
-version = "1.0.92"
+version = "1.0.94"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2678b2e3449475e95b0aa6f9b506a28e61b3dc8996592b983695e8ebb58a8b41"
+checksum = "17f6e324229dc011159fcc089755d1e2e216a90d43a7dea6853ca740b84f35e7"
[[package]]
name = "cfg-if"
@@ -227,7 +227,7 @@ dependencies = [
"num-traits",
"serde",
"wasm-bindgen",
- "windows-targets 0.52.4",
+ "windows-targets 0.52.5",
]
[[package]]
@@ -354,7 +354,7 @@ checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f"
[[package]]
name = "crunchy-cli"
-version = "3.4.2"
+version = "3.4.3"
dependencies = [
"chrono",
"clap",
@@ -367,7 +367,7 @@ dependencies = [
[[package]]
name = "crunchy-cli-core"
-version = "3.4.2"
+version = "3.4.3"
dependencies = [
"anyhow",
"async-speed-limit",
@@ -404,9 +404,9 @@ dependencies = [
[[package]]
name = "crunchyroll-rs"
-version = "0.10.6"
+version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "93e6c52101e3afd7246a099478945ee01f0a5f07ee75cf44398a752e74b2bc90"
+checksum = "3eaf93641a3697ba4cd6845b3a741089f4b4c692a91ed40dece6d7376c419ef9"
dependencies = [
"async-trait",
"chrono",
@@ -430,9 +430,9 @@ dependencies = [
[[package]]
name = "crunchyroll-rs-internal"
-version = "0.10.6"
+version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6cc8e8098c9cc87b88c8026c2dbc3bbd68ba69d26ce04dbc89963e9c2e69c7cd"
+checksum = "48daba6fe0296c2b400cd6545cf2e8ee23870f1a5a35291fa2d61987098a5692"
dependencies = [
"darling",
"quote",
@@ -564,9 +564,9 @@ dependencies = [
[[package]]
name = "either"
-version = "1.10.0"
+version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "11157ac094ffbdde99aa67b23417ebdd801842852b500e395a45a9c0aac03e4a"
+checksum = "a47c1c47d2f5964e29c61246e81db715514cd532db6b5116a25ea3c03d6780a2"
[[package]]
name = "encode_unicode"
@@ -2333,7 +2333,7 @@ version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9"
dependencies = [
- "windows-targets 0.52.4",
+ "windows-targets 0.52.5",
]
[[package]]
@@ -2351,7 +2351,7 @@ version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
- "windows-targets 0.52.4",
+ "windows-targets 0.52.5",
]
[[package]]
@@ -2371,17 +2371,18 @@ dependencies = [
[[package]]
name = "windows-targets"
-version = "0.52.4"
+version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7dd37b7e5ab9018759f893a1952c9420d060016fc19a472b4bb20d1bdd694d1b"
+checksum = "6f0713a46559409d202e70e28227288446bf7841d3211583a4b53e3f6d96e7eb"
dependencies = [
- "windows_aarch64_gnullvm 0.52.4",
- "windows_aarch64_msvc 0.52.4",
- "windows_i686_gnu 0.52.4",
- "windows_i686_msvc 0.52.4",
- "windows_x86_64_gnu 0.52.4",
- "windows_x86_64_gnullvm 0.52.4",
- "windows_x86_64_msvc 0.52.4",
+ "windows_aarch64_gnullvm 0.52.5",
+ "windows_aarch64_msvc 0.52.5",
+ "windows_i686_gnu 0.52.5",
+ "windows_i686_gnullvm",
+ "windows_i686_msvc 0.52.5",
+ "windows_x86_64_gnu 0.52.5",
+ "windows_x86_64_gnullvm 0.52.5",
+ "windows_x86_64_msvc 0.52.5",
]
[[package]]
@@ -2392,9 +2393,9 @@ checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
[[package]]
name = "windows_aarch64_gnullvm"
-version = "0.52.4"
+version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bcf46cf4c365c6f2d1cc93ce535f2c8b244591df96ceee75d8e83deb70a9cac9"
+checksum = "7088eed71e8b8dda258ecc8bac5fb1153c5cffaf2578fc8ff5d61e23578d3263"
[[package]]
name = "windows_aarch64_msvc"
@@ -2404,9 +2405,9 @@ checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
[[package]]
name = "windows_aarch64_msvc"
-version = "0.52.4"
+version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "da9f259dd3bcf6990b55bffd094c4f7235817ba4ceebde8e6d11cd0c5633b675"
+checksum = "9985fd1504e250c615ca5f281c3f7a6da76213ebd5ccc9561496568a2752afb6"
[[package]]
name = "windows_i686_gnu"
@@ -2416,9 +2417,15 @@ checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
[[package]]
name = "windows_i686_gnu"
-version = "0.52.4"
+version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b474d8268f99e0995f25b9f095bc7434632601028cf86590aea5c8a5cb7801d3"
+checksum = "88ba073cf16d5372720ec942a8ccbf61626074c6d4dd2e745299726ce8b89670"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.52.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "87f4261229030a858f36b459e748ae97545d6f1ec60e5e0d6a3d32e0dc232ee9"
[[package]]
name = "windows_i686_msvc"
@@ -2428,9 +2435,9 @@ checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
[[package]]
name = "windows_i686_msvc"
-version = "0.52.4"
+version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1515e9a29e5bed743cb4415a9ecf5dfca648ce85ee42e15873c3cd8610ff8e02"
+checksum = "db3c2bf3d13d5b658be73463284eaf12830ac9a26a90c717b7f771dfe97487bf"
[[package]]
name = "windows_x86_64_gnu"
@@ -2440,9 +2447,9 @@ checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
[[package]]
name = "windows_x86_64_gnu"
-version = "0.52.4"
+version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5eee091590e89cc02ad514ffe3ead9eb6b660aedca2183455434b93546371a03"
+checksum = "4e4246f76bdeff09eb48875a0fd3e2af6aada79d409d33011886d3e1581517d9"
[[package]]
name = "windows_x86_64_gnullvm"
@@ -2452,9 +2459,9 @@ checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
[[package]]
name = "windows_x86_64_gnullvm"
-version = "0.52.4"
+version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "77ca79f2451b49fa9e2af39f0747fe999fcda4f5e241b2898624dca97a1f2177"
+checksum = "852298e482cd67c356ddd9570386e2862b5673c85bd5f88df9ab6802b334c596"
[[package]]
name = "windows_x86_64_msvc"
@@ -2464,9 +2471,9 @@ checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
[[package]]
name = "windows_x86_64_msvc"
-version = "0.52.4"
+version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "32b752e52a2da0ddfbdbcc6fceadfeede4c939ed16d13e648833a61dfb611ed8"
+checksum = "bec47e5bfd1bff0eeaf6d8b485cc1074891a197ab4225d504cb7a1ab88b02bf0"
[[package]]
name = "winreg"
diff --git a/Cargo.toml b/Cargo.toml
index 356fba8..ee34786 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli"
authors = ["Crunchy Labs Maintainers"]
-version = "3.4.2"
+version = "3.4.3"
edition = "2021"
license = "MIT"
diff --git a/crunchy-cli-core/Cargo.toml b/crunchy-cli-core/Cargo.toml
index 952adc4..6d6b57b 100644
--- a/crunchy-cli-core/Cargo.toml
+++ b/crunchy-cli-core/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli-core"
authors = ["Crunchy Labs Maintainers"]
-version = "3.4.2"
+version = "3.4.3"
edition = "2021"
license = "MIT"
@@ -16,7 +16,7 @@ anyhow = "1.0"
async-speed-limit = "0.4"
clap = { version = "4.5", features = ["derive", "string"] }
chrono = "0.4"
-crunchyroll-rs = { version = "0.10.6", features = ["experimental-stabilizations", "tower"] }
+crunchyroll-rs = { version = "0.10.7", features = ["experimental-stabilizations", "tower"] }
ctrlc = "3.4"
dialoguer = { version = "0.11", default-features = false }
dirs = "5.0"
From 6515d3025f39eed68979ca1695f532b6a2a5e63b Mon Sep 17 00:00:00 2001
From: bytedream
Date: Sun, 14 Apr 2024 21:43:24 +0200
Subject: [PATCH 29/82] Add warn message when using a non-premium account with
download or archive
---
crunchy-cli-core/src/archive/command.rs | 4 ++++
crunchy-cli-core/src/download/command.rs | 4 ++++
2 files changed, 8 insertions(+)
diff --git a/crunchy-cli-core/src/archive/command.rs b/crunchy-cli-core/src/archive/command.rs
index 7fe3796..e2fff5c 100644
--- a/crunchy-cli-core/src/archive/command.rs
+++ b/crunchy-cli-core/src/archive/command.rs
@@ -271,6 +271,10 @@ impl Execute for Archive {
}
async fn execute(self, ctx: Context) -> Result<()> {
+ if !ctx.crunchy.premium().await {
+ warn!("You may not be able to download all requested videos when logging in anonymously or using a non-premium account")
+ }
+
let mut parsed_urls = vec![];
for (i, url) in self.urls.clone().into_iter().enumerate() {
diff --git a/crunchy-cli-core/src/download/command.rs b/crunchy-cli-core/src/download/command.rs
index 87c0e07..44c3d65 100644
--- a/crunchy-cli-core/src/download/command.rs
+++ b/crunchy-cli-core/src/download/command.rs
@@ -212,6 +212,10 @@ impl Execute for Download {
}
async fn execute(self, ctx: Context) -> Result<()> {
+ if !ctx.crunchy.premium().await {
+ warn!("You may not be able to download all requested videos when logging in anonymously or using a non-premium account")
+ }
+
let mut parsed_urls = vec![];
let output_supports_softsubs = SOFTSUB_CONTAINERS.contains(
From 4fc20c7c1cc67f4cc06a03120c10b67469210572 Mon Sep 17 00:00:00 2001
From: Amelia
Date: Sun, 14 Apr 2024 12:55:55 -0700
Subject: [PATCH 30/82] Support override fonts (#378)
* Support override fonts
* Compile fix
* Actual compile fix
* Use snake_case
---
crunchy-cli-core/src/utils/download.rs | 8 +++++++-
1 file changed, 7 insertions(+), 1 deletion(-)
diff --git a/crunchy-cli-core/src/utils/download.rs b/crunchy-cli-core/src/utils/download.rs
index daae9a5..a17875d 100644
--- a/crunchy-cli-core/src/utils/download.rs
+++ b/crunchy-cli-core/src/utils/download.rs
@@ -1295,7 +1295,7 @@ const FONTS: [(&str, &str); 68] = [
("Webdings", "webdings.woff2"),
];
lazy_static::lazy_static! {
- static ref FONT_REGEX: Regex = Regex::new(r"(?m)^Style:\s.+?,(?P.+?),").unwrap();
+ static ref FONT_REGEX: Regex = Regex::new(r"(?m)^(?:Style:\s.+?,(?P.+?),|(?:Dialogue:\s(?:.+?,)+,\{(?:\\.*)?\\fn(?P[\w\s]+)(?:\\.*)?)\})").unwrap();
}
/// Get the fonts used in the subtitle.
@@ -1309,6 +1309,12 @@ fn get_subtitle_stats(path: &Path) -> Result> {
fonts.push(font_string)
}
}
+ if let Some(override_font) = capture.name("overrideFont") {
+ let font_string = override_font.as_str().to_string();
+ if !fonts.contains(&font_string) {
+ fonts.push(font_string)
+ }
+ }
}
Ok(fonts)
From 9bdd3aa85b1f3fb244f8981160ebfacfbaf71ec0 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Thu, 18 Apr 2024 18:44:31 +0200
Subject: [PATCH 31/82] Switch to `openssl-tls` on nix flake (#359)
---
flake.lock | 12 ++++++------
flake.nix | 2 +-
2 files changed, 7 insertions(+), 7 deletions(-)
diff --git a/flake.lock b/flake.lock
index e92c958..71f3f28 100644
--- a/flake.lock
+++ b/flake.lock
@@ -2,11 +2,11 @@
"nodes": {
"nixpkgs": {
"locked": {
- "lastModified": 1707877513,
- "narHash": "sha256-sp0w2apswd3wv0sAEF7StOGHkns3XUQaO5erhWFZWXk=",
+ "lastModified": 1710534455,
+ "narHash": "sha256-huQT4Xs0y4EeFKn2BTBVYgEwJSv8SDlm82uWgMnCMmI=",
"owner": "NixOS",
"repo": "nixpkgs",
- "rev": "89653a03e0915e4a872788d10680e7eec92f8600",
+ "rev": "9af9c1c87ed3e3ed271934cb896e0cdd33dae212",
"type": "github"
},
"original": {
@@ -41,11 +41,11 @@
"systems": "systems"
},
"locked": {
- "lastModified": 1705309234,
- "narHash": "sha256-uNRRNRKmJyCRC/8y1RqBkqWBLM034y4qN7EprSdmgyA=",
+ "lastModified": 1710146030,
+ "narHash": "sha256-SZ5L6eA7HJ/nmkzGG7/ISclqe6oZdOZTNoesiInkXPQ=",
"owner": "numtide",
"repo": "flake-utils",
- "rev": "1ef2e671c3b0c19053962c07dbda38332dcebf26",
+ "rev": "b1d9ab70662946ef0850d488da1c9019f3a9752a",
"type": "github"
},
"original": {
diff --git a/flake.nix b/flake.nix
index 2ca105a..29d9ccd 100644
--- a/flake.nix
+++ b/flake.nix
@@ -26,7 +26,7 @@
};
buildNoDefaultFeatures = true;
- buildFeatures = [ "openssl" ];
+ buildFeatures = [ "openssl-tls" ];
nativeBuildInputs = [
pkgs.pkg-config
From 8ada8223966a6db219130f739886c9f8eedfde2b Mon Sep 17 00:00:00 2001
From: bytedream
Date: Sat, 20 Apr 2024 00:00:02 +0200
Subject: [PATCH 32/82] Remove etp-rt login
---
README.md | 14 +-------------
crunchy-cli-core/src/lib.rs | 13 +++++--------
crunchy-cli-core/src/login/command.rs | 10 +---------
3 files changed, 7 insertions(+), 30 deletions(-)
diff --git a/README.md b/README.md
index 09db003..e3a0c10 100644
--- a/README.md
+++ b/README.md
@@ -122,16 +122,6 @@ You can authenticate with your credentials (email:password) or by using a refres
$ crunchy-cli --credentials "email:password"
```
-- Refresh Token
-
- To obtain a refresh token, you have to log in at [crunchyroll.com](https://www.crunchyroll.com/) and extract the `etp_rt` cookie.
- The easiest way to get it is via a browser extension which lets you export your cookies, like [Cookie-Editor](https://cookie-editor.cgagnier.ca/) ([Firefox](https://addons.mozilla.org/en-US/firefox/addon/cookie-editor/) / [Chrome](https://chrome.google.com/webstore/detail/cookie-editor/hlkenndednhfkekhgcdicdfddnkalmdm)).
- When installed, look for the `etp_rt` entry and extract its value.
-
- ```shell
- $ crunchy-cli --etp-rt "4ebf1690-53a4-491a-a2ac-488309120f5d"
- ```
-
- Stay Anonymous
Login without an account (you won't be able to access premium content):
@@ -226,11 +216,9 @@ The `login` command can store your session, so you don't have to authenticate ev
# save the refresh token which gets generated when login with credentials.
# your email and password won't be stored at any time on disk
$ crunchy-cli login --credentials "email:password"
-# save etp-rt cookie
-$ crunchy-cli login --etp-rt "4ebf1690-53a4-491a-a2ac-488309120f5d"
```
-With the session stored, you do not need to pass `--credentials` / `--etp-rt` / `--anonymous` anymore when you want to execute a command.
+With the session stored, you do not need to pass `--credentials` / `--anonymous` anymore when you want to execute a command.
### Download
diff --git a/crunchy-cli-core/src/lib.rs b/crunchy-cli-core/src/lib.rs
index d8d5ec5..1ec5281 100644
--- a/crunchy-cli-core/src/lib.rs
+++ b/crunchy-cli-core/src/lib.rs
@@ -326,9 +326,8 @@ async fn crunchyroll_session(
builder = builder.middleware(rate_limiter)
}
- let root_login_methods_count = cli.login_method.credentials.is_some() as u8
- + cli.login_method.etp_rt.is_some() as u8
- + cli.login_method.anonymous as u8;
+ let root_login_methods_count =
+ cli.login_method.credentials.is_some() as u8 + cli.login_method.anonymous as u8;
let progress_handler = progress!("Logging in");
if root_login_methods_count == 0 {
@@ -340,16 +339,16 @@ async fn crunchyroll_session(
"refresh_token" => {
return Ok(builder.login_with_refresh_token(token).await?)
}
- "etp_rt" => return Ok(builder.login_with_etp_rt(token).await?),
+ "etp_rt" => bail!("The stored login method (etp-rt) isn't supported anymore. Please use your credentials to login"),
_ => (),
}
}
bail!("Could not read stored session ('{}')", session)
}
}
- bail!("Please use a login method ('--credentials', '--etp-rt' or '--anonymous')")
+ bail!("Please use a login method ('--credentials' or '--anonymous')")
} else if root_login_methods_count > 1 {
- bail!("Please use only one login method ('--credentials', '--etp-rt' or '--anonymous')")
+ bail!("Please use only one login method ('--credentials' or '--anonymous')")
}
let crunchy = if let Some(credentials) = &cli.login_method.credentials {
@@ -358,8 +357,6 @@ async fn crunchyroll_session(
} else {
bail!("Invalid credentials format. Please provide your credentials as email:password")
}
- } else if let Some(etp_rt) = &cli.login_method.etp_rt {
- builder.login_with_etp_rt(etp_rt).await?
} else if cli.login_method.anonymous {
builder.login_anonymously().await?
} else {
diff --git a/crunchy-cli-core/src/login/command.rs b/crunchy-cli-core/src/login/command.rs
index 5642948..4da1898 100644
--- a/crunchy-cli-core/src/login/command.rs
+++ b/crunchy-cli-core/src/login/command.rs
@@ -25,9 +25,7 @@ impl Execute for Login {
SessionToken::RefreshToken(refresh_token) => {
fs::write(login_file_path, format!("refresh_token:{}", refresh_token))?
}
- SessionToken::EtpRt(etp_rt) => {
- fs::write(login_file_path, format!("etp_rt:{}", etp_rt))?
- }
+ SessionToken::EtpRt(_) => bail!("Login with etp_rt isn't supported anymore. Please use your credentials to login"),
SessionToken::Anonymous => bail!("Anonymous login cannot be saved"),
}
@@ -47,12 +45,6 @@ pub struct LoginMethod {
)]
#[arg(global = true, long)]
pub credentials: Option,
- #[arg(help = "Login with the etp-rt cookie")]
- #[arg(
- long_help = "Login with the etp-rt cookie. This can be obtained when you login on crunchyroll.com and extract it from there"
- )]
- #[arg(global = true, long)]
- pub etp_rt: Option,
#[arg(help = "Login anonymously / without an account")]
#[arg(global = true, long, default_value_t = false)]
pub anonymous: bool,
From db6e45e7f472040b725227411b70f91226255f09 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Sat, 20 Apr 2024 00:02:18 +0200
Subject: [PATCH 33/82] Update dependencies and version
---
Cargo.lock | 52 ++++++++++++++++++-------------------
Cargo.toml | 2 +-
crunchy-cli-core/Cargo.toml | 4 +--
3 files changed, 29 insertions(+), 29 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index 682b85d..3e16a61 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -217,9 +217,9 @@ checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e"
[[package]]
name = "chrono"
-version = "0.4.37"
+version = "0.4.38"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8a0d04d43504c61aa6c7531f1871dd0d418d91130162063b789da00fd7057a5e"
+checksum = "a21f936df1771bf62b77f047b726c4625ff2e8aa607c01ec06e5a05bd8463401"
dependencies = [
"android-tzdata",
"iana-time-zone",
@@ -354,7 +354,7 @@ checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f"
[[package]]
name = "crunchy-cli"
-version = "3.4.3"
+version = "3.5.0"
dependencies = [
"chrono",
"clap",
@@ -367,7 +367,7 @@ dependencies = [
[[package]]
name = "crunchy-cli-core"
-version = "3.4.3"
+version = "3.5.0"
dependencies = [
"anyhow",
"async-speed-limit",
@@ -404,9 +404,9 @@ dependencies = [
[[package]]
name = "crunchyroll-rs"
-version = "0.10.7"
+version = "0.10.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3eaf93641a3697ba4cd6845b3a741089f4b4c692a91ed40dece6d7376c419ef9"
+checksum = "ccd0a624f3f8ec3fb7af8d83b907142aaee1858579ab697f24f05d00736e5bb2"
dependencies = [
"async-trait",
"chrono",
@@ -430,9 +430,9 @@ dependencies = [
[[package]]
name = "crunchyroll-rs-internal"
-version = "0.10.7"
+version = "0.10.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "48daba6fe0296c2b400cd6545cf2e8ee23870f1a5a35291fa2d61987098a5692"
+checksum = "85c3614a871ec25ab17425405b08aea3c5869597e2348302b922c2a077aa9c3a"
dependencies = [
"darling",
"quote",
@@ -486,9 +486,9 @@ dependencies = [
[[package]]
name = "dash-mpd"
-version = "0.16.0"
+version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6cafa2c33eff2857e1a14c38aa9a432aa565a01e77804a541fce7aec3affb8f8"
+checksum = "79b4bdd5f1c0c7493d780c645f0bff5b9361e6408210fa88910adb181efca64c"
dependencies = [
"base64 0.22.0",
"base64-serde",
@@ -831,9 +831,9 @@ checksum = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904"
[[package]]
name = "hyper"
-version = "1.2.0"
+version = "1.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "186548d73ac615b32a73aafe38fb4f56c0d340e110e5a200bcadbaf2e199263a"
+checksum = "fe575dd17d0862a9a33781c8c4696a55c320909004a67a00fb286ba8b1bc496d"
dependencies = [
"bytes",
"futures-channel",
@@ -1375,9 +1375,9 @@ dependencies = [
[[package]]
name = "proc-macro2"
-version = "1.0.79"
+version = "1.0.81"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e835ff2298f5721608eb1a980ecaee1aef2c132bf95ecc026a11b7bf3c01c02e"
+checksum = "3d1597b0c024618f09a9c3b8655b7e430397a36d23fdafec26d6965e9eec3eba"
dependencies = [
"unicode-ident",
]
@@ -1459,9 +1459,9 @@ checksum = "adad44e29e4c806119491a7f06f03de4d1af22c3a680dd47f1e6e179439d1f56"
[[package]]
name = "reqwest"
-version = "0.12.3"
+version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3e6cc1e89e689536eb5aeede61520e874df5a4707df811cd5da4aa5fbb2aae19"
+checksum = "566cafdd92868e0939d3fb961bd0dc25fcfaaed179291093b3d43e6b3150ea10"
dependencies = [
"base64 0.22.0",
"bytes",
@@ -1576,9 +1576,9 @@ dependencies = [
[[package]]
name = "rustls"
-version = "0.22.3"
+version = "0.22.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "99008d7ad0bbbea527ec27bddbc0e432c5b87d8175178cee68d2eec9c4a1813c"
+checksum = "bf4ef73721ac7bcd79b2b315da7779d8fc09718c6b3d2d1b2d94850eb8c18432"
dependencies = [
"log",
"ring",
@@ -1668,18 +1668,18 @@ dependencies = [
[[package]]
name = "serde"
-version = "1.0.197"
+version = "1.0.198"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3fb1c873e1b9b056a4dc4c0c198b24c3ffa059243875552b2bd0933b1aee4ce2"
+checksum = "9846a40c979031340571da2545a4e5b7c4163bdae79b301d5f86d03979451fcc"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
-version = "1.0.197"
+version = "1.0.198"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b"
+checksum = "e88edab869b01783ba905e7d0153f9fc1a6505a96e4ad3018011eedb838566d9"
dependencies = [
"proc-macro2",
"quote",
@@ -1688,9 +1688,9 @@ dependencies = [
[[package]]
name = "serde_json"
-version = "1.0.115"
+version = "1.0.116"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "12dc5c46daa8e9fdf4f5e71b6cf9a53f2487da0e86e55808e2d35539666497dd"
+checksum = "3e17db7126d17feb94eb3fad46bf1a96b034e8aacbc2e775fe81505f8b0b2813"
dependencies = [
"itoa",
"ryu",
@@ -1838,9 +1838,9 @@ checksum = "81cdd64d312baedb58e21336b31bc043b77e01cc99033ce76ef539f78e965ebc"
[[package]]
name = "syn"
-version = "2.0.58"
+version = "2.0.60"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "44cfb93f38070beee36b3fef7d4f5a16f27751d94b187b666a5cc5e9b0d30687"
+checksum = "909518bc7b1c9b779f1bbf07f2929d35af9f0f37e47c6e9ef7f9dddc1e1821f3"
dependencies = [
"proc-macro2",
"quote",
diff --git a/Cargo.toml b/Cargo.toml
index ee34786..9520ec9 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli"
authors = ["Crunchy Labs Maintainers"]
-version = "3.4.3"
+version = "3.5.0"
edition = "2021"
license = "MIT"
diff --git a/crunchy-cli-core/Cargo.toml b/crunchy-cli-core/Cargo.toml
index 6d6b57b..58c7fe8 100644
--- a/crunchy-cli-core/Cargo.toml
+++ b/crunchy-cli-core/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli-core"
authors = ["Crunchy Labs Maintainers"]
-version = "3.4.3"
+version = "3.5.0"
edition = "2021"
license = "MIT"
@@ -16,7 +16,7 @@ anyhow = "1.0"
async-speed-limit = "0.4"
clap = { version = "4.5", features = ["derive", "string"] }
chrono = "0.4"
-crunchyroll-rs = { version = "0.10.7", features = ["experimental-stabilizations", "tower"] }
+crunchyroll-rs = { version = "0.10.8", features = ["experimental-stabilizations", "tower"] }
ctrlc = "3.4"
dialoguer = { version = "0.11", default-features = false }
dirs = "5.0"
From 8fff807ae68b61931aa8b1c899b8c8bba4df0784 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Sat, 20 Apr 2024 00:22:46 +0200
Subject: [PATCH 34/82] Add message if stored login is expired
---
crunchy-cli-core/src/lib.rs | 14 ++++++++++++--
1 file changed, 12 insertions(+), 2 deletions(-)
diff --git a/crunchy-cli-core/src/lib.rs b/crunchy-cli-core/src/lib.rs
index 1ec5281..1c180e8 100644
--- a/crunchy-cli-core/src/lib.rs
+++ b/crunchy-cli-core/src/lib.rs
@@ -337,9 +337,19 @@ async fn crunchyroll_session(
if let Some((token_type, token)) = session.split_once(':') {
match token_type {
"refresh_token" => {
- return Ok(builder.login_with_refresh_token(token).await?)
+ return match builder.login_with_refresh_token(token).await {
+ Ok(crunchy) => Ok(crunchy),
+ Err(e) => {
+ if let Error::Request { message, .. } = &e {
+ if message.starts_with("invalid_grant") {
+ bail!("The stored login is expired, please login again")
+ }
+ }
+ Err(e.into())
+ }
+ }
}
- "etp_rt" => bail!("The stored login method (etp-rt) isn't supported anymore. Please use your credentials to login"),
+ "etp_rt" => bail!("The stored login method (etp-rt) isn't supported anymore. Please login again using your credentials"),
_ => (),
}
}
From 177aa376317cbba052b8705db0a3daaaa508317b Mon Sep 17 00:00:00 2001
From: Simon <47527944+Frooastside@users.noreply.github.com>
Date: Sun, 21 Apr 2024 12:40:53 +0200
Subject: [PATCH 35/82] Move help for --language-tagging (#385)
---
crunchy-cli-core/src/archive/command.rs | 9 ++++-----
1 file changed, 4 insertions(+), 5 deletions(-)
diff --git a/crunchy-cli-core/src/archive/command.rs b/crunchy-cli-core/src/archive/command.rs
index e2fff5c..0303db7 100644
--- a/crunchy-cli-core/src/archive/command.rs
+++ b/crunchy-cli-core/src/archive/command.rs
@@ -105,11 +105,6 @@ pub struct Archive {
)]
#[arg(long, default_value_t = 200)]
pub(crate) merge_auto_tolerance: u32,
- #[arg(
- long,
- help = "Specified which language tagging the audio and subtitle tracks and language specific format options should have. \
- Valid options are: 'default' (how Crunchyroll uses it internally), 'ietf' (according to the IETF standard)"
- )]
#[arg(help = "Tries to sync the timing of all downloaded audios to match one video")]
#[arg(
long_help = "Tries to sync the timing of all downloaded audios to match one video. \
@@ -122,6 +117,10 @@ pub struct Archive {
#[arg(long, require_equals = true, num_args = 0..=1, default_missing_value = "7.5")]
pub(crate) sync_start: Option,
+ #[arg(
+ help = "Specified which language tagging the audio and subtitle tracks and language specific format options should have. \
+ Valid options are: 'default' (how Crunchyroll uses it internally), 'ietf' (according to the IETF standard)"
+ )]
#[arg(
long_help = "Specified which language tagging the audio and subtitle tracks and language specific format options should have. \
Valid options are: 'default' (how Crunchyroll uses it internally), 'ietf' (according to the IETF standard; you might run in issues as there are multiple locales which resolve to the same IETF language code, e.g. 'es-LA' and 'es-ES' are both resolving to 'es')"
From 4f3475131cee7df1294948aa9239eb2d45f3307d Mon Sep 17 00:00:00 2001
From: bytedream
Date: Sun, 21 Apr 2024 13:19:54 +0200
Subject: [PATCH 36/82] Disable LTO in source aur pkgbuild
---
.github/scripts/PKGBUILD.source | 2 ++
1 file changed, 2 insertions(+)
diff --git a/.github/scripts/PKGBUILD.source b/.github/scripts/PKGBUILD.source
index af6b8e1..4430f95 100644
--- a/.github/scripts/PKGBUILD.source
+++ b/.github/scripts/PKGBUILD.source
@@ -12,6 +12,8 @@ depends=('ffmpeg' 'openssl')
makedepends=('cargo')
source=("${pkgname}-${pkgver}.tar.gz::https://github.com/crunchy-labs/crunchy-cli/archive/refs/tags/v${pkgver}.tar.gz")
sha256sums=('$CI_SHA_SUM')
+# lto causes linking errors when executed by this buildscript. besides, lto is already done by cargo itself (which doesn't cause linking errors)
+options=(!lto)
build() {
cd "$srcdir/${pkgname}-$pkgver"
From 777b39aba13be2861c82d04af7120b716881c05c Mon Sep 17 00:00:00 2001
From: Simon <47527944+Frooastside@users.noreply.github.com>
Date: Mon, 22 Apr 2024 23:47:49 +0200
Subject: [PATCH 37/82] Fix: stop skipping every episode with archive command
while using a non premium account (#388)
---
crunchy-cli-core/src/archive/filter.rs | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)
diff --git a/crunchy-cli-core/src/archive/filter.rs b/crunchy-cli-core/src/archive/filter.rs
index 287bcc0..f638c50 100644
--- a/crunchy-cli-core/src/archive/filter.rs
+++ b/crunchy-cli-core/src/archive/filter.rs
@@ -333,8 +333,10 @@ impl Filter for ArchiveFilter {
.unwrap()
.push(episode.season_number)
}
-
- return Ok(None);
+
+ if episodes.is_empty() {
+ return Ok(None);
+ }
}
let mut relative_episode_number = None;
From 541f0e27477848e92baf1c6b3f0a512d2d202f29 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Tue, 23 Apr 2024 16:00:42 +0200
Subject: [PATCH 38/82] Fix wrong audio and subtitle video reference number
(#384)
---
crunchy-cli-core/src/utils/download.rs | 14 +++++++++++---
1 file changed, 11 insertions(+), 3 deletions(-)
diff --git a/crunchy-cli-core/src/utils/download.rs b/crunchy-cli-core/src/utils/download.rs
index a17875d..6882a42 100644
--- a/crunchy-cli-core/src/utils/download.rs
+++ b/crunchy-cli-core/src/utils/download.rs
@@ -128,6 +128,7 @@ struct FFmpegAudioMeta {
path: TempPath,
locale: Locale,
start_time: Option,
+ video_idx: usize,
}
struct FFmpegSubtitleMeta {
@@ -135,6 +136,7 @@ struct FFmpegSubtitleMeta {
locale: Locale,
cc: bool,
start_time: Option,
+ video_idx: usize,
}
pub struct DownloadFormat {
@@ -433,7 +435,7 @@ impl Downloader {
}
// downloads all audios
- for format in &self.formats {
+ for (i, format) in self.formats.iter().enumerate() {
for (j, (stream_data, locale)) in format.audios.iter().enumerate() {
let path = self
.download_audio(
@@ -445,6 +447,7 @@ impl Downloader {
path,
locale: locale.clone(),
start_time: audio_offsets.get(&j).cloned(),
+ video_idx: i,
})
}
}
@@ -507,6 +510,7 @@ impl Downloader {
locale: subtitle.locale.clone(),
cc: !not_cc,
start_time: subtitle_offsets.get(&j).cloned(),
+ video_idx: i,
})
}
}
@@ -632,7 +636,11 @@ impl Downloader {
if videos.len() == 1 {
meta.locale.to_human_readable()
} else {
- format!("{} [Video: #{}]", meta.locale.to_human_readable(), i + 1,)
+ format!(
+ "{} [Video: #{}]",
+ meta.locale.to_human_readable(),
+ meta.video_idx + 1
+ )
}
),
]);
@@ -679,7 +687,7 @@ impl Downloader {
title += " (CC)"
}
if videos.len() > 1 {
- title += &format!(" [Video: #{}]", i + 1)
+ title += &format!(" [Video: #{}]", meta.video_idx + 1)
}
title
}),
From 177ceb19205698a2af09676e685feffc80d87168 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Tue, 23 Apr 2024 16:13:42 +0200
Subject: [PATCH 39/82] Update dependencies and version
---
Cargo.lock | 24 ++++++++++++------------
Cargo.toml | 2 +-
crunchy-cli-core/Cargo.toml | 2 +-
3 files changed, 14 insertions(+), 14 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index 3e16a61..ec4cfd0 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -199,9 +199,9 @@ checksum = "514de17de45fdb8dc022b1a7975556c53c86f9f0aa5f534b98977b171857c2c9"
[[package]]
name = "cc"
-version = "1.0.94"
+version = "1.0.95"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "17f6e324229dc011159fcc089755d1e2e216a90d43a7dea6853ca740b84f35e7"
+checksum = "d32a725bc159af97c3e629873bb9f88fb8cf8a4867175f76dc987815ea07c83b"
[[package]]
name = "cfg-if"
@@ -354,7 +354,7 @@ checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f"
[[package]]
name = "crunchy-cli"
-version = "3.5.0"
+version = "3.5.1"
dependencies = [
"chrono",
"clap",
@@ -367,7 +367,7 @@ dependencies = [
[[package]]
name = "crunchy-cli-core"
-version = "3.5.0"
+version = "3.5.1"
dependencies = [
"anyhow",
"async-speed-limit",
@@ -1563,9 +1563,9 @@ dependencies = [
[[package]]
name = "rustix"
-version = "0.38.32"
+version = "0.38.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "65e04861e65f21776e67888bfbea442b3642beaa0138fdb1dd7a84a52dffdb89"
+checksum = "70dc5ec042f7a43c4a73241207cecc9873a06d45debb38b329f8541d85c2730f"
dependencies = [
"bitflags 2.5.0",
"errno",
@@ -1619,9 +1619,9 @@ checksum = "ecd36cc4259e3e4514335c4a138c6b43171a8d61d8f5c9348f9fc7529416f247"
[[package]]
name = "rustls-webpki"
-version = "0.102.2"
+version = "0.102.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "faaa0a62740bedb9b2ef5afa303da42764c012f743917351dc9a237ea1663610"
+checksum = "f3bce581c0dd41bce533ce695a1437fa16a7ab5ac3ccfa99fe1a620a7885eabf"
dependencies = [
"ring",
"rustls-pki-types",
@@ -1897,18 +1897,18 @@ dependencies = [
[[package]]
name = "thiserror"
-version = "1.0.58"
+version = "1.0.59"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "03468839009160513471e86a034bb2c5c0e4baae3b43f79ffc55c4a5427b3297"
+checksum = "f0126ad08bff79f29fc3ae6a55cc72352056dfff61e3ff8bb7129476d44b23aa"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
-version = "1.0.58"
+version = "1.0.59"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c61f3ba182994efc43764a46c018c347bc492c79f024e705f46567b418f6d4f7"
+checksum = "d1cd413b5d558b4c5bf3680e324a6fa5014e7b7c067a51e69dbdf47eb7148b66"
dependencies = [
"proc-macro2",
"quote",
diff --git a/Cargo.toml b/Cargo.toml
index 9520ec9..f08615a 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli"
authors = ["Crunchy Labs Maintainers"]
-version = "3.5.0"
+version = "3.5.1"
edition = "2021"
license = "MIT"
diff --git a/crunchy-cli-core/Cargo.toml b/crunchy-cli-core/Cargo.toml
index 58c7fe8..cb1c088 100644
--- a/crunchy-cli-core/Cargo.toml
+++ b/crunchy-cli-core/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli-core"
authors = ["Crunchy Labs Maintainers"]
-version = "3.5.0"
+version = "3.5.1"
edition = "2021"
license = "MIT"
From 74aaed4e7a672789dd13c5e73627af61cd91c35c Mon Sep 17 00:00:00 2001
From: bytedream
Date: Thu, 25 Apr 2024 00:48:37 +0200
Subject: [PATCH 40/82] Update dependencies and version
---
Cargo.lock | 30 +++++++++++++-------------
Cargo.toml | 2 +-
crunchy-cli-core/Cargo.toml | 4 ++--
crunchy-cli-core/src/utils/download.rs | 3 +--
4 files changed, 19 insertions(+), 20 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index ec4cfd0..61832fe 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -354,7 +354,7 @@ checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f"
[[package]]
name = "crunchy-cli"
-version = "3.5.1"
+version = "3.5.2"
dependencies = [
"chrono",
"clap",
@@ -367,7 +367,7 @@ dependencies = [
[[package]]
name = "crunchy-cli-core"
-version = "3.5.1"
+version = "3.5.2"
dependencies = [
"anyhow",
"async-speed-limit",
@@ -404,9 +404,9 @@ dependencies = [
[[package]]
name = "crunchyroll-rs"
-version = "0.10.8"
+version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ccd0a624f3f8ec3fb7af8d83b907142aaee1858579ab697f24f05d00736e5bb2"
+checksum = "e63a541bdcf0170a29eab4015943e8a6a09281334b4beacd70ac5cfc1c19496b"
dependencies = [
"async-trait",
"chrono",
@@ -430,9 +430,9 @@ dependencies = [
[[package]]
name = "crunchyroll-rs-internal"
-version = "0.10.8"
+version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "85c3614a871ec25ab17425405b08aea3c5869597e2348302b922c2a077aa9c3a"
+checksum = "3a9e0e09162451565645fdd4dadc6b38e09f3aafcfb477153584bedd8d62a358"
dependencies = [
"darling",
"quote",
@@ -1613,9 +1613,9 @@ dependencies = [
[[package]]
name = "rustls-pki-types"
-version = "1.4.1"
+version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ecd36cc4259e3e4514335c4a138c6b43171a8d61d8f5c9348f9fc7529416f247"
+checksum = "beb461507cee2c2ff151784c52762cf4d9ff6a61f3e80968600ed24fa837fa54"
[[package]]
name = "rustls-webpki"
@@ -1730,11 +1730,11 @@ dependencies = [
[[package]]
name = "serde_with"
-version = "3.7.0"
+version = "3.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ee80b0e361bbf88fd2f6e242ccd19cfda072cb0faa6ae694ecee08199938569a"
+checksum = "2c85f8e96d1d6857f13768fcbd895fcb06225510022a2774ed8b5150581847b0"
dependencies = [
- "base64 0.21.7",
+ "base64 0.22.0",
"chrono",
"hex",
"indexmap 1.9.3",
@@ -1748,9 +1748,9 @@ dependencies = [
[[package]]
name = "serde_with_macros"
-version = "3.7.0"
+version = "3.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6561dc161a9224638a31d876ccdfefbc1df91d3f3a8342eddb35f055d48c7655"
+checksum = "c8b3a576c4eb2924262d5951a3b737ccaf16c931e39a2810c36f9a7e25575557"
dependencies = [
"darling",
"proc-macro2",
@@ -2498,9 +2498,9 @@ dependencies = [
[[package]]
name = "zeroize"
-version = "1.7.0"
+version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "525b4ec142c6b68a2d10f01f7bbf6755599ca3f81ea53b8431b7dd348f5fdb2d"
+checksum = "63381fa6624bf92130a6b87c0d07380116f80b565c42cf0d754136f0238359ef"
[[package]]
name = "zune-core"
diff --git a/Cargo.toml b/Cargo.toml
index f08615a..6886f97 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli"
authors = ["Crunchy Labs Maintainers"]
-version = "3.5.1"
+version = "3.5.2"
edition = "2021"
license = "MIT"
diff --git a/crunchy-cli-core/Cargo.toml b/crunchy-cli-core/Cargo.toml
index cb1c088..e31ef46 100644
--- a/crunchy-cli-core/Cargo.toml
+++ b/crunchy-cli-core/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli-core"
authors = ["Crunchy Labs Maintainers"]
-version = "3.5.1"
+version = "3.5.2"
edition = "2021"
license = "MIT"
@@ -16,7 +16,7 @@ anyhow = "1.0"
async-speed-limit = "0.4"
clap = { version = "4.5", features = ["derive", "string"] }
chrono = "0.4"
-crunchyroll-rs = { version = "0.10.8", features = ["experimental-stabilizations", "tower"] }
+crunchyroll-rs = { version = "0.11.0", features = ["experimental-stabilizations", "tower"] }
ctrlc = "3.4"
dialoguer = { version = "0.11", default-features = false }
dirs = "5.0"
diff --git a/crunchy-cli-core/src/utils/download.rs b/crunchy-cli-core/src/utils/download.rs
index 6882a42..eb280c3 100644
--- a/crunchy-cli-core/src/utils/download.rs
+++ b/crunchy-cli-core/src/utils/download.rs
@@ -960,8 +960,7 @@ impl Downloader {
let tempfile = tempfile(".ass")?;
let (mut file, path) = tempfile.into_parts();
- let mut buf = vec![];
- subtitle.write_to(&mut buf).await?;
+ let mut buf = subtitle.data().await?;
fix_subtitles(&mut buf, max_length);
file.write_all(buf.as_slice())?;
From cf8bfb02ac40e326908e273dcf9ec2a66972c623 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Thu, 25 Apr 2024 20:32:51 +0200
Subject: [PATCH 41/82] Automatically cut too long path segments
---
crunchy-cli-core/src/utils/format.rs | 28 +++++++++++++++++++++++++++-
1 file changed, 27 insertions(+), 1 deletion(-)
diff --git a/crunchy-cli-core/src/utils/format.rs b/crunchy-cli-core/src/utils/format.rs
index 17f324f..1987e87 100644
--- a/crunchy-cli-core/src/utils/format.rs
+++ b/crunchy-cli-core/src/utils/format.rs
@@ -526,7 +526,33 @@ impl Format {
),
);
- PathBuf::from(path)
+ let mut path = PathBuf::from(path);
+
+ // make sure that every path section has a maximum of 255 characters
+ if path.file_name().unwrap_or_default().to_string_lossy().len() > 255 {
+ let name = path
+ .file_stem()
+ .unwrap_or_default()
+ .to_string_lossy()
+ .to_string();
+ let ext = path
+ .extension()
+ .unwrap_or_default()
+ .to_string_lossy()
+ .to_string();
+ if ext != name {
+ path.set_file_name(format!("{}.{}", &name[..(255 - ext.len() - 1)], ext))
+ }
+ }
+ path.into_iter()
+ .map(|s| {
+ if s.len() > 255 {
+ s.to_string_lossy()[..255].to_string()
+ } else {
+ s.to_string_lossy().to_string()
+ }
+ })
+ .collect()
}
pub fn visual_output(&self, dst: &Path) {
From bf28dbf1ce2aa25a9bf66f6fc4be0d69a1f1f2fc Mon Sep 17 00:00:00 2001
From: Simon <47527944+Frooastside@users.noreply.github.com>
Date: Fri, 26 Apr 2024 15:50:44 +0200
Subject: [PATCH 42/82] rename merge-auto-tolerance to merge-time-tolerance
(#391)
---
README.md | 6 +++---
crunchy-cli-core/src/archive/command.rs | 4 ++--
2 files changed, 5 insertions(+), 5 deletions(-)
diff --git a/README.md b/README.md
index e3a0c10..7316f57 100644
--- a/README.md
+++ b/README.md
@@ -471,13 +471,13 @@ The `archive` command lets you download episodes with multiple audios and subtit
Default is `auto`.
-- Merge auto tolerance
+- Merge time tolerance
Sometimes two video tracks are downloaded with `--merge` set to `auto` even if they only differ some milliseconds in length which shouldn't be noticeable to the viewer.
- To prevent this, you can specify a range in milliseconds with the `--merge-auto-tolerance` flag that only downloads one video if the length difference is in the given range.
+ To prevent this, you can specify a range in milliseconds with the `--merge-time-tolerance` flag that only downloads one video if the length difference is in the given range.
```shell
- $ crunchy-cli archive -m auto --merge-auto-tolerance 100 https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx
+ $ crunchy-cli archive -m auto --merge-time-tolerance 100 https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx
```
Default are `200` milliseconds.
diff --git a/crunchy-cli-core/src/archive/command.rs b/crunchy-cli-core/src/archive/command.rs
index 0303db7..3525a4a 100644
--- a/crunchy-cli-core/src/archive/command.rs
+++ b/crunchy-cli-core/src/archive/command.rs
@@ -104,7 +104,7 @@ pub struct Archive {
help = "If the merge behavior is 'auto', only download multiple video tracks if their length difference is higher than the given milliseconds"
)]
#[arg(long, default_value_t = 200)]
- pub(crate) merge_auto_tolerance: u32,
+ pub(crate) merge_time_tolerance: u32,
#[arg(help = "Tries to sync the timing of all downloaded audios to match one video")]
#[arg(
long_help = "Tries to sync the timing of all downloaded audios to match one video. \
@@ -577,7 +577,7 @@ async fn get_format(
.sub(single_format.duration)
.abs()
.num_milliseconds()
- < archive.merge_auto_tolerance.into() =>
+ < archive.merge_time_tolerance.into() =>
{
// If less than `audio_error` apart, use same audio.
closest_format
From f237033aff91c18280e924a93d30f273a0445e8f Mon Sep 17 00:00:00 2001
From: Simon <47527944+Frooastside@users.noreply.github.com>
Date: Sun, 28 Apr 2024 15:15:23 +0200
Subject: [PATCH 43/82] move format_time_delta to own file (#392)
---
crunchy-cli-core/src/utils/download.rs | 23 ++++++-----------------
crunchy-cli-core/src/utils/fmt.rs | 19 +++++++++++++++++++
crunchy-cli-core/src/utils/mod.rs | 1 +
3 files changed, 26 insertions(+), 17 deletions(-)
create mode 100644 crunchy-cli-core/src/utils/fmt.rs
diff --git a/crunchy-cli-core/src/utils/download.rs b/crunchy-cli-core/src/utils/download.rs
index eb280c3..bd7bf3d 100644
--- a/crunchy-cli-core/src/utils/download.rs
+++ b/crunchy-cli-core/src/utils/download.rs
@@ -1,5 +1,6 @@
use crate::utils::ffmpeg::FFmpegPreset;
use crate::utils::filter::real_dedup_vec;
+use crate::utils::fmt::format_time_delta;
use crate::utils::log::progress;
use crate::utils::os::{
cache_dir, is_special_file, temp_directory, temp_named_pipe, tempdir, tempfile,
@@ -595,7 +596,7 @@ impl Downloader {
for (i, meta) in videos.iter().enumerate() {
if let Some(start_time) = meta.start_time {
- input.extend(["-ss".to_string(), format_time_delta(start_time)])
+ input.extend(["-ss".to_string(), format_time_delta(&start_time)])
}
input.extend(["-i".to_string(), meta.path.to_string_lossy().to_string()]);
maps.extend(["-map".to_string(), i.to_string()]);
@@ -616,7 +617,7 @@ impl Downloader {
}
for (i, meta) in audios.iter().enumerate() {
if let Some(start_time) = meta.start_time {
- input.extend(["-ss".to_string(), format_time_delta(start_time)])
+ input.extend(["-ss".to_string(), format_time_delta(&start_time)])
}
input.extend(["-i".to_string(), meta.path.to_string_lossy().to_string()]);
maps.extend(["-map".to_string(), (i + videos.len()).to_string()]);
@@ -663,7 +664,7 @@ impl Downloader {
if container_supports_softsubs {
for (i, meta) in subtitles.iter().enumerate() {
if let Some(start_time) = meta.start_time {
- input.extend(["-ss".to_string(), format_time_delta(start_time)])
+ input.extend(["-ss".to_string(), format_time_delta(&start_time)])
}
input.extend(["-i".to_string(), meta.path.to_string_lossy().to_string()]);
maps.extend([
@@ -1390,8 +1391,8 @@ fn fix_subtitles(raw: &mut Vec, max_length: TimeDelta) {
format!(
"Dialogue: {},{},{},",
layer,
- format_time_delta(start),
- format_time_delta(end)
+ format_time_delta(&start),
+ format_time_delta(&end)
),
)
.to_string()
@@ -1665,18 +1666,6 @@ fn check_frame_windows(base_hashes: &[ImageHash], check_hashes: &[ImageHash]) ->
results
}
-fn format_time_delta(time_delta: TimeDelta) -> String {
- let hours = time_delta.num_hours();
- let minutes = time_delta.num_minutes() - time_delta.num_hours() * 60;
- let seconds = time_delta.num_seconds() - time_delta.num_minutes() * 60;
- let milliseconds = time_delta.num_milliseconds() - time_delta.num_seconds() * 1000;
-
- format!(
- "{}:{:0>2}:{:0>2}.{:0>3}",
- hours, minutes, seconds, milliseconds
- )
-}
-
fn len_from_segments(segments: &[StreamSegment]) -> TimeDelta {
TimeDelta::milliseconds(segments.iter().map(|s| s.length.as_millis()).sum::() as i64)
}
diff --git a/crunchy-cli-core/src/utils/fmt.rs b/crunchy-cli-core/src/utils/fmt.rs
new file mode 100644
index 0000000..cd7d81a
--- /dev/null
+++ b/crunchy-cli-core/src/utils/fmt.rs
@@ -0,0 +1,19 @@
+use chrono::TimeDelta;
+
+pub fn format_time_delta(time_delta: &TimeDelta) -> String {
+ let negative = *time_delta < TimeDelta::zero();
+ let time_delta = time_delta.abs();
+ let hours = time_delta.num_hours();
+ let minutes = time_delta.num_minutes() - time_delta.num_hours() * 60;
+ let seconds = time_delta.num_seconds() - time_delta.num_minutes() * 60;
+ let milliseconds = time_delta.num_milliseconds() - time_delta.num_seconds() * 1000;
+
+ format!(
+ "{}{}:{:0>2}:{:0>2}.{:0>3}",
+ if negative { "-" } else { "" },
+ hours,
+ minutes,
+ seconds,
+ milliseconds
+ )
+}
diff --git a/crunchy-cli-core/src/utils/mod.rs b/crunchy-cli-core/src/utils/mod.rs
index e5c4894..72a0908 100644
--- a/crunchy-cli-core/src/utils/mod.rs
+++ b/crunchy-cli-core/src/utils/mod.rs
@@ -3,6 +3,7 @@ pub mod context;
pub mod download;
pub mod ffmpeg;
pub mod filter;
+pub mod fmt;
pub mod format;
pub mod interactive_select;
pub mod locale;
From 72c574c883cef48f59b7dda7eae2e0598e8671fd Mon Sep 17 00:00:00 2001
From: Simon <47527944+Frooastside@users.noreply.github.com>
Date: Thu, 2 May 2024 00:35:13 +0200
Subject: [PATCH 44/82] Switch to audio fingerprinting based syncing (#393)
* rename merge-auto-tolerance -> merge-time-tolerance
* move format_time_delta to own file
* switch to audio fingerprinting based syncing
* move format_time_delta to own file
* simpler approach to determine negative time deltas
* add missing readme part for --sync-precision
* fix all clippy "errors"
* Use rust-native chromaprint port instead of ffmpeg
* buffer with 128kb instead of 32kb
* improve helps
* improve help
---------
Co-authored-by: bytedream
---
Cargo.lock | 96 ++----
README.md | 19 +-
crunchy-cli-core/Cargo.toml | 3 +-
crunchy-cli-core/src/archive/command.rs | 46 ++-
crunchy-cli-core/src/archive/filter.rs | 2 +-
crunchy-cli-core/src/utils/download.rs | 261 +++-----------
crunchy-cli-core/src/utils/format.rs | 2 +-
crunchy-cli-core/src/utils/mod.rs | 1 +
crunchy-cli-core/src/utils/os.rs | 18 +-
crunchy-cli-core/src/utils/sync.rs | 432 ++++++++++++++++++++++++
10 files changed, 555 insertions(+), 325 deletions(-)
create mode 100644 crunchy-cli-core/src/utils/sync.rs
diff --git a/Cargo.lock b/Cargo.lock
index 61832fe..26f81b9 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -179,18 +179,6 @@ version = "3.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c"
-[[package]]
-name = "bytemuck"
-version = "1.15.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5d6d68c57235a3a081186990eca2867354726650f42f7516ca50c28d6281fd15"
-
-[[package]]
-name = "byteorder"
-version = "1.5.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
-
[[package]]
name = "bytes"
version = "1.6.0"
@@ -381,8 +369,6 @@ dependencies = [
"fs2",
"futures-util",
"http",
- "image",
- "image_hasher",
"indicatif",
"lazy_static",
"log",
@@ -391,6 +377,7 @@ dependencies = [
"regex",
"reqwest",
"rustls-native-certs",
+ "rusty-chromaprint",
"serde",
"serde_json",
"serde_plain",
@@ -951,32 +938,6 @@ dependencies = [
"unicode-normalization",
]
-[[package]]
-name = "image"
-version = "0.25.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fd54d660e773627692c524beaad361aca785a4f9f5730ce91f42aabe5bce3d11"
-dependencies = [
- "bytemuck",
- "byteorder",
- "num-traits",
- "zune-core",
- "zune-jpeg",
-]
-
-[[package]]
-name = "image_hasher"
-version = "2.0.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9481465fe767d92494987319b0b447a5829edf57f09c52bf8639396abaaeaf78"
-dependencies = [
- "base64 0.22.0",
- "image",
- "rustdct",
- "serde",
- "transpose",
-]
-
[[package]]
name = "indexmap"
version = "1.9.3"
@@ -1417,6 +1378,15 @@ dependencies = [
"proc-macro2",
]
+[[package]]
+name = "realfft"
+version = "3.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "953d9f7e5cdd80963547b456251296efc2626ed4e3cbf36c869d9564e0220571"
+dependencies = [
+ "rustfft",
+]
+
[[package]]
name = "redox_users"
version = "0.4.5"
@@ -1531,21 +1501,24 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b833d8d034ea094b1ea68aa6d5c740e0d04bad9d16568d08ba6f76823a114316"
+[[package]]
+name = "rubato"
+version = "0.14.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6dd52e80cfc21894deadf554a5673002938ae4625f7a283e536f9cf7c17b0d5"
+dependencies = [
+ "num-complex",
+ "num-integer",
+ "num-traits",
+ "realfft",
+]
+
[[package]]
name = "rustc-demangle"
version = "0.1.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76"
-[[package]]
-name = "rustdct"
-version = "0.7.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8b61555105d6a9bf98797c063c362a1d24ed8ab0431655e38f1cf51e52089551"
-dependencies = [
- "rustfft",
-]
-
[[package]]
name = "rustfft"
version = "6.2.0"
@@ -1628,6 +1601,16 @@ dependencies = [
"untrusted",
]
+[[package]]
+name = "rusty-chromaprint"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1755646867c36ecb391776deaa0b557a76d3badf20c142de7282630c34b20440"
+dependencies = [
+ "rubato",
+ "rustfft",
+]
+
[[package]]
name = "ryu"
version = "1.0.17"
@@ -2501,18 +2484,3 @@ name = "zeroize"
version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63381fa6624bf92130a6b87c0d07380116f80b565c42cf0d754136f0238359ef"
-
-[[package]]
-name = "zune-core"
-version = "0.4.12"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3f423a2c17029964870cfaabb1f13dfab7d092a62a29a89264f4d36990ca414a"
-
-[[package]]
-name = "zune-jpeg"
-version = "0.4.11"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ec866b44a2a1fd6133d363f073ca1b179f438f99e7e5bfb1e33f7181facfe448"
-dependencies = [
- "zune-core",
-]
diff --git a/README.md b/README.md
index 7316f57..1fdf348 100644
--- a/README.md
+++ b/README.md
@@ -462,7 +462,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
In the best case, when multiple audio & subtitle tracks are used, there is only one *video* track and all other languages can be stored as audio-only.
But, as said, this is not always the case.
With the `-m` / `--merge` flag you can define the behaviour when an episodes' video tracks differ in length.
- Valid options are `audio` - store one video and all other languages as audio only; `video` - store the video + audio for every language; `auto` - detect if videos differ in length: if so, behave like `video` - otherwise like `audio`.
+ Valid options are `audio` - store one video and all other languages as audio only; `video` - store the video + audio for every language; `auto` - detect if videos differ in length: if so, behave like `video` - otherwise like `audio`; `sync` - detect if videos differ in length: if so, it tries to find the offset of matching audio parts and removes the offset from the beginning, otherwise it behaves like `audio`.
Subtitles will always match the primary audio and video.
```shell
@@ -482,15 +482,18 @@ The `archive` command lets you download episodes with multiple audios and subtit
Default are `200` milliseconds.
-- Sync start
+- Sync tolerance
- If you want that all videos of the same episode should start at the same time and `--merge` doesn't fit your needs (e.g. one video has an intro, all other doesn't), you might consider using the `--sync-start`.
- It tries to sync the timing of all downloaded audios to match one video.
- This is done by downloading the first few segments/frames of all video tracks that differ in length and comparing them frame by frame.
- The flag takes an optional value determines how accurate the syncing is, generally speaking everything over 15 begins to be more inaccurate and everything below 6 is too accurate (and won't succeed).
- When the syncing fails, the command is continued as if `--sync-start` wasn't provided for this episode.
+ Sometimes two video tracks are downloaded with `--merge` set to `sync` because the audio fingerprinting fails to identify matching audio parts (e.g. opening).
+ To prevent this, you can use the `--sync-tolerance` flag to specify the difference by which two fingerprints are considered equal.
- Default is `7.5`.
+ Default is `6`.
+
+- Sync precision
+
+ If you use `--merge` set to `sync` and the syncing seems to be not accurate enough or takes to long, you can use the `--sync-precision` flag to specify the amount of offset determination runs from which the final offset is calculated.
+
+ Default is `4`.
- Language tagging
diff --git a/crunchy-cli-core/Cargo.toml b/crunchy-cli-core/Cargo.toml
index e31ef46..517284a 100644
--- a/crunchy-cli-core/Cargo.toml
+++ b/crunchy-cli-core/Cargo.toml
@@ -24,14 +24,13 @@ derive_setters = "0.1"
futures-util = { version = "0.3", features = ["io"] }
fs2 = "0.4"
http = "1.1"
-image = { version = "0.25", features = ["jpeg"], default-features = false }
-image_hasher = "2.0"
indicatif = "0.17"
lazy_static = "1.4"
log = { version = "0.4", features = ["std"] }
num_cpus = "1.16"
regex = "1.10"
reqwest = { version = "0.12", features = ["socks", "stream"] }
+rusty-chromaprint = "0.2"
serde = "1.0"
serde_json = "1.0"
serde_plain = "1.0"
diff --git a/crunchy-cli-core/src/archive/command.rs b/crunchy-cli-core/src/archive/command.rs
index 3525a4a..77cf50f 100644
--- a/crunchy-cli-core/src/archive/command.rs
+++ b/crunchy-cli-core/src/archive/command.rs
@@ -90,32 +90,31 @@ pub struct Archive {
pub(crate) resolution: Resolution,
#[arg(
- help = "Sets the behavior of the stream merging. Valid behaviors are 'auto', 'audio' and 'video'"
+ help = "Sets the behavior of the stream merging. Valid behaviors are 'auto', 'sync', 'audio' and 'video'"
)]
#[arg(
long_help = "Because of local restrictions (or other reasons) some episodes with different languages does not have the same length (e.g. when some scenes were cut out). \
With this flag you can set the behavior when handling multiple language.
- Valid options are 'audio' (stores one video and all other languages as audio only), 'video' (stores the video + audio for every language) and 'auto' (detects if videos differ in length: if so, behave like 'video' else like 'audio')"
+ Valid options are 'audio' (stores one video and all other languages as audio only), 'video' (stores the video + audio for every language), 'auto' (detects if videos differ in length: if so, behave like 'video' else like 'audio') and 'sync' (detects if videos differ in length: if so, tries to find the offset of matching audio parts and removes it from the beginning, otherwise it behaves like 'audio')"
)]
#[arg(short, long, default_value = "auto")]
#[arg(value_parser = MergeBehavior::parse)]
pub(crate) merge: MergeBehavior,
#[arg(
- help = "If the merge behavior is 'auto', only download multiple video tracks if their length difference is higher than the given milliseconds"
+ help = "If the merge behavior is 'auto' or 'sync', consider videos to be of equal lengths if the difference in length is smaller than the specified milliseconds"
)]
#[arg(long, default_value_t = 200)]
pub(crate) merge_time_tolerance: u32,
- #[arg(help = "Tries to sync the timing of all downloaded audios to match one video")]
#[arg(
- long_help = "Tries to sync the timing of all downloaded audios to match one video. \
- This is done by downloading the first few segments/frames of all video tracks that differ in length and comparing them frame by frame. \
- The value of this flag determines how accurate the syncing is, generally speaking everything over 15 begins to be more inaccurate and everything below 6 is too accurate (and won't succeed). \
- If you want to provide a custom value to this flag, you have to set it with an equals (e.g. `--sync-start=10` instead of `--sync-start 10`). \
- When the syncing fails, the command is continued as if `--sync-start` wasn't provided for this episode
- "
+ help = "If the merge behavior is 'sync', specify the difference by which two fingerprints are considered equal, higher values can help when the algorithm fails"
)]
- #[arg(long, require_equals = true, num_args = 0..=1, default_missing_value = "7.5")]
- pub(crate) sync_start: Option,
+ #[arg(long, default_value_t = 6)]
+ pub(crate) sync_tolerance: u32,
+ #[arg(
+ help = "If the merge behavior is 'sync', specify the amount of offset determination runs from which the final offset is calculated, higher values will increase the time required but lead to more precise offsets"
+ )]
+ #[arg(long, default_value_t = 4)]
+ pub(crate) sync_precision: u32,
#[arg(
help = "Specified which language tagging the audio and subtitle tracks and language specific format options should have. \
@@ -229,18 +228,10 @@ impl Execute for Archive {
}
if self.include_chapters
+ && !matches!(self.merge, MergeBehavior::Sync)
&& !matches!(self.merge, MergeBehavior::Audio)
- && self.sync_start.is_none()
{
- bail!("`--include-chapters` can only be used if `--merge` is set to 'audio' or `--sync-start` is set")
- }
-
- if !matches!(self.merge, MergeBehavior::Auto) && self.sync_start.is_some() {
- bail!("`--sync-start` can only be used if `--merge` is set to `auto`")
- }
-
- if self.sync_start.is_some() && self.ffmpeg_preset.is_none() {
- warn!("Using `--sync-start` without `--ffmpeg-preset` might produce worse sync results than with `--ffmpeg-preset` set")
+ bail!("`--include-chapters` can only be used if `--merge` is set to 'audio' or 'sync'")
}
self.audio = all_locale_in_locales(self.audio.clone());
@@ -317,7 +308,14 @@ impl Execute for Archive {
.audio_sort(Some(self.audio.clone()))
.subtitle_sort(Some(self.subtitle.clone()))
.no_closed_caption(self.no_closed_caption)
- .sync_start_value(self.sync_start)
+ .sync_tolerance(match self.merge {
+ MergeBehavior::Sync => Some(self.sync_tolerance),
+ _ => None,
+ })
+ .sync_precision(match self.merge {
+ MergeBehavior::Sync => Some(self.sync_precision),
+ _ => None,
+ })
.threads(self.threads)
.audio_locale_output_map(
zip(self.audio.clone(), self.output_audio_locales.clone()).collect(),
@@ -560,7 +558,7 @@ async fn get_format(
},
},
}),
- MergeBehavior::Auto => {
+ MergeBehavior::Auto | MergeBehavior::Sync => {
let mut d_formats: Vec<(Duration, DownloadFormat)> = vec![];
for (single_format, video, audio, subtitles) in format_pairs {
diff --git a/crunchy-cli-core/src/archive/filter.rs b/crunchy-cli-core/src/archive/filter.rs
index f638c50..b08fb6c 100644
--- a/crunchy-cli-core/src/archive/filter.rs
+++ b/crunchy-cli-core/src/archive/filter.rs
@@ -333,7 +333,7 @@ impl Filter for ArchiveFilter {
.unwrap()
.push(episode.season_number)
}
-
+
if episodes.is_empty() {
return Ok(None);
}
diff --git a/crunchy-cli-core/src/utils/download.rs b/crunchy-cli-core/src/utils/download.rs
index bd7bf3d..cfec7b4 100644
--- a/crunchy-cli-core/src/utils/download.rs
+++ b/crunchy-cli-core/src/utils/download.rs
@@ -2,15 +2,13 @@ use crate::utils::ffmpeg::FFmpegPreset;
use crate::utils::filter::real_dedup_vec;
use crate::utils::fmt::format_time_delta;
use crate::utils::log::progress;
-use crate::utils::os::{
- cache_dir, is_special_file, temp_directory, temp_named_pipe, tempdir, tempfile,
-};
+use crate::utils::os::{cache_dir, is_special_file, temp_directory, temp_named_pipe, tempfile};
use crate::utils::rate_limit::RateLimiterService;
+use crate::utils::sync::{sync_audios, SyncAudio};
use anyhow::{bail, Result};
use chrono::{NaiveTime, TimeDelta};
use crunchyroll_rs::media::{SkipEvents, SkipEventsEvent, StreamData, StreamSegment, Subtitle};
use crunchyroll_rs::Locale;
-use image_hasher::{Hasher, HasherConfig, ImageHash};
use indicatif::{ProgressBar, ProgressDrawTarget, ProgressFinish, ProgressStyle};
use log::{debug, warn, LevelFilter};
use regex::Regex;
@@ -39,6 +37,7 @@ pub enum MergeBehavior {
Video,
Audio,
Auto,
+ Sync,
}
impl MergeBehavior {
@@ -47,6 +46,7 @@ impl MergeBehavior {
"video" => MergeBehavior::Video,
"audio" => MergeBehavior::Audio,
"auto" => MergeBehavior::Auto,
+ "sync" => MergeBehavior::Sync,
_ => return Err(format!("'{}' is not a valid merge behavior", s)),
})
}
@@ -64,7 +64,8 @@ pub struct DownloadBuilder {
force_hardsub: bool,
download_fonts: bool,
no_closed_caption: bool,
- sync_start_value: Option,
+ sync_tolerance: Option,
+ sync_precision: Option,
threads: usize,
ffmpeg_threads: Option,
audio_locale_output_map: HashMap,
@@ -84,7 +85,8 @@ impl DownloadBuilder {
force_hardsub: false,
download_fonts: false,
no_closed_caption: false,
- sync_start_value: None,
+ sync_tolerance: None,
+ sync_precision: None,
threads: num_cpus::get(),
ffmpeg_threads: None,
audio_locale_output_map: HashMap::new(),
@@ -106,7 +108,8 @@ impl DownloadBuilder {
download_fonts: self.download_fonts,
no_closed_caption: self.no_closed_caption,
- sync_start_value: self.sync_start_value,
+ sync_tolerance: self.sync_tolerance,
+ sync_precision: self.sync_precision,
download_threads: self.threads,
ffmpeg_threads: self.ffmpeg_threads,
@@ -165,7 +168,8 @@ pub struct Downloader {
download_fonts: bool,
no_closed_caption: bool,
- sync_start_value: Option,
+ sync_tolerance: Option,
+ sync_precision: Option,
download_threads: usize,
ffmpeg_threads: Option,
@@ -245,6 +249,7 @@ impl Downloader {
let mut video_offset = None;
let mut audio_offsets = HashMap::new();
let mut subtitle_offsets = HashMap::new();
+ let mut raw_audios = vec![];
let mut videos = vec![];
let mut audios = vec![];
let mut subtitles = vec![];
@@ -263,40 +268,33 @@ impl Downloader {
.max()
.unwrap();
- if self.formats.len() > 1 && self.sync_start_value.is_some() {
- let all_segments_count: Vec = self
- .formats
- .iter()
- .map(|f| f.video.0.segments().len())
- .collect();
- let sync_segments = 11.max(
- all_segments_count.iter().max().unwrap() - all_segments_count.iter().min().unwrap(),
- );
- let mut sync_vids = vec![];
- for (i, format) in self.formats.iter().enumerate() {
+ // downloads all audios
+ for (i, format) in self.formats.iter().enumerate() {
+ for (stream_data, locale) in &format.audios {
let path = self
- .download_video(
- &format.video.0,
- format!("Downloading video #{} sync segments", i + 1),
- Some(sync_segments),
+ .download_audio(
+ stream_data,
+ format!("{:<1$}", format!("Downloading {} audio", locale), fmt_space),
)
.await?;
- sync_vids.push(SyncVideo {
+ raw_audios.push(SyncAudio {
+ format_id: i,
path,
- length: len_from_segments(&format.video.0.segments()),
- available_frames: (len_from_segments(
- &format.video.0.segments()[0..sync_segments],
- )
- .num_milliseconds() as f64
- * format.video.0.fps().unwrap()
- / 1000.0) as u64,
- idx: i,
+ locale: locale.clone(),
+ sample_rate: stream_data.sampling_rate().unwrap(),
+ video_idx: i,
})
}
+ }
+ if self.formats.len() > 1 && self.sync_tolerance.is_some() {
let _progress_handler =
progress!("Syncing video start times (this might take some time)");
- let mut offsets = sync_videos(sync_vids, self.sync_start_value.unwrap())?;
+ let mut offsets = sync_audios(
+ &raw_audios,
+ self.sync_tolerance.unwrap(),
+ self.sync_precision.unwrap(),
+ )?;
drop(_progress_handler);
let mut offset_pre_checked = false;
@@ -307,19 +305,14 @@ impl Downloader {
.enumerate()
.map(|(i, f)| {
len_from_segments(&f.video.0.segments())
- - TimeDelta::milliseconds(
- tmp_offsets
- .get(&i)
- .map(|o| (*o as f64 / f.video.0.fps().unwrap() * 1000.0) as i64)
- .unwrap_or_default(),
- )
+ - tmp_offsets.get(&i).copied().unwrap_or_default()
})
.collect();
let min = formats_with_offset.iter().min().unwrap();
let max = formats_with_offset.iter().max().unwrap();
if max.num_seconds() - min.num_seconds() > 15 {
- warn!("Found difference of >15 seconds after sync, skipping applying it");
+ warn!("Found difference of >15 seconds after sync, so the application was skipped");
offsets = None;
offset_pre_checked = true
}
@@ -331,7 +324,7 @@ impl Downloader {
let mut audio_count: usize = 0;
let mut subtitle_count: usize = 0;
for (i, format) in self.formats.iter().enumerate() {
- let format_fps = format.video.0.fps().unwrap();
+ let offset = offsets.get(&i).copied().unwrap_or_default();
let format_len = format
.video
.0
@@ -339,7 +332,7 @@ impl Downloader {
.iter()
.map(|s| s.length.as_millis())
.sum::() as u64
- - offsets.get(&i).map_or(0, |o| *o);
+ - offset.num_milliseconds() as u64;
if format_len > root_format_length {
root_format_idx = i;
root_format_length = format_len;
@@ -347,23 +340,13 @@ impl Downloader {
for _ in &format.audios {
if let Some(offset) = &offsets.get(&i) {
- audio_offsets.insert(
- audio_count,
- TimeDelta::milliseconds(
- (**offset as f64 / format_fps * 1000.0) as i64,
- ),
- );
+ audio_offsets.insert(audio_count, **offset);
}
audio_count += 1
}
for _ in &format.subtitles {
if let Some(offset) = &offsets.get(&i) {
- subtitle_offsets.insert(
- subtitle_count,
- TimeDelta::milliseconds(
- (**offset as f64 / format_fps * 1000.0) as i64,
- ),
- );
+ subtitle_offsets.insert(subtitle_count, **offset);
}
subtitle_count += 1
}
@@ -390,20 +373,28 @@ impl Downloader {
root_format.subtitles.extend(subtitle_append);
self.formats = vec![root_format];
- video_offset = offsets.get(&root_format_idx).map(|o| {
- TimeDelta::milliseconds(
- (*o as f64 / self.formats[0].video.0.fps().unwrap() * 1000.0) as i64,
- )
- })
+ video_offset = offsets.get(&root_format_idx).copied();
+ for raw_audio in raw_audios.iter_mut() {
+ raw_audio.video_idx = root_format_idx;
+ }
} else {
for format in &mut self.formats {
format.metadata.skip_events = None
}
+ if !offset_pre_checked {
+ warn!("Couldn't find reliable sync positions")
+ }
}
+ }
- if !offset_pre_checked {
- warn!("Couldn't find reliable sync positions")
- }
+ // add audio metadata
+ for raw_audio in raw_audios {
+ audios.push(FFmpegAudioMeta {
+ path: raw_audio.path,
+ locale: raw_audio.locale,
+ start_time: audio_offsets.get(&raw_audio.format_id).copied(),
+ video_idx: raw_audio.video_idx,
+ })
}
// downloads all videos
@@ -435,24 +426,6 @@ impl Downloader {
})
}
- // downloads all audios
- for (i, format) in self.formats.iter().enumerate() {
- for (j, (stream_data, locale)) in format.audios.iter().enumerate() {
- let path = self
- .download_audio(
- stream_data,
- format!("{:<1$}", format!("Downloading {} audio", locale), fmt_space),
- )
- .await?;
- audios.push(FFmpegAudioMeta {
- path,
- locale: locale.clone(),
- start_time: audio_offsets.get(&j).cloned(),
- video_idx: i,
- })
- }
- }
-
for (i, format) in self.formats.iter().enumerate() {
if format.subtitles.is_empty() {
continue;
@@ -1538,134 +1511,6 @@ async fn ffmpeg_progress(
Ok(())
}
-struct SyncVideo {
- path: TempPath,
- length: TimeDelta,
- available_frames: u64,
- idx: usize,
-}
-
-fn sync_videos(mut sync_videos: Vec, value: f64) -> Result>> {
- let mut result = HashMap::new();
- let hasher = HasherConfig::new().preproc_dct().to_hasher();
- let start_frame = 300;
-
- sync_videos.sort_by_key(|sv| sv.length);
-
- let sync_base = sync_videos.remove(0);
- let sync_hashes = extract_frame_hashes(&sync_base.path, start_frame, 50, &hasher)?;
-
- for sync_video in sync_videos {
- let mut highest_frame_match = f64::INFINITY;
- let mut frame = start_frame;
- let mut hashes = vec![];
-
- loop {
- if frame == sync_video.available_frames {
- debug!(
- "Failed to sync videos, end of stream {} reached (highest frame match: {})",
- sync_video.idx + 1,
- highest_frame_match
- );
- return Ok(None);
- }
-
- hashes.drain(0..(hashes.len() as i32 - sync_hashes.len() as i32).max(0) as usize);
- hashes.extend(extract_frame_hashes(
- &sync_video.path,
- frame,
- 300 - hashes.len() as u64,
- &hasher,
- )?);
-
- let mut check_frame_windows_result: Vec<(usize, f64)> =
- check_frame_windows(&sync_hashes, &hashes)
- .into_iter()
- .enumerate()
- .collect();
- check_frame_windows_result.sort_by(|(_, a), (_, b)| a.partial_cmp(&b).unwrap());
- if check_frame_windows_result[0].1 <= value {
- result.insert(
- sync_video.idx,
- frame + check_frame_windows_result[0].0 as u64 - start_frame,
- );
- break;
- } else if check_frame_windows_result[0].1 < highest_frame_match {
- highest_frame_match = check_frame_windows_result[0].1
- }
-
- frame = (frame + 300 - sync_hashes.len() as u64).min(sync_video.available_frames)
- }
- }
-
- Ok(Some(result))
-}
-
-fn extract_frame_hashes(
- input_file: &Path,
- start_frame: u64,
- frame_count: u64,
- hasher: &Hasher,
-) -> Result> {
- let frame_dir = tempdir(format!(
- "{}_sync_frames",
- input_file
- .file_name()
- .unwrap_or_default()
- .to_string_lossy()
- .trim_end_matches(
- &input_file
- .file_stem()
- .unwrap_or_default()
- .to_string_lossy()
- .to_string()
- )
- ))?;
- let extract_output = Command::new("ffmpeg")
- .arg("-hide_banner")
- .arg("-y")
- .args(["-i", input_file.to_string_lossy().to_string().as_str()])
- .args([
- "-vf",
- format!(
- r#"select=between(n\,{}\,{}),setpts=PTS-STARTPTS,scale=-1:240"#,
- start_frame,
- start_frame + frame_count
- )
- .as_str(),
- ])
- .args(["-vframes", frame_count.to_string().as_str()])
- .arg(format!("{}/%03d.jpg", frame_dir.path().to_string_lossy()))
- .output()?;
- if !extract_output.status.success() {
- bail!(
- "{}",
- String::from_utf8_lossy(extract_output.stderr.as_slice())
- )
- }
-
- let mut hashes = vec![];
- for file in frame_dir.path().read_dir()? {
- let file = file?;
- let img = image::open(file.path())?;
- hashes.push(hasher.hash_image(&img))
- }
- Ok(hashes)
-}
-
-fn check_frame_windows(base_hashes: &[ImageHash], check_hashes: &[ImageHash]) -> Vec {
- let mut results = vec![];
-
- for i in 0..(check_hashes.len() - base_hashes.len()) {
- let check_window = &check_hashes[i..(base_hashes.len() + i)];
- let sum = std::iter::zip(base_hashes, check_window)
- .map(|(a, b)| a.dist(b))
- .sum::();
- results.push(sum as f64 / check_window.len() as f64);
- }
- results
-}
-
fn len_from_segments(segments: &[StreamSegment]) -> TimeDelta {
TimeDelta::milliseconds(segments.iter().map(|s| s.length.as_millis()).sum::() as i64)
}
diff --git a/crunchy-cli-core/src/utils/format.rs b/crunchy-cli-core/src/utils/format.rs
index 1987e87..0a71838 100644
--- a/crunchy-cli-core/src/utils/format.rs
+++ b/crunchy-cli-core/src/utils/format.rs
@@ -544,7 +544,7 @@ impl Format {
path.set_file_name(format!("{}.{}", &name[..(255 - ext.len() - 1)], ext))
}
}
- path.into_iter()
+ path.iter()
.map(|s| {
if s.len() > 255 {
s.to_string_lossy()[..255].to_string()
diff --git a/crunchy-cli-core/src/utils/mod.rs b/crunchy-cli-core/src/utils/mod.rs
index 72a0908..6260047 100644
--- a/crunchy-cli-core/src/utils/mod.rs
+++ b/crunchy-cli-core/src/utils/mod.rs
@@ -11,4 +11,5 @@ pub mod log;
pub mod os;
pub mod parse;
pub mod rate_limit;
+pub mod sync;
pub mod video;
diff --git a/crunchy-cli-core/src/utils/os.rs b/crunchy-cli-core/src/utils/os.rs
index b65abc2..a216f87 100644
--- a/crunchy-cli-core/src/utils/os.rs
+++ b/crunchy-cli-core/src/utils/os.rs
@@ -7,7 +7,7 @@ use std::pin::Pin;
use std::process::{Command, Stdio};
use std::task::{Context, Poll};
use std::{env, fs, io};
-use tempfile::{Builder, NamedTempFile, TempDir, TempPath};
+use tempfile::{Builder, NamedTempFile, TempPath};
use tokio::io::{AsyncRead, ReadBuf};
pub fn has_ffmpeg() -> bool {
@@ -46,22 +46,6 @@ pub fn tempfile>(suffix: S) -> io::Result {
Ok(tempfile)
}
-/// Any tempdir should be created with this function. The prefix and directory of every directory
-/// created with this function stays the same which is helpful to query all existing tempdirs and
-/// e.g. remove them in a case of ctrl-c. Having one function also good to prevent mistakes like
-/// setting the wrong prefix if done manually.
-pub fn tempdir>(suffix: S) -> io::Result {
- let tempdir = Builder::default()
- .prefix(".crunchy-cli_")
- .suffix(suffix.as_ref())
- .tempdir_in(temp_directory())?;
- debug!(
- "Created temporary directory: {}",
- tempdir.path().to_string_lossy()
- );
- Ok(tempdir)
-}
-
pub fn cache_dir>(name: S) -> io::Result {
let cache_dir = temp_directory().join(format!(".crunchy-cli_{}_cache", name.as_ref()));
fs::create_dir_all(&cache_dir)?;
diff --git a/crunchy-cli-core/src/utils/sync.rs b/crunchy-cli-core/src/utils/sync.rs
new file mode 100644
index 0000000..1e9bc42
--- /dev/null
+++ b/crunchy-cli-core/src/utils/sync.rs
@@ -0,0 +1,432 @@
+use std::io::Read;
+use std::process::Stdio;
+use std::{
+ cmp,
+ collections::{HashMap, HashSet},
+ mem,
+ ops::Not,
+ path::Path,
+ process::Command,
+};
+
+use chrono::TimeDelta;
+use crunchyroll_rs::Locale;
+use log::debug;
+use tempfile::TempPath;
+
+use anyhow::{bail, Result};
+use rusty_chromaprint::{Configuration, Fingerprinter};
+
+use super::fmt::format_time_delta;
+
+pub struct SyncAudio {
+ pub format_id: usize,
+ pub path: TempPath,
+ pub locale: Locale,
+ pub sample_rate: u32,
+ pub video_idx: usize,
+}
+
+#[derive(Debug, Clone, Copy)]
+struct TimeRange {
+ start: f64,
+ end: f64,
+}
+
+pub fn sync_audios(
+ available_audios: &Vec,
+ sync_tolerance: u32,
+ sync_precision: u32,
+) -> Result>> {
+ let mut result: HashMap = HashMap::new();
+
+ let mut sync_audios = vec![];
+ let mut chromaprints = HashMap::new();
+ let mut formats = HashSet::new();
+ for audio in available_audios {
+ if formats.contains(&audio.format_id) {
+ continue;
+ }
+ formats.insert(audio.format_id);
+ sync_audios.push((audio.format_id, &audio.path, audio.sample_rate));
+ chromaprints.insert(
+ audio.format_id,
+ generate_chromaprint(
+ &audio.path,
+ audio.sample_rate,
+ &TimeDelta::zero(),
+ &TimeDelta::zero(),
+ &TimeDelta::zero(),
+ )?,
+ );
+ }
+ sync_audios.sort_by_key(|sync_audio| chromaprints.get(&sync_audio.0).unwrap().len());
+
+ let base_audio = sync_audios.remove(0);
+
+ let mut start = f64::MAX;
+ let mut end = f64::MIN;
+ let mut initial_offsets = HashMap::new();
+ for audio in &sync_audios {
+ debug!(
+ "Initial comparison of format {} to {}",
+ audio.0, &base_audio.0
+ );
+
+ let (lhs_ranges, rhs_ranges) = compare_chromaprints(
+ chromaprints.get(&base_audio.0).unwrap(),
+ chromaprints.get(&audio.0).unwrap(),
+ sync_tolerance,
+ );
+ if lhs_ranges.is_empty() || rhs_ranges.is_empty() {
+ bail!(
+ "Failed to sync videos, couldn't find matching audio parts between format {} and {}",
+ base_audio.0 + 1,
+ audio.0 + 1
+ );
+ }
+ let lhs_range = lhs_ranges[0];
+ let rhs_range = rhs_ranges[0];
+ start = start.min(lhs_range.start);
+ end = end.max(lhs_range.end);
+ start = start.min(rhs_range.start);
+ end = end.max(rhs_range.end);
+ let offset = TimeDelta::milliseconds(((rhs_range.start - lhs_range.start) * 1000.0) as i64);
+ initial_offsets.insert(audio.0, TimeDelta::zero().checked_sub(&offset).unwrap());
+ debug!(
+ "Found initial offset of {}ms ({} - {} {}s) ({} - {} {}s) for format {} to {}",
+ offset.num_milliseconds(),
+ lhs_range.start,
+ lhs_range.end,
+ lhs_range.end - lhs_range.start,
+ rhs_range.start,
+ rhs_range.end,
+ rhs_range.end - rhs_range.start,
+ audio.0,
+ base_audio.0
+ );
+ }
+
+ debug!(
+ "Found matching audio parts at {} - {}, narrowing search",
+ start, end
+ );
+
+ let start = TimeDelta::milliseconds((start * 1000.0) as i64 - 20000);
+ let end = TimeDelta::milliseconds((end * 1000.0) as i64 + 20000);
+
+ for sync_audio in &sync_audios {
+ let chromaprint = generate_chromaprint(
+ sync_audio.1,
+ sync_audio.2,
+ &start,
+ &end,
+ initial_offsets.get(&sync_audio.0).unwrap(),
+ )?;
+ chromaprints.insert(sync_audio.0, chromaprint);
+ }
+
+ let mut runs: HashMap = HashMap::new();
+ let iterator_range_limits: i64 = 2 ^ sync_precision as i64;
+ for i in -iterator_range_limits..=iterator_range_limits {
+ let base_offset = TimeDelta::milliseconds(
+ ((0.128 / iterator_range_limits as f64 * i as f64) * 1000.0) as i64,
+ );
+ chromaprints.insert(
+ base_audio.0,
+ generate_chromaprint(base_audio.1, base_audio.2, &start, &end, &base_offset)?,
+ );
+ for audio in &sync_audios {
+ let initial_offset = initial_offsets.get(&audio.0).copied().unwrap();
+ let offset = find_offset(
+ (&base_audio.0, chromaprints.get(&base_audio.0).unwrap()),
+ &base_offset,
+ (&audio.0, chromaprints.get(&audio.0).unwrap()),
+ &initial_offset,
+ &start,
+ sync_tolerance,
+ );
+ if offset.is_none() {
+ continue;
+ }
+ let offset = offset.unwrap();
+
+ result.insert(
+ audio.0,
+ result
+ .get(&audio.0)
+ .copied()
+ .unwrap_or_default()
+ .checked_add(&offset)
+ .unwrap(),
+ );
+ runs.insert(audio.0, runs.get(&audio.0).copied().unwrap_or_default() + 1);
+ }
+ }
+ let mut result: HashMap = result
+ .iter()
+ .map(|(format_id, offset)| {
+ (
+ *format_id,
+ TimeDelta::milliseconds(
+ offset.num_milliseconds() / runs.get(format_id).copied().unwrap(),
+ ),
+ )
+ })
+ .collect();
+ result.insert(base_audio.0, TimeDelta::milliseconds(0));
+
+ Ok(Some(result))
+}
+
+fn find_offset(
+ lhs: (&usize, &Vec),
+ lhs_shift: &TimeDelta,
+ rhs: (&usize, &Vec),
+ rhs_shift: &TimeDelta,
+ start: &TimeDelta,
+ sync_tolerance: u32,
+) -> Option {
+ let (lhs_ranges, rhs_ranges) = compare_chromaprints(lhs.1, rhs.1, sync_tolerance);
+ if lhs_ranges.is_empty() || rhs_ranges.is_empty() {
+ return None;
+ }
+ let lhs_range = lhs_ranges[0];
+ let rhs_range = rhs_ranges[0];
+ let offset = rhs_range.end - lhs_range.end;
+ let offset = TimeDelta::milliseconds((offset * 1000.0) as i64)
+ .checked_add(lhs_shift)?
+ .checked_sub(rhs_shift)?;
+ debug!(
+ "Found offset of {}ms ({} - {} {}s) ({} - {} {}s) for format {} to {}",
+ offset.num_milliseconds(),
+ lhs_range.start + start.num_milliseconds() as f64 / 1000.0,
+ lhs_range.end + start.num_milliseconds() as f64 / 1000.0,
+ lhs_range.end - lhs_range.start,
+ rhs_range.start + start.num_milliseconds() as f64 / 1000.0,
+ rhs_range.end + start.num_milliseconds() as f64 / 1000.0,
+ rhs_range.end - rhs_range.start,
+ rhs.0,
+ lhs.0
+ );
+ Some(offset)
+}
+
+fn generate_chromaprint(
+ input_file: &Path,
+ sample_rate: u32,
+ start: &TimeDelta,
+ end: &TimeDelta,
+ offset: &TimeDelta,
+) -> Result> {
+ let mut ss_argument: &TimeDelta = &start.checked_sub(offset).unwrap();
+ let mut offset_argument = &TimeDelta::zero();
+ if *offset < TimeDelta::zero() {
+ ss_argument = start;
+ offset_argument = offset;
+ };
+
+ let mut printer = Fingerprinter::new(&Configuration::preset_test1());
+ printer.start(sample_rate, 2)?;
+
+ let mut command = Command::new("ffmpeg");
+ command
+ .arg("-hide_banner")
+ .arg("-y")
+ .args(["-ss", format_time_delta(ss_argument).as_str()]);
+
+ if end.is_zero().not() {
+ command.args(["-to", format_time_delta(end).as_str()]);
+ }
+
+ command
+ .args(["-itsoffset", format_time_delta(offset_argument).as_str()])
+ .args(["-i", input_file.to_string_lossy().to_string().as_str()])
+ .args(["-ac", "2"])
+ .args([
+ "-f",
+ if cfg!(target_endian = "big") {
+ "s16be"
+ } else {
+ "s16le"
+ },
+ ])
+ .arg("-");
+
+ let mut handle = command
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()?;
+
+ // the stdout is read in chunks because keeping all the raw audio data in memory would take up
+ // a significant amount of space
+ let mut stdout = handle.stdout.take().unwrap();
+ let mut buf: [u8; 128_000] = [0; 128_000];
+ while handle.try_wait()?.is_none() {
+ loop {
+ let read_bytes = stdout.read(&mut buf)?;
+ if read_bytes == 0 {
+ break;
+ }
+ let data: [i16; 64_000] = unsafe { mem::transmute(buf) };
+ printer.consume(&data[0..(read_bytes / 2)])
+ }
+ }
+
+ if !handle.wait()?.success() {
+ bail!("{}", std::io::read_to_string(handle.stderr.unwrap())?)
+ }
+
+ printer.finish();
+ return Ok(printer.fingerprint().into());
+}
+
+fn compare_chromaprints(
+ lhs_chromaprint: &Vec,
+ rhs_chromaprint: &Vec,
+ sync_tolerance: u32,
+) -> (Vec, Vec) {
+ let lhs_inverse_index = create_inverse_index(lhs_chromaprint);
+ let rhs_inverse_index = create_inverse_index(rhs_chromaprint);
+
+ let mut possible_shifts = HashSet::new();
+ for lhs_pair in lhs_inverse_index {
+ let original_point = lhs_pair.0;
+ for i in -2..=2 {
+ let modified_point = (original_point as i32 + i) as u32;
+ if rhs_inverse_index.contains_key(&modified_point) {
+ let rhs_index = rhs_inverse_index.get(&modified_point).copied().unwrap();
+ possible_shifts.insert(rhs_index as i32 - lhs_pair.1 as i32);
+ }
+ }
+ }
+
+ let mut all_lhs_time_ranges = vec![];
+ let mut all_rhs_time_ranges = vec![];
+ for shift_amount in possible_shifts {
+ let time_range_pair = find_time_ranges(
+ lhs_chromaprint,
+ rhs_chromaprint,
+ shift_amount,
+ sync_tolerance,
+ );
+ if time_range_pair.is_none() {
+ continue;
+ }
+ let (mut lhs_time_ranges, mut rhs_time_ranges) = time_range_pair.unwrap();
+ let mut lhs_time_ranges: Vec = lhs_time_ranges
+ .drain(..)
+ .filter(|time_range| {
+ (20.0 < (time_range.end - time_range.start))
+ && ((time_range.end - time_range.start) < 180.0)
+ && time_range.end > 0.0
+ })
+ .collect();
+ lhs_time_ranges.sort_by(|a, b| (b.end - b.start).total_cmp(&(a.end - a.start)));
+ let mut rhs_time_ranges: Vec = rhs_time_ranges
+ .drain(..)
+ .filter(|time_range| {
+ (20.0 < (time_range.end - time_range.start))
+ && ((time_range.end - time_range.start) < 180.0)
+ && time_range.end > 0.0
+ })
+ .collect();
+ rhs_time_ranges.sort_by(|a, b| (b.end - b.start).total_cmp(&(a.end - a.start)));
+ if lhs_time_ranges.is_empty() || rhs_time_ranges.is_empty() {
+ continue;
+ }
+
+ all_lhs_time_ranges.push(lhs_time_ranges[0]);
+ all_rhs_time_ranges.push(rhs_time_ranges[0]);
+ }
+ all_lhs_time_ranges.sort_by(|a, b| (a.end - a.start).total_cmp(&(b.end - b.start)));
+ all_lhs_time_ranges.reverse();
+ all_rhs_time_ranges.sort_by(|a, b| (a.end - a.start).total_cmp(&(b.end - b.start)));
+ all_rhs_time_ranges.reverse();
+
+ (all_lhs_time_ranges, all_rhs_time_ranges)
+}
+
+fn create_inverse_index(chromaprint: &Vec) -> HashMap {
+ let mut inverse_index = HashMap::with_capacity(chromaprint.capacity());
+ for (i, fingerprint) in chromaprint.iter().enumerate().take(chromaprint.capacity()) {
+ inverse_index.insert(*fingerprint, i);
+ }
+ inverse_index
+}
+
+fn find_time_ranges(
+ lhs_chromaprint: &[u32],
+ rhs_chromaprint: &[u32],
+ shift_amount: i32,
+ sync_tolerance: u32,
+) -> Option<(Vec, Vec)> {
+ let mut lhs_shift: i32 = 0;
+ let mut rhs_shift: i32 = 0;
+ if shift_amount < 0 {
+ lhs_shift -= shift_amount;
+ } else {
+ rhs_shift += shift_amount;
+ }
+
+ let mut lhs_matching_timestamps = vec![];
+ let mut rhs_matching_timestamps = vec![];
+ let upper_limit =
+ cmp::min(lhs_chromaprint.len(), rhs_chromaprint.len()) as i32 - shift_amount.abs();
+
+ for i in 0..upper_limit {
+ let lhs_position = i + lhs_shift;
+ let rhs_position = i + rhs_shift;
+ let difference = (lhs_chromaprint[lhs_position as usize]
+ ^ rhs_chromaprint[rhs_position as usize])
+ .count_ones();
+
+ if difference > sync_tolerance {
+ continue;
+ }
+
+ lhs_matching_timestamps.push(lhs_position as f64 * 0.128);
+ rhs_matching_timestamps.push(rhs_position as f64 * 0.128);
+ }
+ lhs_matching_timestamps.push(f64::MAX);
+ rhs_matching_timestamps.push(f64::MAX);
+
+ let lhs_time_ranges = timestamps_to_ranges(lhs_matching_timestamps);
+ lhs_time_ranges.as_ref()?;
+ let lhs_time_ranges = lhs_time_ranges.unwrap();
+ let rhs_time_ranges = timestamps_to_ranges(rhs_matching_timestamps).unwrap();
+
+ Some((lhs_time_ranges, rhs_time_ranges))
+}
+
+fn timestamps_to_ranges(mut timestamps: Vec) -> Option> {
+ if timestamps.is_empty() {
+ return None;
+ }
+
+ timestamps.sort_by(|a, b| a.total_cmp(b));
+
+ let mut time_ranges = vec![];
+ let mut current_range = TimeRange {
+ start: timestamps[0],
+ end: timestamps[0],
+ };
+
+ for i in 0..timestamps.len() - 1 {
+ let current = timestamps[i];
+ let next = timestamps[i + 1];
+ if next - current <= 1.0 {
+ current_range.end = next;
+ continue;
+ }
+
+ time_ranges.push(current_range);
+ current_range.start = next;
+ current_range.end = next;
+ }
+ if !time_ranges.is_empty() {
+ Some(time_ranges)
+ } else {
+ None
+ }
+}
From 173292ff32f338cff8900b87e6d0f16ae9a5172d Mon Sep 17 00:00:00 2001
From: bytedream
Date: Thu, 2 May 2024 17:00:58 +0200
Subject: [PATCH 45/82] Prettify negated subtitle cc boolean
---
crunchy-cli-core/src/archive/command.rs | 6 +++---
crunchy-cli-core/src/download/command.rs | 4 ++--
crunchy-cli-core/src/utils/download.rs | 14 +++++++-------
3 files changed, 12 insertions(+), 12 deletions(-)
diff --git a/crunchy-cli-core/src/archive/command.rs b/crunchy-cli-core/src/archive/command.rs
index 77cf50f..efb54f4 100644
--- a/crunchy-cli-core/src/archive/command.rs
+++ b/crunchy-cli-core/src/archive/command.rs
@@ -501,15 +501,15 @@ async fn get_format(
.subtitles
.get(s)
.cloned()
- // the subtitle is probably not cc if the audio is japanese or more than one
+ // the subtitle is probably cc if the audio is not japanese or only one
// subtitle exists for this stream
.map(|l| {
(
l,
- single_format.audio == Locale::ja_JP || stream.subtitles.len() > 1,
+ single_format.audio != Locale::ja_JP && stream.subtitles.len() == 1,
)
});
- let cc = stream.captions.get(s).cloned().map(|l| (l, false));
+ let cc = stream.captions.get(s).cloned().map(|l| (l, true));
subtitles
.into_iter()
diff --git a/crunchy-cli-core/src/download/command.rs b/crunchy-cli-core/src/download/command.rs
index 44c3d65..bb0c1fd 100644
--- a/crunchy-cli-core/src/download/command.rs
+++ b/crunchy-cli-core/src/download/command.rs
@@ -400,7 +400,7 @@ async fn get_format(
subtitles: subtitle.clone().map_or(vec![], |s| {
vec![(
s,
- single_format.audio == Locale::ja_JP || stream.subtitles.len() > 1,
+ single_format.audio != Locale::ja_JP && stream.subtitles.len() == 1,
)]
}),
metadata: DownloadFormatMetadata {
@@ -417,7 +417,7 @@ async fn get_format(
subtitle.map_or(vec![], |s| {
vec![(
s,
- single_format.audio == Locale::ja_JP || stream.subtitles.len() > 1,
+ single_format.audio != Locale::ja_JP && stream.subtitles.len() == 1,
)]
}),
)]);
diff --git a/crunchy-cli-core/src/utils/download.rs b/crunchy-cli-core/src/utils/download.rs
index cfec7b4..2278bef 100644
--- a/crunchy-cli-core/src/utils/download.rs
+++ b/crunchy-cli-core/src/utils/download.rs
@@ -232,13 +232,13 @@ impl Downloader {
if let Some(subtitle_sort) = &self.subtitle_sort {
format
.subtitles
- .sort_by(|(a_subtitle, a_not_cc), (b_subtitle, b_not_cc)| {
+ .sort_by(|(a_subtitle, a_cc), (b_subtitle, b_cc)| {
let ordering = subtitle_sort
.iter()
.position(|l| l == &a_subtitle.locale)
.cmp(&subtitle_sort.iter().position(|l| l == &b_subtitle.locale));
if matches!(ordering, Ordering::Equal) {
- a_not_cc.cmp(b_not_cc).reverse()
+ a_cc.cmp(b_cc).reverse()
} else {
ordering
}
@@ -451,8 +451,8 @@ impl Downloader {
None
};
- for (j, (subtitle, not_cc)) in format.subtitles.iter().enumerate() {
- if !not_cc && self.no_closed_caption {
+ for (j, (subtitle, cc)) in format.subtitles.iter().enumerate() {
+ if *cc && self.no_closed_caption {
continue;
}
@@ -462,7 +462,7 @@ impl Downloader {
progress_message += ", "
}
progress_message += &subtitle.locale.to_string();
- if !not_cc {
+ if *cc {
progress_message += " (CC)";
}
if i.min(videos.len() - 1) != 0 {
@@ -477,12 +477,12 @@ impl Downloader {
debug!(
"Downloaded {} subtitles{}",
subtitle.locale,
- (!not_cc).then_some(" (cc)").unwrap_or_default(),
+ cc.then_some(" (cc)").unwrap_or_default(),
);
subtitles.push(FFmpegSubtitleMeta {
path,
locale: subtitle.locale.clone(),
- cc: !not_cc,
+ cc: *cc,
start_time: subtitle_offsets.get(&j).cloned(),
video_idx: i,
})
From 442173c08c7a877cac768de0af1205708d668ca1 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Fri, 3 May 2024 13:46:43 +0200
Subject: [PATCH 46/82] Fix empty subtitles if multiple subtitle formats are
used (#398)
---
Cargo.lock | 11 +++
crunchy-cli-core/Cargo.toml | 1 +
crunchy-cli-core/src/utils/download.rs | 123 +++++++------------------
3 files changed, 43 insertions(+), 92 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index 26f81b9..4f7dd63 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -376,6 +376,7 @@ dependencies = [
"num_cpus",
"regex",
"reqwest",
+ "rsubs-lib",
"rustls-native-certs",
"rusty-chromaprint",
"serde",
@@ -1501,6 +1502,16 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b833d8d034ea094b1ea68aa6d5c740e0d04bad9d16568d08ba6f76823a114316"
+[[package]]
+name = "rsubs-lib"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0df7559a05635a4132b737c736ee286af83f3969cb98d9028d17d333e6b41cc5"
+dependencies = [
+ "regex",
+ "serde",
+]
+
[[package]]
name = "rubato"
version = "0.14.1"
diff --git a/crunchy-cli-core/Cargo.toml b/crunchy-cli-core/Cargo.toml
index 517284a..7fd8367 100644
--- a/crunchy-cli-core/Cargo.toml
+++ b/crunchy-cli-core/Cargo.toml
@@ -30,6 +30,7 @@ log = { version = "0.4", features = ["std"] }
num_cpus = "1.16"
regex = "1.10"
reqwest = { version = "0.12", features = ["socks", "stream"] }
+rsubs-lib = "0.2"
rusty-chromaprint = "0.2"
serde = "1.0"
serde_json = "1.0"
diff --git a/crunchy-cli-core/src/utils/download.rs b/crunchy-cli-core/src/utils/download.rs
index 2278bef..082a937 100644
--- a/crunchy-cli-core/src/utils/download.rs
+++ b/crunchy-cli-core/src/utils/download.rs
@@ -13,6 +13,7 @@ use indicatif::{ProgressBar, ProgressDrawTarget, ProgressFinish, ProgressStyle};
use log::{debug, warn, LevelFilter};
use regex::Regex;
use reqwest::Client;
+use rsubs_lib::{ssa, vtt};
use std::borrow::Borrow;
use std::cmp::Ordering;
use std::collections::{BTreeMap, HashMap};
@@ -931,13 +932,38 @@ impl Downloader {
subtitle: Subtitle,
max_length: TimeDelta,
) -> Result {
+ let buf = subtitle.data().await?;
+ let mut ass = match subtitle.format.as_str() {
+ "ass" => ssa::parse(String::from_utf8_lossy(&buf).to_string()),
+ "vtt" => vtt::parse(String::from_utf8_lossy(&buf).to_string()).to_ass(),
+ _ => bail!("unknown subtitle format: {}", subtitle.format),
+ };
+ // subtitles aren't always correct sorted and video players may have issues with that. to
+ // prevent issues, the subtitles are sorted
+ ass.events
+ .sort_by(|a, b| a.line_start.total_ms().cmp(&b.line_start.total_ms()));
+ // it might be the case that the start and/or end time are greater than the actual video
+ // length. this might also result in issues with video players, thus the times are stripped
+ // to be maxim
+ for i in (0..ass.events.len()).rev() {
+ if ass.events[i].line_end.total_ms() > max_length.num_milliseconds() as u32 {
+ if ass.events[i].line_start.total_ms() > max_length.num_milliseconds() as u32 {
+ ass.events[i]
+ .line_start
+ .set_ms(max_length.num_milliseconds() as u32);
+ }
+ ass.events[i]
+ .line_end
+ .set_ms(max_length.num_milliseconds() as u32);
+ } else {
+ break;
+ }
+ }
+
let tempfile = tempfile(".ass")?;
- let (mut file, path) = tempfile.into_parts();
+ let path = tempfile.into_temp_path();
- let mut buf = subtitle.data().await?;
- fix_subtitles(&mut buf, max_length);
-
- file.write_all(buf.as_slice())?;
+ ass.to_file(path.to_string_lossy().to_string().as_str())?;
Ok(path)
}
@@ -1301,93 +1327,6 @@ fn get_subtitle_stats(path: &Path) -> Result> {
Ok(fonts)
}
-/// Fix the subtitles in multiple ways as Crunchyroll sometimes delivers them malformed.
-///
-/// Look and feel fix: Add `ScaledBorderAndShadows: yes` to subtitles; without it they look very
-/// messy on some video players. See
-/// [crunchy-labs/crunchy-cli#66](https://github.com/crunchy-labs/crunchy-cli/issues/66) for more
-/// information.
-/// Length fix: Sometimes subtitles have an unnecessary long entry which exceeds the video length,
-/// some video players can't handle this correctly. To prevent this, the subtitles must be checked
-/// if any entry is longer than the video length and if so the entry ending must be hard set to not
-/// exceed the video length. See [crunchy-labs/crunchy-cli#32](https://github.com/crunchy-labs/crunchy-cli/issues/32)
-/// for more information.
-/// Sort fix: Sometimes subtitle entries aren't sorted correctly by time which confuses some video
-/// players. To prevent this, the subtitle entries must be manually sorted. See
-/// [crunchy-labs/crunchy-cli#208](https://github.com/crunchy-labs/crunchy-cli/issues/208) for more
-/// information.
-fn fix_subtitles(raw: &mut Vec, max_length: TimeDelta) {
- let re = Regex::new(
- r"^Dialogue:\s(?P\d+),(?P\d+:\d+:\d+\.\d+),(?P\d+:\d+:\d+\.\d+),",
- )
- .unwrap();
-
- let mut entries = (vec![], vec![]);
-
- let mut as_lines: Vec = String::from_utf8_lossy(raw.as_slice())
- .split('\n')
- .map(|s| s.to_string())
- .collect();
-
- for (i, line) in as_lines.iter_mut().enumerate() {
- if line.trim() == "[Script Info]" {
- line.push_str("\nScaledBorderAndShadow: yes")
- } else if let Some(capture) = re.captures(line) {
- let mut start = capture
- .name("start")
- .map_or(NaiveTime::default(), |s| {
- NaiveTime::parse_from_str(s.as_str(), "%H:%M:%S.%f").unwrap()
- })
- .signed_duration_since(NaiveTime::MIN);
- let mut end = capture
- .name("end")
- .map_or(NaiveTime::default(), |e| {
- NaiveTime::parse_from_str(e.as_str(), "%H:%M:%S.%f").unwrap()
- })
- .signed_duration_since(NaiveTime::MIN);
-
- if start > max_length || end > max_length {
- let layer = capture
- .name("layer")
- .map_or(0, |l| i32::from_str(l.as_str()).unwrap());
-
- if start > max_length {
- start = max_length;
- }
- if start > max_length || end > max_length {
- end = max_length;
- }
-
- *line = re
- .replace(
- line,
- format!(
- "Dialogue: {},{},{},",
- layer,
- format_time_delta(&start),
- format_time_delta(&end)
- ),
- )
- .to_string()
- }
- entries.0.push((start, i));
- entries.1.push(i)
- }
- }
-
- entries.0.sort_by(|(a, _), (b, _)| a.cmp(b));
- for i in 0..entries.0.len() {
- let (_, original_position) = entries.0[i];
- let new_position = entries.1[i];
-
- if original_position != new_position {
- as_lines.swap(original_position, new_position)
- }
- }
-
- *raw = as_lines.join("\n").into_bytes()
-}
-
fn write_ffmpeg_chapters(
file: &mut fs::File,
video_len: TimeDelta,
From 55f1e1d32db0fb05af2e203bd0629f11ed96c2b9 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Fri, 3 May 2024 20:33:19 +0200
Subject: [PATCH 47/82] Add option to overwrite git hash on build
---
crunchy-cli-core/build.rs | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/crunchy-cli-core/build.rs b/crunchy-cli-core/build.rs
index f7d5974..b36ec8e 100644
--- a/crunchy-cli-core/build.rs
+++ b/crunchy-cli-core/build.rs
@@ -1,7 +1,8 @@
fn main() -> std::io::Result<()> {
println!(
"cargo:rustc-env=GIT_HASH={}",
- get_short_commit_hash()?.unwrap_or_default()
+ std::env::var("CRUNCHY_CLI_GIT_HASH")
+ .or::(Ok(get_short_commit_hash()?.unwrap_or_default()))?
);
println!(
"cargo:rustc-env=BUILD_DATE={}",
From dcbe433a9c1cec69bb051de7837698104d793456 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Fri, 3 May 2024 20:33:50 +0200
Subject: [PATCH 48/82] Manually git hash when publishing source AUR package
---
.github/scripts/PKGBUILD.source | 1 +
.github/workflows/publish.yml | 6 +++++-
2 files changed, 6 insertions(+), 1 deletion(-)
diff --git a/.github/scripts/PKGBUILD.source b/.github/scripts/PKGBUILD.source
index 4430f95..ed19d54 100644
--- a/.github/scripts/PKGBUILD.source
+++ b/.github/scripts/PKGBUILD.source
@@ -21,6 +21,7 @@ build() {
export CARGO_HOME="$srcdir/cargo-home"
export RUSTUP_TOOLCHAIN=stable
+ export CRUNCHY_CLI_GIT_HASH=$CI_GIT_HASH
cargo build --release
}
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
index 4a477b3..2184042 100644
--- a/.github/workflows/publish.yml
+++ b/.github/workflows/publish.yml
@@ -20,11 +20,15 @@ jobs:
curl -LO https://github.com/crunchy-labs/crunchy-cli/archive/refs/tags/${{ github.ref_name }}.tar.gz
echo "CRUNCHY_CLI_SHA256=$(sha256sum ${{ github.ref_name }}.tar.gz | cut -f 1 -d ' ')" >> $GITHUB_ENV
+ - name: Get release commit hash
+ run: echo "CRUNCHY_CLI_GIT_HASH=$(git rev-parse --short HEAD)" >> $GITHUB_ENV
+
- name: Generate crunchy-cli PKGBUILD
env:
CI_PKG_VERSION: ${{ env.RELEASE_VERSION }}
CI_SHA_SUM: ${{ env.CRUNCHY_CLI_SHA256 }}
- run: envsubst '$CI_PKG_VERSION,$CI_SHA_SUM' < .github/scripts/PKGBUILD.source > PKGBUILD
+ CI_GIT_HASH: ${{ env.CRUNCHY_CLI_GIT_HASH }}
+ run: envsubst '$CI_PKG_VERSION,$CI_SHA_SUM,$CI_GIT_HASH' < .github/scripts/PKGBUILD.source > PKGBUILD
- name: Publish crunchy-cli to AUR
uses: KSXGitHub/github-actions-deploy-aur@v2.7.0
From 4066b8511ca076df74f01a0aa10257a2c6288154 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Fri, 3 May 2024 20:51:31 +0200
Subject: [PATCH 49/82] Build binaries locked
---
.github/scripts/PKGBUILD.source | 13 +++++++++++--
.github/workflows/ci.yml | 6 +++---
2 files changed, 14 insertions(+), 5 deletions(-)
diff --git a/.github/scripts/PKGBUILD.source b/.github/scripts/PKGBUILD.source
index ed19d54..4b14f5b 100644
--- a/.github/scripts/PKGBUILD.source
+++ b/.github/scripts/PKGBUILD.source
@@ -15,14 +15,23 @@ sha256sums=('$CI_SHA_SUM')
# lto causes linking errors when executed by this buildscript. besides, lto is already done by cargo itself (which doesn't cause linking errors)
options=(!lto)
+prepare() {
+ cd "$srcdir/${pkgname}-$pkgver"
+
+ export RUSTUP_TOOLCHAIN=stable
+ export CARGO_HOME="$srcdir/cargo-home"
+
+ cargo fetch --locked --target "$(rustc -vV | sed -n 's/host: //p')"
+}
+
build() {
cd "$srcdir/${pkgname}-$pkgver"
- export CARGO_HOME="$srcdir/cargo-home"
export RUSTUP_TOOLCHAIN=stable
+ export CARGO_HOME="$srcdir/cargo-home"
export CRUNCHY_CLI_GIT_HASH=$CI_GIT_HASH
- cargo build --release
+ cargo build --frozen --release
}
package() {
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 70f4400..5429d94 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -41,7 +41,7 @@ jobs:
run: cargo install --force cross
- name: Build
- run: cross build --release --no-default-features --features openssl-tls-static --target ${{ matrix.toolchain }}
+ run: cross build --locked --release --no-default-features --features openssl-tls-static --target ${{ matrix.toolchain }}
- name: Upload binary artifact
uses: actions/upload-artifact@v4
@@ -101,7 +101,7 @@ jobs:
toolchain: stable
- name: Build
- run: cargo build --release --target ${{ matrix.toolchain }}
+ run: cargo build --locked --release --target ${{ matrix.toolchain }}
- name: Upload binary artifact
uses: actions/upload-artifact@v4
@@ -135,7 +135,7 @@ jobs:
- name: Build
shell: msys2 {0}
- run: cargo build --release --target x86_64-pc-windows-gnu
+ run: cargo build --locked --release --target x86_64-pc-windows-gnu
- name: Upload binary artifact
uses: actions/upload-artifact@v4
From f77804fcb59079b8506275f033beaee6376a71f2 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Fri, 3 May 2024 20:58:46 +0200
Subject: [PATCH 50/82] Apply lints
---
crunchy-cli-core/src/archive/command.rs | 2 +-
crunchy-cli-core/src/utils/download.rs | 3 +-
crunchy-cli-core/src/utils/ffmpeg.rs | 45 +++++++------------------
3 files changed, 15 insertions(+), 35 deletions(-)
diff --git a/crunchy-cli-core/src/archive/command.rs b/crunchy-cli-core/src/archive/command.rs
index efb54f4..70142ec 100644
--- a/crunchy-cli-core/src/archive/command.rs
+++ b/crunchy-cli-core/src/archive/command.rs
@@ -393,7 +393,7 @@ impl Execute for Archive {
|| (method_subtitle && subtitle_differ)
{
skip = false;
- path = formatted_path.clone()
+ path.clone_from(&formatted_path)
}
}
}
diff --git a/crunchy-cli-core/src/utils/download.rs b/crunchy-cli-core/src/utils/download.rs
index 082a937..9fe4f79 100644
--- a/crunchy-cli-core/src/utils/download.rs
+++ b/crunchy-cli-core/src/utils/download.rs
@@ -20,7 +20,6 @@ use std::collections::{BTreeMap, HashMap};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
-use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use std::{env, fs};
@@ -731,7 +730,7 @@ impl Downloader {
output_presets.remove(i - remove_count);
remove_count += 1;
}
- last = s.clone();
+ last.clone_from(s);
}
output_presets.extend([
diff --git a/crunchy-cli-core/src/utils/ffmpeg.rs b/crunchy-cli-core/src/utils/ffmpeg.rs
index a61ed93..ef73581 100644
--- a/crunchy-cli-core/src/utils/ffmpeg.rs
+++ b/crunchy-cli-core/src/utils/ffmpeg.rs
@@ -1,5 +1,7 @@
use lazy_static::lazy_static;
use regex::Regex;
+use std::fmt;
+use std::fmt::Formatter;
use std::str::FromStr;
pub const SOFTSUB_CONTAINERS: [&str; 3] = ["mkv", "mov", "mp4"];
@@ -33,11 +35,11 @@ macro_rules! ffmpeg_enum {
}
}
- impl ToString for $name {
- fn to_string(&self) -> String {
+ impl fmt::Display for $name {
+ fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
$(
- &$name::$field => stringify!($field).to_string().to_lowercase()
+ &$name::$field => write!(f, "{}", stringify!($field).to_string().to_lowercase())
),*
}
}
@@ -135,23 +137,16 @@ impl FFmpegPreset {
for (codec, hwaccel, quality) in FFmpegPreset::available_matches() {
let mut description_details = vec![];
if let Some(h) = &hwaccel {
- description_details.push(format!("{} hardware acceleration", h.to_string()))
+ description_details.push(format!("{h} hardware acceleration"))
}
if let Some(q) = &quality {
- description_details.push(format!("{} video quality/compression", q.to_string()))
+ description_details.push(format!("{q} video quality/compression"))
}
let description = if description_details.is_empty() {
- format!(
- "{} encoded with default video quality/compression",
- codec.to_string()
- )
+ format!("{codec} encoded with default video quality/compression",)
} else if description_details.len() == 1 {
- format!(
- "{} encoded with {}",
- codec.to_string(),
- description_details[0]
- )
+ format!("{} encoded with {}", codec, description_details[0])
} else {
let first = description_details.remove(0);
let last = description_details.remove(description_details.len() - 1);
@@ -161,13 +156,7 @@ impl FFmpegPreset {
"".to_string()
};
- format!(
- "{} encoded with {}{} and {}",
- codec.to_string(),
- first,
- mid,
- last
- )
+ format!("{codec} encoded with {first}{mid} and {last}",)
};
return_values.push(format!(
@@ -201,11 +190,7 @@ impl FFmpegPreset {
.find(|p| p.to_string() == token.to_lowercase())
{
if let Some(cc) = codec {
- return Err(format!(
- "cannot use multiple codecs (found {} and {})",
- cc.to_string(),
- c.to_string()
- ));
+ return Err(format!("cannot use multiple codecs (found {cc} and {c})",));
}
codec = Some(c)
} else if let Some(h) = FFmpegHwAccel::all()
@@ -214,9 +199,7 @@ impl FFmpegPreset {
{
if let Some(hh) = hwaccel {
return Err(format!(
- "cannot use multiple hardware accelerations (found {} and {})",
- hh.to_string(),
- h.to_string()
+ "cannot use multiple hardware accelerations (found {hh} and {h})",
));
}
hwaccel = Some(h)
@@ -226,9 +209,7 @@ impl FFmpegPreset {
{
if let Some(qq) = quality {
return Err(format!(
- "cannot use multiple ffmpeg preset qualities (found {} and {})",
- qq.to_string(),
- q.to_string()
+ "cannot use multiple ffmpeg preset qualities (found {qq} and {q})",
));
}
quality = Some(q)
From 0f7d7d928c553d4c37a4b4a1153091bc27945829 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Fri, 3 May 2024 21:08:34 +0200
Subject: [PATCH 51/82] Add format check and linting action pipelines
---
.github/workflows/ci.yml | 50 ++++++++++++++++++++++++++++++++++++++++
1 file changed, 50 insertions(+)
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 5429d94..7be86f6 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -8,6 +8,56 @@ on:
workflow_dispatch:
jobs:
+ fmt:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Cargo cache
+ uses: actions/cache@v4
+ with:
+ path: |
+ ~/.cargo/bin/
+ ~/.cargo/registry/index/
+ ~/.cargo/registry/cache/
+ ~/.cargo/git/db/
+ target/
+ key: x86_64-unknown-linux-gnu-cargo-${{ hashFiles('**/Cargo.lock') }}
+
+ - name: Setup Rust
+ uses: dtolnay/rust-toolchain@stable
+ with:
+ toolchain: stable
+
+ - name: Check fmt
+ run: cargo fmt --check
+
+ lint:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Cargo cache
+ uses: actions/cache@v4
+ with:
+ path: |
+ ~/.cargo/bin/
+ ~/.cargo/registry/index/
+ ~/.cargo/registry/cache/
+ ~/.cargo/git/db/
+ target/
+ key: x86_64-unknown-linux-gnu-cargo-${{ hashFiles('**/Cargo.lock') }}
+
+ - name: Setup Rust
+ uses: dtolnay/rust-toolchain@stable
+ with:
+ toolchain: stable
+
+ - name: Lint
+ run: cargo clippy -- -D warnings
+
build-linux:
runs-on: ubuntu-latest
strategy:
From fca1b74cacdad5f7c028a0c4eb9714ad0cd8dc70 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Fri, 3 May 2024 21:10:40 +0200
Subject: [PATCH 52/82] Separate build and lint pipelines
---
.github/workflows/{ci.yml => build.yml} | 52 +---------------------
.github/workflows/lint.yml | 58 +++++++++++++++++++++++++
2 files changed, 59 insertions(+), 51 deletions(-)
rename .github/workflows/{ci.yml => build.yml} (78%)
create mode 100644 .github/workflows/lint.yml
diff --git a/.github/workflows/ci.yml b/.github/workflows/build.yml
similarity index 78%
rename from .github/workflows/ci.yml
rename to .github/workflows/build.yml
index 7be86f6..9248ca5 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/build.yml
@@ -1,4 +1,4 @@
-name: ci
+name: build
on:
push:
@@ -8,56 +8,6 @@ on:
workflow_dispatch:
jobs:
- fmt:
- runs-on: ubuntu-latest
- steps:
- - name: Checkout
- uses: actions/checkout@v4
-
- - name: Cargo cache
- uses: actions/cache@v4
- with:
- path: |
- ~/.cargo/bin/
- ~/.cargo/registry/index/
- ~/.cargo/registry/cache/
- ~/.cargo/git/db/
- target/
- key: x86_64-unknown-linux-gnu-cargo-${{ hashFiles('**/Cargo.lock') }}
-
- - name: Setup Rust
- uses: dtolnay/rust-toolchain@stable
- with:
- toolchain: stable
-
- - name: Check fmt
- run: cargo fmt --check
-
- lint:
- runs-on: ubuntu-latest
- steps:
- - name: Checkout
- uses: actions/checkout@v4
-
- - name: Cargo cache
- uses: actions/cache@v4
- with:
- path: |
- ~/.cargo/bin/
- ~/.cargo/registry/index/
- ~/.cargo/registry/cache/
- ~/.cargo/git/db/
- target/
- key: x86_64-unknown-linux-gnu-cargo-${{ hashFiles('**/Cargo.lock') }}
-
- - name: Setup Rust
- uses: dtolnay/rust-toolchain@stable
- with:
- toolchain: stable
-
- - name: Lint
- run: cargo clippy -- -D warnings
-
build-linux:
runs-on: ubuntu-latest
strategy:
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
new file mode 100644
index 0000000..2d6eaf0
--- /dev/null
+++ b/.github/workflows/lint.yml
@@ -0,0 +1,58 @@
+name: lint
+
+on:
+ push:
+ branches:
+ - '*'
+ pull_request:
+
+jobs:
+ fmt:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Cargo cache
+ uses: actions/cache@v4
+ with:
+ path: |
+ ~/.cargo/bin/
+ ~/.cargo/registry/index/
+ ~/.cargo/registry/cache/
+ ~/.cargo/git/db/
+ target/
+ key: x86_64-unknown-linux-gnu-cargo-${{ hashFiles('**/Cargo.lock') }}
+
+ - name: Setup Rust
+ uses: dtolnay/rust-toolchain@stable
+ with:
+ toolchain: stable
+
+ - name: Check fmt
+ run: cargo fmt --check
+
+ lint:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Cargo cache
+ uses: actions/cache@v4
+ with:
+ path: |
+ ~/.cargo/bin/
+ ~/.cargo/registry/index/
+ ~/.cargo/registry/cache/
+ ~/.cargo/git/db/
+ target/
+ key: x86_64-unknown-linux-gnu-cargo-${{ hashFiles('**/Cargo.lock') }}
+
+ - name: Setup Rust
+ uses: dtolnay/rust-toolchain@stable
+ with:
+ toolchain: stable
+
+ - name: Lint
+ run: cargo clippy -- -D warnings
From 757d3094ea28fffe718ae4720eac7785e9ff9ee4 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Fri, 3 May 2024 21:14:51 +0200
Subject: [PATCH 53/82] Rename directory for workflow resources
---
.github/{scripts => workflow-resources}/PKGBUILD.binary | 0
.github/{scripts => workflow-resources}/PKGBUILD.source | 0
.github/workflows/publish.yml | 4 ++--
3 files changed, 2 insertions(+), 2 deletions(-)
rename .github/{scripts => workflow-resources}/PKGBUILD.binary (100%)
rename .github/{scripts => workflow-resources}/PKGBUILD.source (100%)
diff --git a/.github/scripts/PKGBUILD.binary b/.github/workflow-resources/PKGBUILD.binary
similarity index 100%
rename from .github/scripts/PKGBUILD.binary
rename to .github/workflow-resources/PKGBUILD.binary
diff --git a/.github/scripts/PKGBUILD.source b/.github/workflow-resources/PKGBUILD.source
similarity index 100%
rename from .github/scripts/PKGBUILD.source
rename to .github/workflow-resources/PKGBUILD.source
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
index 2184042..8f178ce 100644
--- a/.github/workflows/publish.yml
+++ b/.github/workflows/publish.yml
@@ -28,7 +28,7 @@ jobs:
CI_PKG_VERSION: ${{ env.RELEASE_VERSION }}
CI_SHA_SUM: ${{ env.CRUNCHY_CLI_SHA256 }}
CI_GIT_HASH: ${{ env.CRUNCHY_CLI_GIT_HASH }}
- run: envsubst '$CI_PKG_VERSION,$CI_SHA_SUM,$CI_GIT_HASH' < .github/scripts/PKGBUILD.source > PKGBUILD
+ run: envsubst '$CI_PKG_VERSION,$CI_SHA_SUM,$CI_GIT_HASH' < .github/workflow-resources/PKGBUILD.source > PKGBUILD
- name: Publish crunchy-cli to AUR
uses: KSXGitHub/github-actions-deploy-aur@v2.7.0
@@ -61,7 +61,7 @@ jobs:
CI_MANPAGES_SHA_SUM: ${{ env.CRUNCHY_CLI_BIN_MANPAGES_SHA256 }}
CI_COMPLETIONS_SHA_SUM: ${{ env.CRUNCHY_CLI_BIN_COMPLETIONS_SHA256 }}
CI_LICENSE_SHA_SUM: ${{ env.CRUNCHY_CLI_BIN_LICENSE_SHA256 }}
- run: envsubst '$CI_PKG_VERSION,$CI_AMD_BINARY_SHA_SUM,$CI_ARM_BINARY_SHA_SUM,$CI_COMPLETIONS_SHA_SUM,$CI_MANPAGES_SHA_SUM,$CI_LICENSE_SHA_SUM' < .github/scripts/PKGBUILD.binary > PKGBUILD
+ run: envsubst '$CI_PKG_VERSION,$CI_AMD_BINARY_SHA_SUM,$CI_ARM_BINARY_SHA_SUM,$CI_COMPLETIONS_SHA_SUM,$CI_MANPAGES_SHA_SUM,$CI_LICENSE_SHA_SUM' < .github/workflow-resources/PKGBUILD.binary > PKGBUILD
- name: Publish crunchy-cli-bin to AUR
uses: KSXGitHub/github-actions-deploy-aur@v2.7.0
From dad91dba91910d5ea69600fbb28a5e521191a77a Mon Sep 17 00:00:00 2001
From: bytedream
Date: Sat, 4 May 2024 23:08:55 +0200
Subject: [PATCH 54/82] Rename `--sync-tolerance` to `--merge-sync-tolerance`
and `--merge-sync-precision` to `--merge-sync-precision`
---
README.md | 6 +++---
crunchy-cli-core/src/archive/command.rs | 12 ++++++------
crunchy-cli-core/src/utils/download.rs | 22 +++++++++++-----------
3 files changed, 20 insertions(+), 20 deletions(-)
diff --git a/README.md b/README.md
index 1fdf348..29893f9 100644
--- a/README.md
+++ b/README.md
@@ -482,14 +482,14 @@ The `archive` command lets you download episodes with multiple audios and subtit
Default are `200` milliseconds.
-- Sync tolerance
+- Merge sync tolerance
Sometimes two video tracks are downloaded with `--merge` set to `sync` because the audio fingerprinting fails to identify matching audio parts (e.g. opening).
- To prevent this, you can use the `--sync-tolerance` flag to specify the difference by which two fingerprints are considered equal.
+ To prevent this, you can use the `--merge-sync-tolerance` flag to specify the difference by which two fingerprints are considered equal.
Default is `6`.
-- Sync precision
+- Merge sync precision
If you use `--merge` set to `sync` and the syncing seems to be not accurate enough or takes to long, you can use the `--sync-precision` flag to specify the amount of offset determination runs from which the final offset is calculated.
diff --git a/crunchy-cli-core/src/archive/command.rs b/crunchy-cli-core/src/archive/command.rs
index 70142ec..38bddc1 100644
--- a/crunchy-cli-core/src/archive/command.rs
+++ b/crunchy-cli-core/src/archive/command.rs
@@ -109,12 +109,12 @@ pub struct Archive {
help = "If the merge behavior is 'sync', specify the difference by which two fingerprints are considered equal, higher values can help when the algorithm fails"
)]
#[arg(long, default_value_t = 6)]
- pub(crate) sync_tolerance: u32,
+ pub(crate) merge_sync_tolerance: u32,
#[arg(
help = "If the merge behavior is 'sync', specify the amount of offset determination runs from which the final offset is calculated, higher values will increase the time required but lead to more precise offsets"
)]
#[arg(long, default_value_t = 4)]
- pub(crate) sync_precision: u32,
+ pub(crate) merge_sync_precision: u32,
#[arg(
help = "Specified which language tagging the audio and subtitle tracks and language specific format options should have. \
@@ -308,12 +308,12 @@ impl Execute for Archive {
.audio_sort(Some(self.audio.clone()))
.subtitle_sort(Some(self.subtitle.clone()))
.no_closed_caption(self.no_closed_caption)
- .sync_tolerance(match self.merge {
- MergeBehavior::Sync => Some(self.sync_tolerance),
+ .merge_sync_tolerance(match self.merge {
+ MergeBehavior::Sync => Some(self.merge_sync_tolerance),
_ => None,
})
- .sync_precision(match self.merge {
- MergeBehavior::Sync => Some(self.sync_precision),
+ .merge_sync_precision(match self.merge {
+ MergeBehavior::Sync => Some(self.merge_sync_precision),
_ => None,
})
.threads(self.threads)
diff --git a/crunchy-cli-core/src/utils/download.rs b/crunchy-cli-core/src/utils/download.rs
index 9fe4f79..565ed7d 100644
--- a/crunchy-cli-core/src/utils/download.rs
+++ b/crunchy-cli-core/src/utils/download.rs
@@ -64,8 +64,8 @@ pub struct DownloadBuilder {
force_hardsub: bool,
download_fonts: bool,
no_closed_caption: bool,
- sync_tolerance: Option,
- sync_precision: Option,
+ merge_sync_tolerance: Option,
+ merge_sync_precision: Option,
threads: usize,
ffmpeg_threads: Option,
audio_locale_output_map: HashMap,
@@ -85,8 +85,8 @@ impl DownloadBuilder {
force_hardsub: false,
download_fonts: false,
no_closed_caption: false,
- sync_tolerance: None,
- sync_precision: None,
+ merge_sync_tolerance: None,
+ merge_sync_precision: None,
threads: num_cpus::get(),
ffmpeg_threads: None,
audio_locale_output_map: HashMap::new(),
@@ -108,8 +108,8 @@ impl DownloadBuilder {
download_fonts: self.download_fonts,
no_closed_caption: self.no_closed_caption,
- sync_tolerance: self.sync_tolerance,
- sync_precision: self.sync_precision,
+ merge_sync_tolerance: self.merge_sync_tolerance,
+ merge_sync_precision: self.merge_sync_precision,
download_threads: self.threads,
ffmpeg_threads: self.ffmpeg_threads,
@@ -168,8 +168,8 @@ pub struct Downloader {
download_fonts: bool,
no_closed_caption: bool,
- sync_tolerance: Option,
- sync_precision: Option,
+ merge_sync_tolerance: Option,
+ merge_sync_precision: Option,
download_threads: usize,
ffmpeg_threads: Option,
@@ -287,13 +287,13 @@ impl Downloader {
}
}
- if self.formats.len() > 1 && self.sync_tolerance.is_some() {
+ if self.formats.len() > 1 && self.merge_sync_tolerance.is_some() {
let _progress_handler =
progress!("Syncing video start times (this might take some time)");
let mut offsets = sync_audios(
&raw_audios,
- self.sync_tolerance.unwrap(),
- self.sync_precision.unwrap(),
+ self.merge_sync_tolerance.unwrap(),
+ self.merge_sync_precision.unwrap(),
)?;
drop(_progress_handler);
From 96d3de48cf9b33ac3860c469b9bb577ec20b4f38 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Sat, 4 May 2024 23:10:35 +0200
Subject: [PATCH 55/82] Add missing code examples
---
README.md | 8 ++++++++
1 file changed, 8 insertions(+)
diff --git a/README.md b/README.md
index 29893f9..1735a6e 100644
--- a/README.md
+++ b/README.md
@@ -487,12 +487,20 @@ The `archive` command lets you download episodes with multiple audios and subtit
Sometimes two video tracks are downloaded with `--merge` set to `sync` because the audio fingerprinting fails to identify matching audio parts (e.g. opening).
To prevent this, you can use the `--merge-sync-tolerance` flag to specify the difference by which two fingerprints are considered equal.
+ ```shell
+ $ crunchy-cli archive -m sync --merge-sync-tolerance 3 https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome
+ ```
+
Default is `6`.
- Merge sync precision
If you use `--merge` set to `sync` and the syncing seems to be not accurate enough or takes to long, you can use the `--sync-precision` flag to specify the amount of offset determination runs from which the final offset is calculated.
+ ```shell
+ $ crunchy-cli archive -m sync --merge-sync-precision 3 https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome
+ ```
+
Default is `4`.
- Language tagging
From 89b9c5db390691e626a18a294e3573cf73d9604c Mon Sep 17 00:00:00 2001
From: bytedream
Date: Sat, 4 May 2024 23:36:09 +0200
Subject: [PATCH 56/82] Update dependencies and version
---
Cargo.lock | 114 +++++++++++++++++++-----------------
Cargo.toml | 2 +-
crunchy-cli-core/Cargo.toml | 4 +-
3 files changed, 63 insertions(+), 57 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index 4f7dd63..b9dce7b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -43,47 +43,48 @@ dependencies = [
[[package]]
name = "anstream"
-version = "0.6.13"
+version = "0.6.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d96bd03f33fe50a863e394ee9718a706f988b9079b20c3784fb726e7678b62fb"
+checksum = "418c75fa768af9c03be99d17643f93f79bbba589895012a80e3452a19ddda15b"
dependencies = [
"anstyle",
"anstyle-parse",
"anstyle-query",
"anstyle-wincon",
"colorchoice",
+ "is_terminal_polyfill",
"utf8parse",
]
[[package]]
name = "anstyle"
-version = "1.0.6"
+version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8901269c6307e8d93993578286ac0edf7f195079ffff5ebdeea6a59ffb7e36bc"
+checksum = "038dfcf04a5feb68e9c60b21c9625a54c2c0616e79b72b0fd87075a056ae1d1b"
[[package]]
name = "anstyle-parse"
-version = "0.2.3"
+version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c75ac65da39e5fe5ab759307499ddad880d724eed2f6ce5b5e8a26f4f387928c"
+checksum = "c03a11a9034d92058ceb6ee011ce58af4a9bf61491aa7e1e59ecd24bd40d22d4"
dependencies = [
"utf8parse",
]
[[package]]
name = "anstyle-query"
-version = "1.0.2"
+version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e28923312444cdd728e4738b3f9c9cac739500909bb3d3c94b43551b16517648"
+checksum = "a64c907d4e79225ac72e2a354c9ce84d50ebb4586dee56c82b3ee73004f537f5"
dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "anstyle-wincon"
-version = "3.0.2"
+version = "3.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1cd54b81ec8d6180e24654d0b371ad22fc3dd083b6ff8ba325b72e00c87660a7"
+checksum = "61a38449feb7068f52bb06c12759005cf459ee52bb4adc1d5a7c4322d716fb19"
dependencies = [
"anstyle",
"windows-sys 0.52.0",
@@ -120,9 +121,9 @@ dependencies = [
[[package]]
name = "autocfg"
-version = "1.2.0"
+version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f1fdabc7756949593fe60f30ec81974b613357de856987752631dea1e3394c80"
+checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0"
[[package]]
name = "backtrace"
@@ -147,9 +148,9 @@ checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567"
[[package]]
name = "base64"
-version = "0.22.0"
+version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9475866fec1451be56a3c2400fd081ff546538961565ccb5b7142cbd22bc7a51"
+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "base64-serde"
@@ -187,9 +188,9 @@ checksum = "514de17de45fdb8dc022b1a7975556c53c86f9f0aa5f534b98977b171857c2c9"
[[package]]
name = "cc"
-version = "1.0.95"
+version = "1.0.96"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d32a725bc159af97c3e629873bb9f88fb8cf8a4867175f76dc987815ea07c83b"
+checksum = "065a29261d53ba54260972629f9ca6bffa69bac13cd1fed61420f7fa68b9f8bd"
[[package]]
name = "cfg-if"
@@ -279,9 +280,9 @@ dependencies = [
[[package]]
name = "colorchoice"
-version = "1.0.0"
+version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7"
+checksum = "0b6a852b24ab71dffc585bcb46eaf7959d175cb865a7152e35b348d1b2960422"
[[package]]
name = "console"
@@ -342,7 +343,7 @@ checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f"
[[package]]
name = "crunchy-cli"
-version = "3.5.2"
+version = "3.6.0"
dependencies = [
"chrono",
"clap",
@@ -355,7 +356,7 @@ dependencies = [
[[package]]
name = "crunchy-cli-core"
-version = "3.5.2"
+version = "3.6.0"
dependencies = [
"anyhow",
"async-speed-limit",
@@ -392,9 +393,9 @@ dependencies = [
[[package]]
name = "crunchyroll-rs"
-version = "0.11.0"
+version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e63a541bdcf0170a29eab4015943e8a6a09281334b4beacd70ac5cfc1c19496b"
+checksum = "58580acc9c0abf96a231ec8b1a4597ea55d9426ea17f684ce3582e2b26437bbb"
dependencies = [
"async-trait",
"chrono",
@@ -418,9 +419,9 @@ dependencies = [
[[package]]
name = "crunchyroll-rs-internal"
-version = "0.11.0"
+version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3a9e0e09162451565645fdd4dadc6b38e09f3aafcfb477153584bedd8d62a358"
+checksum = "ce3c844dec8a3390f8c9853b5cf1d65c3d38fd0657b8b5d0e008db8945dea326"
dependencies = [
"darling",
"quote",
@@ -478,7 +479,7 @@ version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "79b4bdd5f1c0c7493d780c645f0bff5b9361e6408210fa88910adb181efca64c"
dependencies = [
- "base64 0.22.0",
+ "base64 0.22.1",
"base64-serde",
"chrono",
"fs-err",
@@ -589,9 +590,9 @@ dependencies = [
[[package]]
name = "fastrand"
-version = "2.0.2"
+version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "658bd65b1cf4c852a3cc96f18a8ce7b5640f6b703f905c7d74532294c2a63984"
+checksum = "9fc0510504f03c51ada170672ac806f1f105a88aa97a5281117e1ddc3368e51a"
[[package]]
name = "fnv"
@@ -755,9 +756,9 @@ checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
[[package]]
name = "hashbrown"
-version = "0.14.3"
+version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "290f1a1d9242c78d09ce40a5e87e7554ee637af1351968159f4952f028f75604"
+checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
[[package]]
name = "heck"
@@ -957,7 +958,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "168fb715dda47215e360912c096649d23d58bf392ac62f73919e831745e40f26"
dependencies = [
"equivalent",
- "hashbrown 0.14.3",
+ "hashbrown 0.14.5",
"serde",
]
@@ -989,6 +990,12 @@ version = "2.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f518f335dce6725a761382244631d86cf0ccb2863413590b31338feb467f9c3"
+[[package]]
+name = "is_terminal_polyfill"
+version = "1.70.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8478577c03552c21db0e2724ffb8986a5ce7af88107e6be5d2ee6e158c12800"
+
[[package]]
name = "iso8601"
version = "0.6.1"
@@ -1034,9 +1041,9 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]]
name = "libc"
-version = "0.2.153"
+version = "0.2.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd"
+checksum = "ae743338b92ff9146ce83992f766a31066a91a8c84a45e0e9f21e7cf6de6d346"
[[package]]
name = "libredox"
@@ -1172,9 +1179,9 @@ dependencies = [
[[package]]
name = "num-traits"
-version = "0.2.18"
+version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "da0df0e5185db44f69b44f26786fe401b6c293d1907744beaa7fa62b2e5a517a"
+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
@@ -1434,7 +1441,7 @@ version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "566cafdd92868e0939d3fb961bd0dc25fcfaaed179291093b3d43e6b3150ea10"
dependencies = [
- "base64 0.22.0",
+ "base64 0.22.1",
"bytes",
"cookie",
"cookie_store",
@@ -1591,7 +1598,7 @@ version = "2.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29993a25686778eb88d4189742cd713c9bce943bc54251a33509dc63cbacf73d"
dependencies = [
- "base64 0.22.0",
+ "base64 0.22.1",
"rustls-pki-types",
]
@@ -1662,18 +1669,18 @@ dependencies = [
[[package]]
name = "serde"
-version = "1.0.198"
+version = "1.0.200"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9846a40c979031340571da2545a4e5b7c4163bdae79b301d5f86d03979451fcc"
+checksum = "ddc6f9cc94d67c0e21aaf7eda3a010fd3af78ebf6e096aa6e2e13c79749cce4f"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
-version = "1.0.198"
+version = "1.0.200"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e88edab869b01783ba905e7d0153f9fc1a6505a96e4ad3018011eedb838566d9"
+checksum = "856f046b9400cee3c8c94ed572ecdb752444c24528c035cd35882aad6f492bcb"
dependencies = [
"proc-macro2",
"quote",
@@ -1724,11 +1731,11 @@ dependencies = [
[[package]]
name = "serde_with"
-version = "3.8.0"
+version = "3.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2c85f8e96d1d6857f13768fcbd895fcb06225510022a2774ed8b5150581847b0"
+checksum = "0ad483d2ab0149d5a5ebcd9972a3852711e0153d863bf5a5d0391d28883c4a20"
dependencies = [
- "base64 0.22.0",
+ "base64 0.22.1",
"chrono",
"hex",
"indexmap 1.9.3",
@@ -1742,9 +1749,9 @@ dependencies = [
[[package]]
name = "serde_with_macros"
-version = "3.8.0"
+version = "3.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c8b3a576c4eb2924262d5951a3b737ccaf16c931e39a2810c36f9a7e25575557"
+checksum = "65569b702f41443e8bc8bbb1c5779bd0450bbe723b56198980e80ec45780bce2"
dependencies = [
"darling",
"proc-macro2",
@@ -1792,9 +1799,9 @@ dependencies = [
[[package]]
name = "socket2"
-version = "0.5.6"
+version = "0.5.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "05ffd9c0a93b7543e062e759284fcf5f5e3b098501104bfbdde4d404db792871"
+checksum = "ce305eb0b4296696835b71df73eb912e0f1ffd2556a501fcede6e0c50349191c"
dependencies = [
"libc",
"windows-sys 0.52.0",
@@ -2018,16 +2025,15 @@ dependencies = [
[[package]]
name = "tokio-util"
-version = "0.7.10"
+version = "0.7.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5419f34732d9eb6ee4c3578b7989078579b7f039cbbb9ca2c4da015749371e15"
+checksum = "9cf6b47b3771c49ac75ad09a6162f53ad4b8088b76ac60e8ec1455b31a189fe1"
dependencies = [
"bytes",
"futures-core",
"futures-sink",
"pin-project-lite",
"tokio",
- "tracing",
]
[[package]]
@@ -2138,9 +2144,9 @@ dependencies = [
[[package]]
name = "unicode-width"
-version = "0.1.11"
+version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e51733f11c9c4f72aa0c160008246859e340b00807569a0da0e7a1079b27ba85"
+checksum = "68f5e5f3158ecfd4b8ff6fe086db7c8467a2dfdac97fe420f2b7c4aa97af66d6"
[[package]]
name = "untrusted"
@@ -2492,6 +2498,6 @@ dependencies = [
[[package]]
name = "zeroize"
-version = "1.8.0"
+version = "1.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "63381fa6624bf92130a6b87c0d07380116f80b565c42cf0d754136f0238359ef"
+checksum = "525b4ec142c6b68a2d10f01f7bbf6755599ca3f81ea53b8431b7dd348f5fdb2d"
diff --git a/Cargo.toml b/Cargo.toml
index 6886f97..fe7b301 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli"
authors = ["Crunchy Labs Maintainers"]
-version = "3.5.2"
+version = "3.6.0"
edition = "2021"
license = "MIT"
diff --git a/crunchy-cli-core/Cargo.toml b/crunchy-cli-core/Cargo.toml
index 7fd8367..896b68f 100644
--- a/crunchy-cli-core/Cargo.toml
+++ b/crunchy-cli-core/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli-core"
authors = ["Crunchy Labs Maintainers"]
-version = "3.5.2"
+version = "3.6.0"
edition = "2021"
license = "MIT"
@@ -16,7 +16,7 @@ anyhow = "1.0"
async-speed-limit = "0.4"
clap = { version = "4.5", features = ["derive", "string"] }
chrono = "0.4"
-crunchyroll-rs = { version = "0.11.0", features = ["experimental-stabilizations", "tower"] }
+crunchyroll-rs = { version = "0.11.1", features = ["experimental-stabilizations", "tower"] }
ctrlc = "3.4"
dialoguer = { version = "0.11", default-features = false }
dirs = "5.0"
From 4d1df833426f1382cf0351ffc250e11c150ce147 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Sat, 4 May 2024 23:45:30 +0200
Subject: [PATCH 57/82] Fix build badge
---
README.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/README.md b/README.md
index 1735a6e..45b8ea7 100644
--- a/README.md
+++ b/README.md
@@ -22,8 +22,8 @@
-
-
+
+
From ab63dcd2e010cccd4b5a99c48d6576fa6c22d664 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Mon, 6 May 2024 20:29:22 +0200
Subject: [PATCH 58/82] Update dependencies and version
---
Cargo.lock | 30 +++++++++++++++---------------
Cargo.toml | 2 +-
crunchy-cli-core/Cargo.toml | 4 ++--
3 files changed, 18 insertions(+), 18 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index b9dce7b..44a47cd 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -92,9 +92,9 @@ dependencies = [
[[package]]
name = "anyhow"
-version = "1.0.82"
+version = "1.0.83"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f538837af36e6f6a9be0faa67f9a314f8119e4e4b5867c6ab40ed60360142519"
+checksum = "25bdb32cbbdce2b519a9cd7df3a678443100e265d5e25ca763b7572a5104f5f3"
[[package]]
name = "async-speed-limit"
@@ -188,9 +188,9 @@ checksum = "514de17de45fdb8dc022b1a7975556c53c86f9f0aa5f534b98977b171857c2c9"
[[package]]
name = "cc"
-version = "1.0.96"
+version = "1.0.97"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "065a29261d53ba54260972629f9ca6bffa69bac13cd1fed61420f7fa68b9f8bd"
+checksum = "099a5357d84c4c61eb35fc8eafa9a79a902c2f76911e5747ced4e032edd8d9b4"
[[package]]
name = "cfg-if"
@@ -343,7 +343,7 @@ checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f"
[[package]]
name = "crunchy-cli"
-version = "3.6.0"
+version = "3.6.1"
dependencies = [
"chrono",
"clap",
@@ -356,7 +356,7 @@ dependencies = [
[[package]]
name = "crunchy-cli-core"
-version = "3.6.0"
+version = "3.6.1"
dependencies = [
"anyhow",
"async-speed-limit",
@@ -712,9 +712,9 @@ dependencies = [
[[package]]
name = "getrandom"
-version = "0.2.14"
+version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "94b22e06ecb0110981051723910cbf0b5f5e09a2062dd7663334ee79a9d1286c"
+checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7"
dependencies = [
"cfg-if",
"js-sys",
@@ -1511,9 +1511,9 @@ checksum = "b833d8d034ea094b1ea68aa6d5c740e0d04bad9d16568d08ba6f76823a114316"
[[package]]
name = "rsubs-lib"
-version = "0.2.0"
+version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0df7559a05635a4132b737c736ee286af83f3969cb98d9028d17d333e6b41cc5"
+checksum = "9dcca2a9560fca05de8f95bc3767e46673d4b4c1f2c7a11092e10efd95bbdf62"
dependencies = [
"regex",
"serde",
@@ -1646,11 +1646,11 @@ dependencies = [
[[package]]
name = "security-framework"
-version = "2.10.0"
+version = "2.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "770452e37cad93e0a50d5abc3990d2bc351c36d0328f86cefec2f2fb206eaef6"
+checksum = "c627723fd09706bacdb5cf41499e95098555af3c3c29d014dc3c458ef6be11c0"
dependencies = [
- "bitflags 1.3.2",
+ "bitflags 2.5.0",
"core-foundation",
"core-foundation-sys",
"libc",
@@ -1659,9 +1659,9 @@ dependencies = [
[[package]]
name = "security-framework-sys"
-version = "2.10.0"
+version = "2.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "41f3cc463c0ef97e11c3461a9d3787412d30e8e7eb907c79180c4a57bf7c04ef"
+checksum = "317936bbbd05227752583946b9e66d7ce3b489f84e11a94a510b4437fef407d7"
dependencies = [
"core-foundation-sys",
"libc",
diff --git a/Cargo.toml b/Cargo.toml
index fe7b301..26f71f3 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli"
authors = ["Crunchy Labs Maintainers"]
-version = "3.6.0"
+version = "3.6.1"
edition = "2021"
license = "MIT"
diff --git a/crunchy-cli-core/Cargo.toml b/crunchy-cli-core/Cargo.toml
index 896b68f..8e1ba3a 100644
--- a/crunchy-cli-core/Cargo.toml
+++ b/crunchy-cli-core/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli-core"
authors = ["Crunchy Labs Maintainers"]
-version = "3.6.0"
+version = "3.6.1"
edition = "2021"
license = "MIT"
@@ -30,7 +30,7 @@ log = { version = "0.4", features = ["std"] }
num_cpus = "1.16"
regex = "1.10"
reqwest = { version = "0.12", features = ["socks", "stream"] }
-rsubs-lib = "0.2"
+rsubs-lib = ">=0.2.1"
rusty-chromaprint = "0.2"
serde = "1.0"
serde_json = "1.0"
From 53a710a3732047a1e08d475f6f112b440b8bde8e Mon Sep 17 00:00:00 2001
From: Simon <47527944+Frooastside@users.noreply.github.com>
Date: Tue, 7 May 2024 16:13:10 +0200
Subject: [PATCH 59/82] Fix audio syncing using wrong internal index (#407)
---
crunchy-cli-core/src/utils/download.rs | 8 ++------
1 file changed, 2 insertions(+), 6 deletions(-)
diff --git a/crunchy-cli-core/src/utils/download.rs b/crunchy-cli-core/src/utils/download.rs
index 565ed7d..8a8ad57 100644
--- a/crunchy-cli-core/src/utils/download.rs
+++ b/crunchy-cli-core/src/utils/download.rs
@@ -321,8 +321,6 @@ impl Downloader {
if let Some(offsets) = offsets {
let mut root_format_idx = 0;
let mut root_format_length = 0;
- let mut audio_count: usize = 0;
- let mut subtitle_count: usize = 0;
for (i, format) in self.formats.iter().enumerate() {
let offset = offsets.get(&i).copied().unwrap_or_default();
let format_len = format
@@ -340,15 +338,13 @@ impl Downloader {
for _ in &format.audios {
if let Some(offset) = &offsets.get(&i) {
- audio_offsets.insert(audio_count, **offset);
+ audio_offsets.insert(i, **offset);
}
- audio_count += 1
}
for _ in &format.subtitles {
if let Some(offset) = &offsets.get(&i) {
- subtitle_offsets.insert(subtitle_count, **offset);
+ subtitle_offsets.insert(i, **offset);
}
- subtitle_count += 1
}
}
From 48bb7a5ef669d3d89ccecfbf02929adeea99a6bd Mon Sep 17 00:00:00 2001
From: bytedream
Date: Tue, 14 May 2024 16:11:55 +0200
Subject: [PATCH 60/82] Fix crashes when converting subtitles (#408)
---
Cargo.lock | 6 ++--
crunchy-cli-core/Cargo.toml | 3 +-
crunchy-cli-core/src/utils/download.rs | 39 ++++++++++++++++----------
3 files changed, 30 insertions(+), 18 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index 44a47cd..cd1f282 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -386,6 +386,7 @@ dependencies = [
"shlex",
"sys-locale",
"tempfile",
+ "time",
"tokio",
"tokio-util",
"tower-service",
@@ -1511,12 +1512,13 @@ checksum = "b833d8d034ea094b1ea68aa6d5c740e0d04bad9d16568d08ba6f76823a114316"
[[package]]
name = "rsubs-lib"
-version = "0.2.1"
+version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9dcca2a9560fca05de8f95bc3767e46673d4b4c1f2c7a11092e10efd95bbdf62"
+checksum = "f43e1a7f184bc76407dbaa67bd2aeea8a15430d7e1e498070963336d03ebedee"
dependencies = [
"regex",
"serde",
+ "time",
]
[[package]]
diff --git a/crunchy-cli-core/Cargo.toml b/crunchy-cli-core/Cargo.toml
index 8e1ba3a..49f7a5e 100644
--- a/crunchy-cli-core/Cargo.toml
+++ b/crunchy-cli-core/Cargo.toml
@@ -30,7 +30,7 @@ log = { version = "0.4", features = ["std"] }
num_cpus = "1.16"
regex = "1.10"
reqwest = { version = "0.12", features = ["socks", "stream"] }
-rsubs-lib = ">=0.2.1"
+rsubs-lib = "0.3"
rusty-chromaprint = "0.2"
serde = "1.0"
serde_json = "1.0"
@@ -38,6 +38,7 @@ serde_plain = "1.0"
shlex = "1.3"
sys-locale = "0.3"
tempfile = "3.10"
+time = "0.3"
tokio = { version = "1.37", features = ["io-util", "macros", "net", "rt-multi-thread", "time"] }
tokio-util = "0.7"
tower-service = "0.3"
diff --git a/crunchy-cli-core/src/utils/download.rs b/crunchy-cli-core/src/utils/download.rs
index 8a8ad57..43d165b 100644
--- a/crunchy-cli-core/src/utils/download.rs
+++ b/crunchy-cli-core/src/utils/download.rs
@@ -13,17 +13,19 @@ use indicatif::{ProgressBar, ProgressDrawTarget, ProgressFinish, ProgressStyle};
use log::{debug, warn, LevelFilter};
use regex::Regex;
use reqwest::Client;
-use rsubs_lib::{ssa, vtt};
+use rsubs_lib::{SSA, VTT};
use std::borrow::Borrow;
use std::cmp::Ordering;
use std::collections::{BTreeMap, HashMap};
use std::io::Write;
+use std::ops::Add;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::Arc;
use std::time::Duration;
use std::{env, fs};
use tempfile::TempPath;
+use time::Time;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader};
use tokio::select;
use tokio::sync::mpsc::unbounded_channel;
@@ -929,36 +931,43 @@ impl Downloader {
) -> Result {
let buf = subtitle.data().await?;
let mut ass = match subtitle.format.as_str() {
- "ass" => ssa::parse(String::from_utf8_lossy(&buf).to_string()),
- "vtt" => vtt::parse(String::from_utf8_lossy(&buf).to_string()).to_ass(),
+ "ass" => SSA::parse(String::from_utf8_lossy(&buf))?,
+ "vtt" => VTT::parse(String::from_utf8_lossy(&buf))?.to_ssa(),
_ => bail!("unknown subtitle format: {}", subtitle.format),
};
// subtitles aren't always correct sorted and video players may have issues with that. to
// prevent issues, the subtitles are sorted
- ass.events
- .sort_by(|a, b| a.line_start.total_ms().cmp(&b.line_start.total_ms()));
+ // (https://github.com/crunchy-labs/crunchy-cli/issues/208)
+ ass.events.sort_by(|a, b| a.start.cmp(&b.start));
// it might be the case that the start and/or end time are greater than the actual video
// length. this might also result in issues with video players, thus the times are stripped
- // to be maxim
+ // to be at most as long as `max_length`
+ // (https://github.com/crunchy-labs/crunchy-cli/issues/32)
for i in (0..ass.events.len()).rev() {
- if ass.events[i].line_end.total_ms() > max_length.num_milliseconds() as u32 {
- if ass.events[i].line_start.total_ms() > max_length.num_milliseconds() as u32 {
- ass.events[i]
- .line_start
- .set_ms(max_length.num_milliseconds() as u32);
+ let max_len = Time::from_hms(0, 0, 0)
+ .unwrap()
+ .add(Duration::from_millis(max_length.num_milliseconds() as u64));
+
+ if ass.events[i].start > max_len {
+ if ass.events[i].end > max_len {
+ ass.events[i].start = max_len
}
- ass.events[i]
- .line_end
- .set_ms(max_length.num_milliseconds() as u32);
+ ass.events[i].end = max_len
} else {
break;
}
}
+ // without this additional info, subtitle look very messy in some video player
+ // (https://github.com/crunchy-labs/crunchy-cli/issues/66)
+ ass.info
+ .additional_fields
+ .insert("ScaledBorderAndShadows".to_string(), "yes".to_string());
+
let tempfile = tempfile(".ass")?;
let path = tempfile.into_temp_path();
- ass.to_file(path.to_string_lossy().to_string().as_str())?;
+ fs::write(&path, ass.to_string())?;
Ok(path)
}
From 817963af4fbf0eef1fde26a02f0771e343ce35d9 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Tue, 14 May 2024 21:22:23 +0200
Subject: [PATCH 61/82] Fix video containing hardsub if not requested (#415)
---
crunchy-cli-core/src/download/command.rs | 20 ++++++++++++++------
crunchy-cli-core/src/utils/video.rs | 24 ++++--------------------
2 files changed, 18 insertions(+), 26 deletions(-)
diff --git a/crunchy-cli-core/src/download/command.rs b/crunchy-cli-core/src/download/command.rs
index bb0c1fd..a9c3acf 100644
--- a/crunchy-cli-core/src/download/command.rs
+++ b/crunchy-cli-core/src/download/command.rs
@@ -384,12 +384,20 @@ async fn get_format(
let subtitle = if contains_hardsub {
None
} else if let Some(subtitle_locale) = &download.subtitle {
- stream
- .subtitles
- .get(subtitle_locale)
- .cloned()
- // use closed captions as fallback if no actual subtitles are found
- .or_else(|| stream.captions.get(subtitle_locale).cloned())
+ if download.audio == Locale::ja_JP {
+ stream
+ .subtitles
+ .get(subtitle_locale)
+ // use closed captions as fallback if no actual subtitles are found
+ .or_else(|| stream.captions.get(subtitle_locale))
+ .cloned()
+ } else {
+ stream
+ .captions
+ .get(subtitle_locale)
+ .or_else(|| stream.subtitles.get(subtitle_locale))
+ .cloned()
+ }
} else {
None
};
diff --git a/crunchy-cli-core/src/utils/video.rs b/crunchy-cli-core/src/utils/video.rs
index 07f6e76..8b25791 100644
--- a/crunchy-cli-core/src/utils/video.rs
+++ b/crunchy-cli-core/src/utils/video.rs
@@ -5,28 +5,12 @@ use crunchyroll_rs::Locale;
pub async fn stream_data_from_stream(
stream: &Stream,
resolution: &Resolution,
- subtitle: Option,
+ hardsub_subtitle: Option,
) -> Result> {
- // sometimes Crunchyroll marks episodes without real subtitles that they have subtitles and
- // reports that only hardsub episode are existing. the following lines are trying to prevent
- // potential errors which might get caused by this incorrect reporting
- // (https://github.com/crunchy-labs/crunchy-cli/issues/231)
- let mut hardsub_locales: Vec = stream.hard_subs.keys().cloned().collect();
- let (hardsub_locale, mut contains_hardsub) = if !hardsub_locales
- .contains(&Locale::Custom("".to_string()))
- && !hardsub_locales.contains(&Locale::Custom(":".to_string()))
- {
- // if only one hardsub locale exists, assume that this stream doesn't really contains hardsubs
- if hardsub_locales.len() == 1 {
- (Some(hardsub_locales.remove(0)), false)
- } else {
- // fallback to `None`. this should trigger an error message in `stream.dash_streaming_data`
- // that the requested stream is not available
- (None, false)
- }
+ let (hardsub_locale, mut contains_hardsub) = if hardsub_subtitle.is_some() {
+ (hardsub_subtitle, true)
} else {
- let hardsubs_requested = subtitle.is_some();
- (subtitle, hardsubs_requested)
+ (None, false)
};
let (mut videos, mut audios) = match stream.stream_data(hardsub_locale).await {
From 590242712b00c90c6c4cd49744764a1b04b64789 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Tue, 14 May 2024 21:36:12 +0200
Subject: [PATCH 62/82] Add warning message the `--skip-existing-method` has no
effect without `--skip-existing` (#418)
---
crunchy-cli-core/src/archive/command.rs | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/crunchy-cli-core/src/archive/command.rs b/crunchy-cli-core/src/archive/command.rs
index 38bddc1..44a30de 100644
--- a/crunchy-cli-core/src/archive/command.rs
+++ b/crunchy-cli-core/src/archive/command.rs
@@ -234,6 +234,10 @@ impl Execute for Archive {
bail!("`--include-chapters` can only be used if `--merge` is set to 'audio' or 'sync'")
}
+ if !self.skip_existing_method.is_empty() && !self.skip_existing {
+ warn!("`--skip-existing-method` has no effect if `--skip-existing` is not set")
+ }
+
self.audio = all_locale_in_locales(self.audio.clone());
self.subtitle = all_locale_in_locales(self.subtitle.clone());
From a98e31f959892fed57a0510356a0c6a47a5c8672 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Tue, 14 May 2024 22:36:59 +0200
Subject: [PATCH 63/82] Only include one CC subtitle
---
crunchy-cli-core/src/archive/command.rs | 31 +++++++++++--------------
1 file changed, 14 insertions(+), 17 deletions(-)
diff --git a/crunchy-cli-core/src/archive/command.rs b/crunchy-cli-core/src/archive/command.rs
index 44a30de..113447f 100644
--- a/crunchy-cli-core/src/archive/command.rs
+++ b/crunchy-cli-core/src/archive/command.rs
@@ -501,24 +501,21 @@ async fn get_format(
.subtitle
.iter()
.flat_map(|s| {
- let subtitles = stream
- .subtitles
- .get(s)
- .cloned()
- // the subtitle is probably cc if the audio is not japanese or only one
- // subtitle exists for this stream
- .map(|l| {
- (
- l,
- single_format.audio != Locale::ja_JP && stream.subtitles.len() == 1,
- )
- });
- let cc = stream.captions.get(s).cloned().map(|l| (l, true));
-
+ let mut subtitles = vec![];
+ if let Some(caption) = stream.captions.get(s) {
+ subtitles.push((caption.clone(), true))
+ }
+ if let Some(subtitle) = stream.subtitles.get(s) {
+ // the subtitle is probably cc if the audio is not japanese or only one subtitle
+ // exists for this stream
+ let cc = single_format.audio != Locale::ja_JP && stream.subtitles.len() == 1;
+ // only include the subtitles if no cc subtitle is already present or if it's
+ // not cc
+ if subtitles.is_empty() || !cc {
+ subtitles.push((subtitle.clone(), cc))
+ }
+ }
subtitles
- .into_iter()
- .chain(cc.into_iter())
- .collect::>()
})
.collect();
From 5279a9b75910992ad1731557ad65ce4302bb9208 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Tue, 14 May 2024 23:42:37 +0200
Subject: [PATCH 64/82] Update dependencies and version
---
Cargo.lock | 57 +++++++++++++++++++------------------
Cargo.toml | 2 +-
crunchy-cli-core/Cargo.toml | 2 +-
3 files changed, 31 insertions(+), 30 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index cd1f282..198afc9 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -343,7 +343,7 @@ checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f"
[[package]]
name = "crunchy-cli"
-version = "3.6.1"
+version = "3.6.2"
dependencies = [
"chrono",
"clap",
@@ -356,7 +356,7 @@ dependencies = [
[[package]]
name = "crunchy-cli-core"
-version = "3.6.1"
+version = "3.6.2"
dependencies = [
"anyhow",
"async-speed-limit",
@@ -476,12 +476,13 @@ dependencies = [
[[package]]
name = "dash-mpd"
-version = "0.16.1"
+version = "0.16.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "79b4bdd5f1c0c7493d780c645f0bff5b9361e6408210fa88910adb181efca64c"
+checksum = "876a00c22923799ac46365eb528c10134f979bf58ced5e3113de5b98d9835290"
dependencies = [
"base64 0.22.1",
"base64-serde",
+ "bytes",
"chrono",
"fs-err",
"iso8601",
@@ -581,9 +582,9 @@ checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5"
[[package]]
name = "errno"
-version = "0.3.8"
+version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a258e46cdc063eb8519c00b9fc845fc47bcfca4130e2f08e88665ceda8474245"
+checksum = "534c5cf6194dfab3db3242765c03bbe257cf92f22b38f6bc0c58d59108a820ba"
dependencies = [
"libc",
"windows-sys 0.52.0",
@@ -1156,9 +1157,9 @@ dependencies = [
[[package]]
name = "num-complex"
-version = "0.4.5"
+version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "23c6602fda94a57c990fe0df199a035d83576b496aa29f4e634a8ac6004e68a6"
+checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
dependencies = [
"num-traits",
]
@@ -1345,9 +1346,9 @@ dependencies = [
[[package]]
name = "proc-macro2"
-version = "1.0.81"
+version = "1.0.82"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3d1597b0c024618f09a9c3b8655b7e430397a36d23fdafec26d6965e9eec3eba"
+checksum = "8ad3d49ab951a01fbaafe34f2ec74122942fe18a3f9814c3268f1bb72042131b"
dependencies = [
"unicode-ident",
]
@@ -1535,9 +1536,9 @@ dependencies = [
[[package]]
name = "rustc-demangle"
-version = "0.1.23"
+version = "0.1.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76"
+checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f"
[[package]]
name = "rustfft"
@@ -1606,9 +1607,9 @@ dependencies = [
[[package]]
name = "rustls-pki-types"
-version = "1.5.0"
+version = "1.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "beb461507cee2c2ff151784c52762cf4d9ff6a61f3e80968600ed24fa837fa54"
+checksum = "976295e77ce332211c0d24d92c0e83e50f5c5f046d11082cea19f3df13a3562d"
[[package]]
name = "rustls-webpki"
@@ -1633,9 +1634,9 @@ dependencies = [
[[package]]
name = "ryu"
-version = "1.0.17"
+version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e86697c916019a8588c99b5fac3cead74ec0b4b819707a682fd4d23fa0ce1ba1"
+checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f"
[[package]]
name = "schannel"
@@ -1671,18 +1672,18 @@ dependencies = [
[[package]]
name = "serde"
-version = "1.0.200"
+version = "1.0.201"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ddc6f9cc94d67c0e21aaf7eda3a010fd3af78ebf6e096aa6e2e13c79749cce4f"
+checksum = "780f1cebed1629e4753a1a38a3c72d30b97ec044f0aef68cb26650a3c5cf363c"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
-version = "1.0.200"
+version = "1.0.201"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "856f046b9400cee3c8c94ed572ecdb752444c24528c035cd35882aad6f492bcb"
+checksum = "c5e405930b9796f1c00bee880d03fc7e0bb4b9a11afc776885ffe84320da2865"
dependencies = [
"proc-macro2",
"quote",
@@ -1691,9 +1692,9 @@ dependencies = [
[[package]]
name = "serde_json"
-version = "1.0.116"
+version = "1.0.117"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3e17db7126d17feb94eb3fad46bf1a96b034e8aacbc2e775fe81505f8b0b2813"
+checksum = "455182ea6142b14f93f4bc5320a2b31c1f266b66a4a5c858b013302a5d8cbfc3"
dependencies = [
"itoa",
"ryu",
@@ -1841,9 +1842,9 @@ checksum = "81cdd64d312baedb58e21336b31bc043b77e01cc99033ce76ef539f78e965ebc"
[[package]]
name = "syn"
-version = "2.0.60"
+version = "2.0.63"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "909518bc7b1c9b779f1bbf07f2929d35af9f0f37e47c6e9ef7f9dddc1e1821f3"
+checksum = "bf5be731623ca1a1fb7d8be6f261a3be6d3e2337b8a1f97be944d020c8fcb704"
dependencies = [
"proc-macro2",
"quote",
@@ -1900,18 +1901,18 @@ dependencies = [
[[package]]
name = "thiserror"
-version = "1.0.59"
+version = "1.0.60"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f0126ad08bff79f29fc3ae6a55cc72352056dfff61e3ff8bb7129476d44b23aa"
+checksum = "579e9083ca58dd9dcf91a9923bb9054071b9ebbd800b342194c9feb0ee89fc18"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
-version = "1.0.59"
+version = "1.0.60"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d1cd413b5d558b4c5bf3680e324a6fa5014e7b7c067a51e69dbdf47eb7148b66"
+checksum = "e2470041c06ec3ac1ab38d0356a6119054dedaea53e12fbefc0de730a1c08524"
dependencies = [
"proc-macro2",
"quote",
diff --git a/Cargo.toml b/Cargo.toml
index 26f71f3..1a1c76f 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli"
authors = ["Crunchy Labs Maintainers"]
-version = "3.6.1"
+version = "3.6.2"
edition = "2021"
license = "MIT"
diff --git a/crunchy-cli-core/Cargo.toml b/crunchy-cli-core/Cargo.toml
index 49f7a5e..f3388f7 100644
--- a/crunchy-cli-core/Cargo.toml
+++ b/crunchy-cli-core/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli-core"
authors = ["Crunchy Labs Maintainers"]
-version = "3.6.1"
+version = "3.6.2"
edition = "2021"
license = "MIT"
From 9819b622594e3cb2164aedcef71827618b421c41 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Fri, 17 May 2024 23:45:41 +0200
Subject: [PATCH 65/82] Fix typo in additional subtitle field (#421)
---
crunchy-cli-core/src/utils/download.rs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/crunchy-cli-core/src/utils/download.rs b/crunchy-cli-core/src/utils/download.rs
index 43d165b..d54b0bc 100644
--- a/crunchy-cli-core/src/utils/download.rs
+++ b/crunchy-cli-core/src/utils/download.rs
@@ -962,7 +962,7 @@ impl Downloader {
// (https://github.com/crunchy-labs/crunchy-cli/issues/66)
ass.info
.additional_fields
- .insert("ScaledBorderAndShadows".to_string(), "yes".to_string());
+ .insert("ScaledBorderAndShadow".to_string(), "yes".to_string());
let tempfile = tempfile(".ass")?;
let path = tempfile.into_temp_path();
From 301dac478f177b70723672effa3f2651ff8419d1 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Mon, 20 May 2024 15:57:28 +0200
Subject: [PATCH 66/82] Update dependencies and version
---
Cargo.lock | 99 ++++++++++++++++++-------------------
Cargo.toml | 5 +-
crunchy-cli-core/Cargo.toml | 2 +-
3 files changed, 53 insertions(+), 53 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index 198afc9..140125d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -92,9 +92,9 @@ dependencies = [
[[package]]
name = "anyhow"
-version = "1.0.83"
+version = "1.0.86"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "25bdb32cbbdce2b519a9cd7df3a678443100e265d5e25ca763b7572a5104f5f3"
+checksum = "b3d1d046238990b9cf5bcde22a3fb3584ee5cf65fb2765f454ed428c7a0063da"
[[package]]
name = "async-speed-limit"
@@ -119,6 +119,12 @@ dependencies = [
"syn",
]
+[[package]]
+name = "atomic-waker"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
+
[[package]]
name = "autocfg"
version = "1.3.0"
@@ -188,9 +194,9 @@ checksum = "514de17de45fdb8dc022b1a7975556c53c86f9f0aa5f534b98977b171857c2c9"
[[package]]
name = "cc"
-version = "1.0.97"
+version = "1.0.98"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "099a5357d84c4c61eb35fc8eafa9a79a902c2f76911e5747ced4e032edd8d9b4"
+checksum = "41c270e7540d725e65ac7f1b212ac8ce349719624d7bcff99f8e2e488e8cf03f"
[[package]]
name = "cfg-if"
@@ -238,7 +244,7 @@ dependencies = [
"anstream",
"anstyle",
"clap_lex",
- "strsim 0.11.1",
+ "strsim",
]
[[package]]
@@ -343,7 +349,7 @@ checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f"
[[package]]
name = "crunchy-cli"
-version = "3.6.2"
+version = "3.6.3"
dependencies = [
"chrono",
"clap",
@@ -356,7 +362,7 @@ dependencies = [
[[package]]
name = "crunchy-cli-core"
-version = "3.6.2"
+version = "3.6.3"
dependencies = [
"anyhow",
"async-speed-limit",
@@ -441,9 +447,9 @@ dependencies = [
[[package]]
name = "darling"
-version = "0.20.8"
+version = "0.20.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "54e36fcd13ed84ffdfda6f5be89b31287cbb80c439841fe69e04841435464391"
+checksum = "83b2eb4d90d12bdda5ed17de686c2acb4c57914f8f921b8da7e112b5a36f3fe1"
dependencies = [
"darling_core",
"darling_macro",
@@ -451,23 +457,23 @@ dependencies = [
[[package]]
name = "darling_core"
-version = "0.20.8"
+version = "0.20.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9c2cf1c23a687a1feeb728783b993c4e1ad83d99f351801977dd809b48d0a70f"
+checksum = "622687fe0bac72a04e5599029151f5796111b90f1baaa9b544d807a5e31cd120"
dependencies = [
"fnv",
"ident_case",
"proc-macro2",
"quote",
- "strsim 0.10.0",
+ "strsim",
"syn",
]
[[package]]
name = "darling_macro"
-version = "0.20.8"
+version = "0.20.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a668eda54683121533a393014d8692171709ff57a7d61f187b6e782719f8933f"
+checksum = "733cabb43482b1a1b53eee8583c2b9e8684d592215ea83efd305dd31bc2f0178"
dependencies = [
"darling_core",
"quote",
@@ -555,9 +561,9 @@ dependencies = [
[[package]]
name = "either"
-version = "1.11.0"
+version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a47c1c47d2f5964e29c61246e81db715514cd532db6b5116a25ea3c03d6780a2"
+checksum = "3dca9240753cf90908d7e4aac30f630662b02aebaa1b58a3cadabdb23385b58b"
[[package]]
name = "encode_unicode"
@@ -733,15 +739,15 @@ checksum = "4271d37baee1b8c7e4b708028c57d816cf9d2434acb33a549475f78c181f6253"
[[package]]
name = "h2"
-version = "0.4.4"
+version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "816ec7294445779408f36fe57bc5b7fc1cf59664059096c65f905c1c61f58069"
+checksum = "fa82e28a107a8cc405f0839610bdc9b15f1e25ec7d696aa5cf173edbcb1486ab"
dependencies = [
+ "atomic-waker",
"bytes",
"fnv",
"futures-core",
"futures-sink",
- "futures-util",
"http",
"indexmap 2.2.6",
"slab",
@@ -979,9 +985,9 @@ dependencies = [
[[package]]
name = "instant"
-version = "0.1.12"
+version = "0.1.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c"
+checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222"
dependencies = [
"cfg-if",
]
@@ -1043,9 +1049,9 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]]
name = "libc"
-version = "0.2.154"
+version = "0.2.155"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ae743338b92ff9146ce83992f766a31066a91a8c84a45e0e9f21e7cf6de6d346"
+checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c"
[[package]]
name = "libredox"
@@ -1059,9 +1065,9 @@ dependencies = [
[[package]]
name = "linux-raw-sys"
-version = "0.4.13"
+version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "01cda141df6706de531b6c46c3a33ecca755538219bd484262fa09410c13539c"
+checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89"
[[package]]
name = "log"
@@ -1099,9 +1105,9 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
[[package]]
name = "miniz_oxide"
-version = "0.7.2"
+version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9d811f3e15f28568be3407c8e7fdb6514c1cda3cb30683f15b6a1a1dc4ea14a7"
+checksum = "87dfd01fe195c66b572b37921ad8803d010623c0aca821bea2302239d155cdae"
dependencies = [
"adler",
]
@@ -1120,7 +1126,7 @@ dependencies = [
[[package]]
name = "native-tls"
version = "0.2.11"
-source = "git+https://github.com/crunchy-labs/rust-not-so-native-tls.git?rev=fdba246#fdba246a79986607cbdf573733445498bb6da2a9"
+source = "git+https://github.com/crunchy-labs/rust-not-so-native-tls.git?rev=b7969a8#b7969a88210096e0570e29d42fb13533baf62aa6"
dependencies = [
"libc",
"log",
@@ -1346,9 +1352,9 @@ dependencies = [
[[package]]
name = "proc-macro2"
-version = "1.0.82"
+version = "1.0.83"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8ad3d49ab951a01fbaafe34f2ec74122942fe18a3f9814c3268f1bb72042131b"
+checksum = "0b33eb56c327dec362a9e55b3ad14f9d2f0904fb5a5b03b513ab5465399e9f43"
dependencies = [
"unicode-ident",
]
@@ -1514,8 +1520,7 @@ checksum = "b833d8d034ea094b1ea68aa6d5c740e0d04bad9d16568d08ba6f76823a114316"
[[package]]
name = "rsubs-lib"
version = "0.3.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f43e1a7f184bc76407dbaa67bd2aeea8a15430d7e1e498070963336d03ebedee"
+source = "git+https://github.com/crunchy-labs/rsubs-lib.git?rev=1c51f60#1c51f60b8c48f1a8f7b261372b237d89bdc17dd4"
dependencies = [
"regex",
"serde",
@@ -1613,9 +1618,9 @@ checksum = "976295e77ce332211c0d24d92c0e83e50f5c5f046d11082cea19f3df13a3562d"
[[package]]
name = "rustls-webpki"
-version = "0.102.3"
+version = "0.102.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f3bce581c0dd41bce533ce695a1437fa16a7ab5ac3ccfa99fe1a620a7885eabf"
+checksum = "ff448f7e92e913c4b7d4c6d8e4540a1724b319b4152b8aef6d4cf8339712b33e"
dependencies = [
"ring",
"rustls-pki-types",
@@ -1672,18 +1677,18 @@ dependencies = [
[[package]]
name = "serde"
-version = "1.0.201"
+version = "1.0.202"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "780f1cebed1629e4753a1a38a3c72d30b97ec044f0aef68cb26650a3c5cf363c"
+checksum = "226b61a0d411b2ba5ff6d7f73a476ac4f8bb900373459cd00fab8512828ba395"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
-version = "1.0.201"
+version = "1.0.202"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c5e405930b9796f1c00bee880d03fc7e0bb4b9a11afc776885ffe84320da2865"
+checksum = "6048858004bcff69094cd972ed40a32500f153bd3be9f716b2eed2e8217c4838"
dependencies = [
"proc-macro2",
"quote",
@@ -1822,12 +1827,6 @@ version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82"
-[[package]]
-name = "strsim"
-version = "0.10.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
-
[[package]]
name = "strsim"
version = "0.11.1"
@@ -1842,9 +1841,9 @@ checksum = "81cdd64d312baedb58e21336b31bc043b77e01cc99033ce76ef539f78e965ebc"
[[package]]
name = "syn"
-version = "2.0.63"
+version = "2.0.65"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bf5be731623ca1a1fb7d8be6f261a3be6d3e2337b8a1f97be944d020c8fcb704"
+checksum = "d2863d96a84c6439701d7a38f9de935ec562c8832cc55d1dde0f513b52fad106"
dependencies = [
"proc-macro2",
"quote",
@@ -1901,18 +1900,18 @@ dependencies = [
[[package]]
name = "thiserror"
-version = "1.0.60"
+version = "1.0.61"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "579e9083ca58dd9dcf91a9923bb9054071b9ebbd800b342194c9feb0ee89fc18"
+checksum = "c546c80d6be4bc6a00c0f01730c08df82eaa7a7a61f11d656526506112cc1709"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
-version = "1.0.60"
+version = "1.0.61"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e2470041c06ec3ac1ab38d0356a6119054dedaea53e12fbefc0de730a1c08524"
+checksum = "46c3384250002a6d5af4d114f2845d37b57521033f30d5c3f46c4d70e1197533"
dependencies = [
"proc-macro2",
"quote",
diff --git a/Cargo.toml b/Cargo.toml
index 1a1c76f..4021ebc 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli"
authors = ["Crunchy Labs Maintainers"]
-version = "3.6.2"
+version = "3.6.3"
edition = "2021"
license = "MIT"
@@ -34,7 +34,8 @@ members = ["crunchy-cli-core"]
[patch.crates-io]
# fork of the `native-tls` crate which can use openssl as backend on every platform. this is done as `reqwest` only
# supports `rustls` and `native-tls` as tls backend
-native-tls = { git = "https://github.com/crunchy-labs/rust-not-so-native-tls.git", rev = "fdba246" }
+native-tls = { git = "https://github.com/crunchy-labs/rust-not-so-native-tls.git", rev = "b7969a8" }
+rsubs-lib = { git = "https://github.com/crunchy-labs/rsubs-lib.git", rev = "1c51f60" }
[profile.release]
strip = true
diff --git a/crunchy-cli-core/Cargo.toml b/crunchy-cli-core/Cargo.toml
index f3388f7..4b4416b 100644
--- a/crunchy-cli-core/Cargo.toml
+++ b/crunchy-cli-core/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli-core"
authors = ["Crunchy Labs Maintainers"]
-version = "3.6.2"
+version = "3.6.3"
edition = "2021"
license = "MIT"
From f7ce888329825470a42e13cf6c0dd35826783d6c Mon Sep 17 00:00:00 2001
From: bytedream
Date: Tue, 21 May 2024 21:33:08 +0200
Subject: [PATCH 67/82] Bypass stream limits
---
crunchy-cli-core/src/archive/command.rs | 4 ++-
crunchy-cli-core/src/download/command.rs | 2 ++
crunchy-cli-core/src/utils/format.rs | 32 +++++++++++++++---------
3 files changed, 25 insertions(+), 13 deletions(-)
diff --git a/crunchy-cli-core/src/archive/command.rs b/crunchy-cli-core/src/archive/command.rs
index 113447f..d34c4b7 100644
--- a/crunchy-cli-core/src/archive/command.rs
+++ b/crunchy-cli-core/src/archive/command.rs
@@ -520,7 +520,9 @@ async fn get_format(
.collect();
format_pairs.push((single_format, video.clone(), audio, subtitles.clone()));
- single_format_to_format_pairs.push((single_format.clone(), video, subtitles))
+ single_format_to_format_pairs.push((single_format.clone(), video, subtitles));
+
+ stream.invalidate().await?
}
let mut download_formats = vec![];
diff --git a/crunchy-cli-core/src/download/command.rs b/crunchy-cli-core/src/download/command.rs
index a9c3acf..fcf069b 100644
--- a/crunchy-cli-core/src/download/command.rs
+++ b/crunchy-cli-core/src/download/command.rs
@@ -434,5 +434,7 @@ async fn get_format(
subs.push(download.subtitle.clone().unwrap())
}
+ stream.invalidate().await?;
+
Ok((download_format, format))
}
diff --git a/crunchy-cli-core/src/utils/format.rs b/crunchy-cli-core/src/utils/format.rs
index 0a71838..325c731 100644
--- a/crunchy-cli-core/src/utils/format.rs
+++ b/crunchy-cli-core/src/utils/format.rs
@@ -2,7 +2,7 @@ use crate::utils::filter::real_dedup_vec;
use crate::utils::locale::LanguageTagging;
use crate::utils::log::tab_info;
use crate::utils::os::{is_special_file, sanitize};
-use anyhow::{bail, Result};
+use anyhow::Result;
use chrono::{Datelike, Duration};
use crunchyroll_rs::media::{Resolution, SkipEvents, Stream, StreamData, Subtitle};
use crunchyroll_rs::{Concert, Episode, Locale, MediaCollection, Movie, MusicVideo};
@@ -166,19 +166,27 @@ impl SingleFormat {
}
pub async fn stream(&self) -> Result {
- let stream = match &self.source {
- MediaCollection::Episode(e) => e.stream_maybe_without_drm().await?,
- MediaCollection::Movie(m) => m.stream_maybe_without_drm().await?,
- MediaCollection::MusicVideo(mv) => mv.stream_maybe_without_drm().await?,
- MediaCollection::Concert(c) => c.stream_maybe_without_drm().await?,
- _ => unreachable!(),
- };
+ let mut i = 0;
+ loop {
+ let stream = match &self.source {
+ MediaCollection::Episode(e) => e.stream_maybe_without_drm().await,
+ MediaCollection::Movie(m) => m.stream_maybe_without_drm().await,
+ MediaCollection::MusicVideo(mv) => mv.stream_maybe_without_drm().await,
+ MediaCollection::Concert(c) => c.stream_maybe_without_drm().await,
+ _ => unreachable!(),
+ };
- if stream.session.uses_stream_limits {
- bail!("Found a stream which probably uses DRM. DRM downloads aren't supported")
+ // sometimes the request to get streams fails with an 403 and the message "JWT error",
+ // even if the jwt (i guess the auth bearer token is meant by that) is perfectly valid.
+ // it's retried the request 3 times if this specific error occurs
+ if let Err(crunchyroll_rs::error::Error::Request { message, .. }) = &stream {
+ if message == "JWT error" && i < 3 {
+ i += 1;
+ continue;
+ }
+ };
+ return Ok(stream?);
}
-
- Ok(stream)
}
pub async fn skip_events(&self) -> Result> {
From cbe57e2b6e6262c5a94312a9646faea3a9f23ccb Mon Sep 17 00:00:00 2001
From: bytedream
Date: Tue, 21 May 2024 21:34:05 +0200
Subject: [PATCH 68/82] Update dependencies and version
---
Cargo.lock | 12 ++++++------
Cargo.toml | 2 +-
crunchy-cli-core/Cargo.toml | 2 +-
3 files changed, 8 insertions(+), 8 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index 140125d..5ea720f 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -349,7 +349,7 @@ checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f"
[[package]]
name = "crunchy-cli"
-version = "3.6.3"
+version = "3.6.4"
dependencies = [
"chrono",
"clap",
@@ -362,7 +362,7 @@ dependencies = [
[[package]]
name = "crunchy-cli-core"
-version = "3.6.3"
+version = "3.6.4"
dependencies = [
"anyhow",
"async-speed-limit",
@@ -482,9 +482,9 @@ dependencies = [
[[package]]
name = "dash-mpd"
-version = "0.16.2"
+version = "0.16.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "876a00c22923799ac46365eb528c10134f979bf58ced5e3113de5b98d9835290"
+checksum = "4618a5e165bf47b084963611bcf1d568c681f52d8a237e8862a0cd8c546ba255"
dependencies = [
"base64 0.22.1",
"base64-serde",
@@ -1259,9 +1259,9 @@ checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf"
[[package]]
name = "openssl-src"
-version = "300.2.3+3.2.1"
+version = "300.3.0+3.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5cff92b6f71555b61bb9315f7c64da3ca43d87531622120fea0195fc761b4843"
+checksum = "eba8804a1c5765b18c4b3f907e6897ebabeedebc9830e1a0046c4a4cf44663e1"
dependencies = [
"cc",
]
diff --git a/Cargo.toml b/Cargo.toml
index 4021ebc..98d2269 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli"
authors = ["Crunchy Labs Maintainers"]
-version = "3.6.3"
+version = "3.6.4"
edition = "2021"
license = "MIT"
diff --git a/crunchy-cli-core/Cargo.toml b/crunchy-cli-core/Cargo.toml
index 4b4416b..8370fdc 100644
--- a/crunchy-cli-core/Cargo.toml
+++ b/crunchy-cli-core/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli-core"
authors = ["Crunchy Labs Maintainers"]
-version = "3.6.3"
+version = "3.6.4"
edition = "2021"
license = "MIT"
From f8bd0929872f4c78a6d2b54eee7dacb4c94cfb9d Mon Sep 17 00:00:00 2001
From: bytedream
Date: Tue, 21 May 2024 21:51:18 +0200
Subject: [PATCH 69/82] Add custom error message if too many streams are active
---
crunchy-cli-core/src/utils/format.rs | 10 ++++++----
1 file changed, 6 insertions(+), 4 deletions(-)
diff --git a/crunchy-cli-core/src/utils/format.rs b/crunchy-cli-core/src/utils/format.rs
index 325c731..436be78 100644
--- a/crunchy-cli-core/src/utils/format.rs
+++ b/crunchy-cli-core/src/utils/format.rs
@@ -2,7 +2,7 @@ use crate::utils::filter::real_dedup_vec;
use crate::utils::locale::LanguageTagging;
use crate::utils::log::tab_info;
use crate::utils::os::{is_special_file, sanitize};
-use anyhow::Result;
+use anyhow::{bail, Result};
use chrono::{Datelike, Duration};
use crunchyroll_rs::media::{Resolution, SkipEvents, Stream, StreamData, Subtitle};
use crunchyroll_rs::{Concert, Episode, Locale, MediaCollection, Movie, MusicVideo};
@@ -176,13 +176,15 @@ impl SingleFormat {
_ => unreachable!(),
};
- // sometimes the request to get streams fails with an 403 and the message "JWT error",
- // even if the jwt (i guess the auth bearer token is meant by that) is perfectly valid.
- // it's retried the request 3 times if this specific error occurs
if let Err(crunchyroll_rs::error::Error::Request { message, .. }) = &stream {
+ // sometimes the request to get streams fails with an 403 and the message
+ // "JWT error", even if the jwt (i guess the auth bearer token is meant by that) is
+ // perfectly valid. it's retried the request 3 times if this specific error occurs
if message == "JWT error" && i < 3 {
i += 1;
continue;
+ } else if message.starts_with("TOO_MANY_ACTIVE_STREAMS") {
+ bail!("Too many active/parallel streams. Please close at least one stream you're watching and try again")
}
};
return Ok(stream?);
From 5593046aae4c399c1f0568c14ff35f3d75d96edc Mon Sep 17 00:00:00 2001
From: bytedream
Date: Wed, 22 May 2024 16:52:43 +0200
Subject: [PATCH 70/82] Update dependencies and version
---
Cargo.lock | 12 ++++++------
Cargo.toml | 2 +-
crunchy-cli-core/Cargo.toml | 4 ++--
3 files changed, 9 insertions(+), 9 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index 5ea720f..b24bc20 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -349,7 +349,7 @@ checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f"
[[package]]
name = "crunchy-cli"
-version = "3.6.4"
+version = "3.6.5"
dependencies = [
"chrono",
"clap",
@@ -362,7 +362,7 @@ dependencies = [
[[package]]
name = "crunchy-cli-core"
-version = "3.6.4"
+version = "3.6.5"
dependencies = [
"anyhow",
"async-speed-limit",
@@ -400,9 +400,9 @@ dependencies = [
[[package]]
name = "crunchyroll-rs"
-version = "0.11.1"
+version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "58580acc9c0abf96a231ec8b1a4597ea55d9426ea17f684ce3582e2b26437bbb"
+checksum = "7a6754d10e1890089eb733b71aee6f4cbc18374040aedb04c4ca76020bcd9818"
dependencies = [
"async-trait",
"chrono",
@@ -426,9 +426,9 @@ dependencies = [
[[package]]
name = "crunchyroll-rs-internal"
-version = "0.11.1"
+version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ce3c844dec8a3390f8c9853b5cf1d65c3d38fd0657b8b5d0e008db8945dea326"
+checksum = "ca15fa827cca647852b091006f2b592f8727e1082f812b475b3f9ebe3f59d5bf"
dependencies = [
"darling",
"quote",
diff --git a/Cargo.toml b/Cargo.toml
index 98d2269..ccf80ec 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli"
authors = ["Crunchy Labs Maintainers"]
-version = "3.6.4"
+version = "3.6.5"
edition = "2021"
license = "MIT"
diff --git a/crunchy-cli-core/Cargo.toml b/crunchy-cli-core/Cargo.toml
index 8370fdc..98ff9d7 100644
--- a/crunchy-cli-core/Cargo.toml
+++ b/crunchy-cli-core/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli-core"
authors = ["Crunchy Labs Maintainers"]
-version = "3.6.4"
+version = "3.6.5"
edition = "2021"
license = "MIT"
@@ -16,7 +16,7 @@ anyhow = "1.0"
async-speed-limit = "0.4"
clap = { version = "4.5", features = ["derive", "string"] }
chrono = "0.4"
-crunchyroll-rs = { version = "0.11.1", features = ["experimental-stabilizations", "tower"] }
+crunchyroll-rs = { version = "0.11.2", features = ["experimental-stabilizations", "tower"] }
ctrlc = "3.4"
dialoguer = { version = "0.11", default-features = false }
dirs = "5.0"
From 7d2ae719c8fee83f2ba5041f214b87eb53d3c33c Mon Sep 17 00:00:00 2001
From: bytedream
Date: Wed, 22 May 2024 16:54:58 +0200
Subject: [PATCH 71/82] Remove internal jwt error retry
---
crunchy-cli-core/src/utils/format.rs | 35 +++++++++++-----------------
1 file changed, 13 insertions(+), 22 deletions(-)
diff --git a/crunchy-cli-core/src/utils/format.rs b/crunchy-cli-core/src/utils/format.rs
index 436be78..c5e8f3d 100644
--- a/crunchy-cli-core/src/utils/format.rs
+++ b/crunchy-cli-core/src/utils/format.rs
@@ -166,29 +166,20 @@ impl SingleFormat {
}
pub async fn stream(&self) -> Result {
- let mut i = 0;
- loop {
- let stream = match &self.source {
- MediaCollection::Episode(e) => e.stream_maybe_without_drm().await,
- MediaCollection::Movie(m) => m.stream_maybe_without_drm().await,
- MediaCollection::MusicVideo(mv) => mv.stream_maybe_without_drm().await,
- MediaCollection::Concert(c) => c.stream_maybe_without_drm().await,
- _ => unreachable!(),
- };
+ let stream = match &self.source {
+ MediaCollection::Episode(e) => e.stream_maybe_without_drm().await,
+ MediaCollection::Movie(m) => m.stream_maybe_without_drm().await,
+ MediaCollection::MusicVideo(mv) => mv.stream_maybe_without_drm().await,
+ MediaCollection::Concert(c) => c.stream_maybe_without_drm().await,
+ _ => unreachable!(),
+ };
- if let Err(crunchyroll_rs::error::Error::Request { message, .. }) = &stream {
- // sometimes the request to get streams fails with an 403 and the message
- // "JWT error", even if the jwt (i guess the auth bearer token is meant by that) is
- // perfectly valid. it's retried the request 3 times if this specific error occurs
- if message == "JWT error" && i < 3 {
- i += 1;
- continue;
- } else if message.starts_with("TOO_MANY_ACTIVE_STREAMS") {
- bail!("Too many active/parallel streams. Please close at least one stream you're watching and try again")
- }
- };
- return Ok(stream?);
- }
+ if let Err(crunchyroll_rs::error::Error::Request { message, .. }) = &stream {
+ if message.starts_with("TOO_MANY_ACTIVE_STREAMS") {
+ bail!("Too many active/parallel streams. Please close at least one stream you're watching and try again")
+ }
+ };
+ Ok(stream?)
}
pub async fn skip_events(&self) -> Result> {
From 74e5e05b0f8b4cb83cd5708747fe81a0183b56f0 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Wed, 22 May 2024 23:59:12 +0200
Subject: [PATCH 72/82] Invalidate stream when using search command (#428)
---
crunchy-cli-core/src/search/format.rs | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/crunchy-cli-core/src/search/format.rs b/crunchy-cli-core/src/search/format.rs
index 7ea84d8..ee855b2 100644
--- a/crunchy-cli-core/src/search/format.rs
+++ b/crunchy-cli-core/src/search/format.rs
@@ -464,7 +464,9 @@ impl Format {
if !stream_empty {
for (_, episodes) in tree.iter_mut() {
for (episode, streams) in episodes {
- streams.push(episode.stream_maybe_without_drm().await?)
+ let stream = episode.stream_maybe_without_drm().await?;
+ stream.clone().invalidate().await?;
+ streams.push(stream)
}
}
} else {
From a1c7b2069d79ecc634e3ba216fb86e63135d9501 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Thu, 23 May 2024 00:01:42 +0200
Subject: [PATCH 73/82] Update dependencies and version
---
Cargo.lock | 17 +++++++++--------
Cargo.toml | 3 +--
crunchy-cli-core/Cargo.toml | 6 +++---
3 files changed, 13 insertions(+), 13 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index b24bc20..8400022 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -349,7 +349,7 @@ checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f"
[[package]]
name = "crunchy-cli"
-version = "3.6.5"
+version = "3.6.6"
dependencies = [
"chrono",
"clap",
@@ -362,7 +362,7 @@ dependencies = [
[[package]]
name = "crunchy-cli-core"
-version = "3.6.5"
+version = "3.6.6"
dependencies = [
"anyhow",
"async-speed-limit",
@@ -400,9 +400,9 @@ dependencies = [
[[package]]
name = "crunchyroll-rs"
-version = "0.11.2"
+version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7a6754d10e1890089eb733b71aee6f4cbc18374040aedb04c4ca76020bcd9818"
+checksum = "1d33b8d77c80dea79e66993cb67963b2171dcf0b8fbc87591c58f2dadfea8da2"
dependencies = [
"async-trait",
"chrono",
@@ -426,9 +426,9 @@ dependencies = [
[[package]]
name = "crunchyroll-rs-internal"
-version = "0.11.2"
+version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ca15fa827cca647852b091006f2b592f8727e1082f812b475b3f9ebe3f59d5bf"
+checksum = "fa51945265f25c45f7d53bd70e5263dd023c0be45e38eaba886a971cb645d797"
dependencies = [
"darling",
"quote",
@@ -1519,8 +1519,9 @@ checksum = "b833d8d034ea094b1ea68aa6d5c740e0d04bad9d16568d08ba6f76823a114316"
[[package]]
name = "rsubs-lib"
-version = "0.3.0"
-source = "git+https://github.com/crunchy-labs/rsubs-lib.git?rev=1c51f60#1c51f60b8c48f1a8f7b261372b237d89bdc17dd4"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d01f7609f0b1bc4fe24b352e8d1792c7d71cc43aea797e14b87974cd009ab402"
dependencies = [
"regex",
"serde",
diff --git a/Cargo.toml b/Cargo.toml
index ccf80ec..f263e59 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli"
authors = ["Crunchy Labs Maintainers"]
-version = "3.6.5"
+version = "3.6.6"
edition = "2021"
license = "MIT"
@@ -35,7 +35,6 @@ members = ["crunchy-cli-core"]
# fork of the `native-tls` crate which can use openssl as backend on every platform. this is done as `reqwest` only
# supports `rustls` and `native-tls` as tls backend
native-tls = { git = "https://github.com/crunchy-labs/rust-not-so-native-tls.git", rev = "b7969a8" }
-rsubs-lib = { git = "https://github.com/crunchy-labs/rsubs-lib.git", rev = "1c51f60" }
[profile.release]
strip = true
diff --git a/crunchy-cli-core/Cargo.toml b/crunchy-cli-core/Cargo.toml
index 98ff9d7..56964ec 100644
--- a/crunchy-cli-core/Cargo.toml
+++ b/crunchy-cli-core/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli-core"
authors = ["Crunchy Labs Maintainers"]
-version = "3.6.5"
+version = "3.6.6"
edition = "2021"
license = "MIT"
@@ -16,7 +16,7 @@ anyhow = "1.0"
async-speed-limit = "0.4"
clap = { version = "4.5", features = ["derive", "string"] }
chrono = "0.4"
-crunchyroll-rs = { version = "0.11.2", features = ["experimental-stabilizations", "tower"] }
+crunchyroll-rs = { version = "0.11.3", features = ["experimental-stabilizations", "tower"] }
ctrlc = "3.4"
dialoguer = { version = "0.11", default-features = false }
dirs = "5.0"
@@ -30,7 +30,7 @@ log = { version = "0.4", features = ["std"] }
num_cpus = "1.16"
regex = "1.10"
reqwest = { version = "0.12", features = ["socks", "stream"] }
-rsubs-lib = "0.3"
+rsubs-lib = "~0.3.1"
rusty-chromaprint = "0.2"
serde = "1.0"
serde_json = "1.0"
From 67c267be2005d18d39c814087db905a801d41fc5 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Fri, 24 May 2024 22:05:04 +0200
Subject: [PATCH 74/82] Remove unused variable
---
crunchy-cli-core/src/utils/format.rs | 11 ++++-------
1 file changed, 4 insertions(+), 7 deletions(-)
diff --git a/crunchy-cli-core/src/utils/format.rs b/crunchy-cli-core/src/utils/format.rs
index c5e8f3d..f0a002c 100644
--- a/crunchy-cli-core/src/utils/format.rs
+++ b/crunchy-cli-core/src/utils/format.rs
@@ -4,7 +4,7 @@ use crate::utils::log::tab_info;
use crate::utils::os::{is_special_file, sanitize};
use anyhow::{bail, Result};
use chrono::{Datelike, Duration};
-use crunchyroll_rs::media::{Resolution, SkipEvents, Stream, StreamData, Subtitle};
+use crunchyroll_rs::media::{SkipEvents, Stream, StreamData, Subtitle};
use crunchyroll_rs::{Concert, Episode, Locale, MediaCollection, Movie, MusicVideo};
use log::{debug, info};
use std::cmp::Ordering;
@@ -354,8 +354,6 @@ pub struct Format {
pub locales: Vec<(Locale, Vec)>,
- // deprecated
- pub resolution: Resolution,
pub width: u64,
pub height: u64,
pub fps: f64,
@@ -401,7 +399,6 @@ impl Format {
title: first_format.title,
description: first_format.description,
locales,
- resolution: first_stream.resolution().unwrap(),
width: first_stream.resolution().unwrap().width,
height: first_stream.resolution().unwrap().height,
fps: first_stream.fps().unwrap(),
@@ -449,11 +446,11 @@ impl Format {
)
.replace(
"{width}",
- &sanitize(self.resolution.width.to_string(), true, universal),
+ &sanitize(self.width.to_string(), true, universal),
)
.replace(
"{height}",
- &sanitize(self.resolution.height.to_string(), true, universal),
+ &sanitize(self.height.to_string(), true, universal),
)
.replace("{series_id}", &sanitize(&self.series_id, true, universal))
.replace(
@@ -589,7 +586,7 @@ impl Format {
.collect::>()
.join(", ")
);
- tab_info!("Resolution: {}", self.resolution);
+ tab_info!("Resolution: {}x{}", self.height, self.width);
tab_info!("FPS: {:.2}", self.fps)
}
From fb8e53564442653bcaa972bf8143066b42cb49d3 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Fri, 24 May 2024 22:09:23 +0200
Subject: [PATCH 75/82] Fix subtitle title not being human-readable
---
crunchy-cli-core/src/utils/download.rs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/crunchy-cli-core/src/utils/download.rs b/crunchy-cli-core/src/utils/download.rs
index d54b0bc..accefce 100644
--- a/crunchy-cli-core/src/utils/download.rs
+++ b/crunchy-cli-core/src/utils/download.rs
@@ -654,7 +654,7 @@ impl Downloader {
metadata.extend([
format!("-metadata:s:s:{}", i),
format!("title={}", {
- let mut title = meta.locale.to_string();
+ let mut title = meta.locale.to_human_readable();
if meta.cc {
title += " (CC)"
}
From e7ac6d8874418c3311d433855f5991ea6f0be187 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Fri, 24 May 2024 22:17:25 +0200
Subject: [PATCH 76/82] Deprecate search stream.is_drm option
---
crunchy-cli-core/src/search/command.rs | 4 ++++
crunchy-cli-core/src/search/format.rs | 2 +-
2 files changed, 5 insertions(+), 1 deletion(-)
diff --git a/crunchy-cli-core/src/search/command.rs b/crunchy-cli-core/src/search/command.rs
index c29ce34..8032bed 100644
--- a/crunchy-cli-core/src/search/command.rs
+++ b/crunchy-cli-core/src/search/command.rs
@@ -111,6 +111,10 @@ impl Execute for Search {
warn!("Using `search` anonymously or with a non-premium account may return incomplete results")
}
+ if self.output.contains("{{stream.is_drm}}") {
+ warn!("The `{{{{stream.is_drm}}}}` option is deprecated as it isn't reliable anymore and will be removed soon")
+ }
+
let input = if crunchyroll_rs::parse::parse_url(&self.input).is_some() {
match parse_url(&ctx.crunchy, self.input.clone(), true).await {
Ok(ok) => vec![ok],
diff --git a/crunchy-cli-core/src/search/format.rs b/crunchy-cli-core/src/search/format.rs
index ee855b2..10f4624 100644
--- a/crunchy-cli-core/src/search/format.rs
+++ b/crunchy-cli-core/src/search/format.rs
@@ -173,7 +173,7 @@ impl From<&Stream> for FormatStream {
Self {
locale: value.audio_locale.clone(),
dash_url: value.url.clone(),
- is_drm: value.session.uses_stream_limits,
+ is_drm: false,
}
}
}
From 287df843828e106d4fef2661c796ffaa69742caf Mon Sep 17 00:00:00 2001
From: bytedream
Date: Fri, 14 Jun 2024 00:17:08 +0200
Subject: [PATCH 77/82] Rework episode filtering
---
Cargo.lock | 16 +-
crunchy-cli-core/Cargo.toml | 2 +-
crunchy-cli-core/src/archive/command.rs | 47 ++-
crunchy-cli-core/src/archive/filter.rs | 466 -----------------------
crunchy-cli-core/src/archive/mod.rs | 1 -
crunchy-cli-core/src/download/command.rs | 53 ++-
crunchy-cli-core/src/download/filter.rs | 307 ---------------
crunchy-cli-core/src/download/mod.rs | 1 -
crunchy-cli-core/src/search/format.rs | 28 +-
crunchy-cli-core/src/utils/filter.rs | 425 +++++++++++++++++++--
crunchy-cli-core/src/utils/format.rs | 2 +
11 files changed, 515 insertions(+), 833 deletions(-)
delete mode 100644 crunchy-cli-core/src/archive/filter.rs
delete mode 100644 crunchy-cli-core/src/download/filter.rs
diff --git a/Cargo.lock b/Cargo.lock
index 8400022..7fdb3d9 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -400,9 +400,9 @@ dependencies = [
[[package]]
name = "crunchyroll-rs"
-version = "0.11.3"
+version = "0.11.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1d33b8d77c80dea79e66993cb67963b2171dcf0b8fbc87591c58f2dadfea8da2"
+checksum = "d6e38c223aecf65c9c9bec50764beea5dc70b6c97cd7f767bf6860f2fc8e0a07"
dependencies = [
"async-trait",
"chrono",
@@ -426,9 +426,9 @@ dependencies = [
[[package]]
name = "crunchyroll-rs-internal"
-version = "0.11.3"
+version = "0.11.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fa51945265f25c45f7d53bd70e5263dd023c0be45e38eaba886a971cb645d797"
+checksum = "144a38040a21aaa456741a9f6749354527bb68ad3bb14210e0bbc40fbd95186c"
dependencies = [
"darling",
"quote",
@@ -1967,9 +1967,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "tokio"
-version = "1.37.0"
+version = "1.38.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1adbebffeca75fcfd058afa480fb6c0b81e165a0323f9c9d39c9697e37c46787"
+checksum = "ba4f4a02a7a80d6f274636f0aa95c7e383b912d41fe721a31f29e29698585a4a"
dependencies = [
"backtrace",
"bytes",
@@ -1984,9 +1984,9 @@ dependencies = [
[[package]]
name = "tokio-macros"
-version = "2.2.0"
+version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b"
+checksum = "5f5ae998a069d4b5aba8ee9dad856af7d520c3699e6159b185c2acd48155d39a"
dependencies = [
"proc-macro2",
"quote",
diff --git a/crunchy-cli-core/Cargo.toml b/crunchy-cli-core/Cargo.toml
index 56964ec..5c7b901 100644
--- a/crunchy-cli-core/Cargo.toml
+++ b/crunchy-cli-core/Cargo.toml
@@ -16,7 +16,7 @@ anyhow = "1.0"
async-speed-limit = "0.4"
clap = { version = "4.5", features = ["derive", "string"] }
chrono = "0.4"
-crunchyroll-rs = { version = "0.11.3", features = ["experimental-stabilizations", "tower"] }
+crunchyroll-rs = { version = "0.11.4", features = ["experimental-stabilizations", "tower"] }
ctrlc = "3.4"
dialoguer = { version = "0.11", default-features = false }
dirs = "5.0"
diff --git a/crunchy-cli-core/src/archive/command.rs b/crunchy-cli-core/src/archive/command.rs
index d34c4b7..0d1b3a4 100644
--- a/crunchy-cli-core/src/archive/command.rs
+++ b/crunchy-cli-core/src/archive/command.rs
@@ -1,10 +1,9 @@
-use crate::archive::filter::ArchiveFilter;
use crate::utils::context::Context;
use crate::utils::download::{
DownloadBuilder, DownloadFormat, DownloadFormatMetadata, MergeBehavior,
};
use crate::utils::ffmpeg::FFmpegPreset;
-use crate::utils::filter::Filter;
+use crate::utils::filter::{Filter, FilterMediaScope};
use crate::utils::format::{Format, SingleFormat};
use crate::utils::locale::{all_locale_in_locales, resolve_locales, LanguageTagging};
use crate::utils::log::progress;
@@ -284,9 +283,49 @@ impl Execute for Archive {
for (i, (media_collection, url_filter)) in parsed_urls.into_iter().enumerate() {
let progress_handler = progress!("Fetching series details");
- let single_format_collection = ArchiveFilter::new(
+ let single_format_collection = Filter::new(
url_filter,
- self.clone(),
+ self.audio.clone(),
+ self.subtitle.clone(),
+ |scope, locales| {
+ let audios = locales.into_iter().map(|l| l.to_string()).collect::>().join(", ");
+ match scope {
+ FilterMediaScope::Series(series) => warn!("Series {} is not available with {} audio", series.title, audios),
+ FilterMediaScope::Season(season) => warn!("Season {} is not available with {} audio", season.season_number, audios),
+ FilterMediaScope::Episode(episodes) => {
+ if episodes.len() == 1 {
+ warn!("Episode {} is not available with {} audio", episodes[0].sequence_number, audios)
+ } else if episodes.len() == 2 {
+ warn!("Season {} is only available with {} audio from episode {} to {}", episodes[0].season_number, audios, episodes[0].sequence_number, episodes[1].sequence_number)
+ } else {
+ unimplemented!()
+ }
+ }
+ }
+ Ok(true)
+ },
+ |scope, locales| {
+ let subtitles = locales.into_iter().map(|l| l.to_string()).collect::>().join(", ");
+ match scope {
+ FilterMediaScope::Series(series) => warn!("Series {} is not available with {} subtitles", series.title, subtitles),
+ FilterMediaScope::Season(season) => warn!("Season {} is not available with {} subtitles", season.season_number, subtitles),
+ FilterMediaScope::Episode(episodes) => {
+ if episodes.len() == 1 {
+ warn!("Episode {} of season {} is not available with {} subtitles", episodes[0].sequence_number, episodes[0].season_title, subtitles)
+ } else if episodes.len() == 2 {
+ warn!("Season {} of season {} is only available with {} subtitles from episode {} to {}", episodes[0].season_number, episodes[0].season_title, subtitles, episodes[0].sequence_number, episodes[1].sequence_number)
+ } else {
+ unimplemented!()
+ }
+ }
+ }
+ Ok(true)
+ },
+ |season| {
+ warn!("Skipping premium episodes in season {season}");
+ Ok(())
+ },
+ Format::has_relative_fmt(&self.output),
!self.yes,
self.skip_specials,
ctx.crunchy.premium().await,
diff --git a/crunchy-cli-core/src/archive/filter.rs b/crunchy-cli-core/src/archive/filter.rs
deleted file mode 100644
index b08fb6c..0000000
--- a/crunchy-cli-core/src/archive/filter.rs
+++ /dev/null
@@ -1,466 +0,0 @@
-use crate::archive::command::Archive;
-use crate::utils::filter::{real_dedup_vec, Filter};
-use crate::utils::format::{Format, SingleFormat, SingleFormatCollection};
-use crate::utils::interactive_select::{check_for_duplicated_seasons, get_duplicated_seasons};
-use crate::utils::parse::{fract, UrlFilter};
-use anyhow::Result;
-use crunchyroll_rs::{Concert, Episode, Locale, Movie, MovieListing, MusicVideo, Season, Series};
-use log::{info, warn};
-use std::collections::{BTreeMap, HashMap};
-use std::ops::Not;
-
-enum Visited {
- Series,
- Season,
- None,
-}
-
-pub(crate) struct ArchiveFilter {
- url_filter: UrlFilter,
- archive: Archive,
- interactive_input: bool,
- skip_special: bool,
- season_episodes: HashMap>,
- season_subtitles_missing: Vec,
- seasons_with_premium: Option>,
- season_sorting: Vec,
- visited: Visited,
-}
-
-impl ArchiveFilter {
- pub(crate) fn new(
- url_filter: UrlFilter,
- archive: Archive,
- interactive_input: bool,
- skip_special: bool,
- is_premium: bool,
- ) -> Self {
- Self {
- url_filter,
- archive,
- interactive_input,
- skip_special,
- season_episodes: HashMap::new(),
- season_subtitles_missing: vec![],
- seasons_with_premium: is_premium.not().then_some(vec![]),
- season_sorting: vec![],
- visited: Visited::None,
- }
- }
-}
-
-impl Filter for ArchiveFilter {
- type T = Vec;
- type Output = SingleFormatCollection;
-
- async fn visit_series(&mut self, series: Series) -> Result> {
- // `series.audio_locales` isn't always populated b/c of crunchyrolls api. so check if the
- // audio is matching only if the field is populated
- if !series.audio_locales.is_empty() {
- let missing_audio = missing_locales(&series.audio_locales, &self.archive.audio);
- if !missing_audio.is_empty() {
- warn!(
- "Series {} is not available with {} audio",
- series.title,
- missing_audio
- .into_iter()
- .map(|l| l.to_string())
- .collect::>()
- .join(", ")
- )
- }
- let missing_subtitle =
- missing_locales(&series.subtitle_locales, &self.archive.subtitle);
- if !missing_subtitle.is_empty() {
- warn!(
- "Series {} is not available with {} subtitles",
- series.title,
- missing_subtitle
- .into_iter()
- .map(|l| l.to_string())
- .collect::>()
- .join(", ")
- )
- }
- self.visited = Visited::Series
- }
-
- let mut seasons = series.seasons().await?;
- let mut remove_ids = vec![];
- for season in seasons.iter_mut() {
- if !self.url_filter.is_season_valid(season.season_number)
- || (!season
- .audio_locales
- .iter()
- .any(|l| self.archive.audio.contains(l))
- && !season
- .available_versions()
- .await?
- .iter()
- .any(|l| self.archive.audio.contains(l)))
- {
- remove_ids.push(season.id.clone());
- }
- }
-
- seasons.retain(|s| !remove_ids.contains(&s.id));
-
- let duplicated_seasons = get_duplicated_seasons(&seasons);
- if !duplicated_seasons.is_empty() {
- if self.interactive_input {
- check_for_duplicated_seasons(&mut seasons);
- } else {
- info!(
- "Found duplicated seasons: {}",
- duplicated_seasons
- .iter()
- .map(|d| d.to_string())
- .collect::>()
- .join(", ")
- )
- }
- }
-
- Ok(seasons)
- }
-
- async fn visit_season(&mut self, mut season: Season) -> Result> {
- if !self.url_filter.is_season_valid(season.season_number) {
- return Ok(vec![]);
- }
-
- let mut seasons = season.version(self.archive.audio.clone()).await?;
- if self
- .archive
- .audio
- .iter()
- .any(|l| season.audio_locales.contains(l))
- {
- seasons.insert(0, season.clone());
- }
-
- if !matches!(self.visited, Visited::Series) {
- let mut audio_locales: Vec = seasons
- .iter()
- .flat_map(|s| s.audio_locales.clone())
- .collect();
- real_dedup_vec(&mut audio_locales);
- let missing_audio = missing_locales(&audio_locales, &self.archive.audio);
- if !missing_audio.is_empty() {
- warn!(
- "Season {} is not available with {} audio",
- season.season_number,
- missing_audio
- .into_iter()
- .map(|l| l.to_string())
- .collect::>()
- .join(", ")
- )
- }
-
- let subtitle_locales: Vec = seasons
- .iter()
- .flat_map(|s| s.subtitle_locales.clone())
- .collect();
- let missing_subtitle = missing_locales(&subtitle_locales, &self.archive.subtitle);
- if !missing_subtitle.is_empty() {
- warn!(
- "Season {} is not available with {} subtitles",
- season.season_number,
- missing_subtitle
- .into_iter()
- .map(|l| l.to_string())
- .collect::>()
- .join(", ")
- )
- }
- self.visited = Visited::Season
- }
-
- let mut episodes = vec![];
- for season in seasons {
- self.season_sorting.push(season.id.clone());
- let season_locale = if season.audio_locales.len() < 2 {
- Some(
- season
- .audio_locales
- .first()
- .cloned()
- .unwrap_or(Locale::ja_JP),
- )
- } else {
- None
- };
- let mut eps = season.episodes().await?;
- let before_len = eps.len();
-
- for mut ep in eps.clone() {
- if let Some(l) = &season_locale {
- if &ep.audio_locale == l {
- continue;
- }
- eps.remove(eps.iter().position(|p| p.id == ep.id).unwrap());
- } else {
- let mut requested_locales = self.archive.audio.clone();
- if let Some(idx) = requested_locales.iter().position(|p| p == &ep.audio_locale)
- {
- requested_locales.remove(idx);
- } else {
- eps.remove(eps.iter().position(|p| p.id == ep.id).unwrap());
- }
- eps.extend(ep.version(self.archive.audio.clone()).await?);
- }
- }
- if eps.len() < before_len {
- if eps.is_empty() {
- if matches!(self.visited, Visited::Series) {
- warn!(
- "Season {} is not available with {} audio",
- season.season_number,
- season_locale.unwrap_or(Locale::ja_JP)
- )
- }
- } else {
- let last_episode = eps.last().unwrap();
- warn!(
- "Season {} is only available with {} audio until episode {} ({})",
- season.season_number,
- season_locale.unwrap_or(Locale::ja_JP),
- last_episode.sequence_number,
- last_episode.title
- )
- }
- }
- episodes.extend(eps)
- }
-
- if Format::has_relative_fmt(&self.archive.output) {
- for episode in episodes.iter() {
- self.season_episodes
- .entry(episode.season_id.clone())
- .or_default()
- .push(episode.clone())
- }
- }
-
- Ok(episodes)
- }
-
- async fn visit_episode(&mut self, mut episode: Episode) -> Result> {
- if !self
- .url_filter
- .is_episode_valid(episode.sequence_number, episode.season_number)
- {
- return Ok(None);
- }
-
- // skip the episode if it's a special
- if self.skip_special
- && (episode.sequence_number == 0.0 || episode.sequence_number.fract() != 0.0)
- {
- return Ok(None);
- }
-
- let mut episodes = vec![];
- if !matches!(self.visited, Visited::Series) && !matches!(self.visited, Visited::Season) {
- if self.archive.audio.contains(&episode.audio_locale) {
- episodes.push((episode.clone(), episode.subtitle_locales.clone()))
- }
- episodes.extend(
- episode
- .version(self.archive.audio.clone())
- .await?
- .into_iter()
- .map(|e| (e.clone(), e.subtitle_locales.clone())),
- );
- let audio_locales: Vec = episodes
- .iter()
- .map(|(e, _)| e.audio_locale.clone())
- .collect();
- let missing_audio = missing_locales(&audio_locales, &self.archive.audio);
- if !missing_audio.is_empty() {
- warn!(
- "Episode {} is not available with {} audio",
- episode.sequence_number,
- missing_audio
- .into_iter()
- .map(|l| l.to_string())
- .collect::>()
- .join(", ")
- )
- }
-
- let mut subtitle_locales: Vec =
- episodes.iter().flat_map(|(_, s)| s.clone()).collect();
- real_dedup_vec(&mut subtitle_locales);
- let missing_subtitles = missing_locales(&subtitle_locales, &self.archive.subtitle);
- if !missing_subtitles.is_empty()
- && !self
- .season_subtitles_missing
- .contains(&episode.season_number)
- {
- warn!(
- "Episode {} is not available with {} subtitles",
- episode.sequence_number,
- missing_subtitles
- .into_iter()
- .map(|l| l.to_string())
- .collect::>()
- .join(", ")
- );
- self.season_subtitles_missing.push(episode.season_number)
- }
- } else {
- episodes.push((episode.clone(), episode.subtitle_locales.clone()))
- }
-
- if self.seasons_with_premium.is_some() {
- let episode_len_before = episodes.len();
- episodes.retain(|(e, _)| !e.is_premium_only);
- if episode_len_before < episodes.len()
- && !self
- .seasons_with_premium
- .as_ref()
- .unwrap()
- .contains(&episode.season_number)
- {
- warn!(
- "Skipping premium episodes in season {}",
- episode.season_number
- );
- self.seasons_with_premium
- .as_mut()
- .unwrap()
- .push(episode.season_number)
- }
-
- if episodes.is_empty() {
- return Ok(None);
- }
- }
-
- let mut relative_episode_number = None;
- let mut relative_sequence_number = None;
- // get the relative episode number. only done if the output string has the pattern to include
- // the relative episode number as this requires some extra fetching
- if Format::has_relative_fmt(&self.archive.output) {
- let season_eps = match self.season_episodes.get(&episode.season_id) {
- Some(eps) => eps,
- None => {
- self.season_episodes.insert(
- episode.season_id.clone(),
- episode.season().await?.episodes().await?,
- );
- self.season_episodes.get(&episode.season_id).unwrap()
- }
- };
- let mut non_integer_sequence_number_count = 0;
- for (i, ep) in season_eps.iter().enumerate() {
- if ep.sequence_number.fract() != 0.0 || ep.sequence_number == 0.0 {
- non_integer_sequence_number_count += 1;
- }
- if ep.id == episode.id {
- relative_episode_number = Some(i + 1);
- relative_sequence_number = Some(
- (i + 1 - non_integer_sequence_number_count) as f32
- + fract(ep.sequence_number),
- );
- break;
- }
- }
- if relative_episode_number.is_none() || relative_sequence_number.is_none() {
- warn!(
- "Failed to get relative episode number for episode {} ({}) of {} season {}",
- episode.sequence_number,
- episode.title,
- episode.series_title,
- episode.season_number,
- )
- }
- }
-
- Ok(Some(
- episodes
- .into_iter()
- .map(|(e, s)| {
- SingleFormat::new_from_episode(
- e,
- s,
- relative_episode_number.map(|n| n as u32),
- relative_sequence_number,
- )
- })
- .collect(),
- ))
- }
-
- async fn visit_movie_listing(&mut self, movie_listing: MovieListing) -> Result> {
- Ok(movie_listing.movies().await?)
- }
-
- async fn visit_movie(&mut self, movie: Movie) -> Result> {
- Ok(Some(vec![SingleFormat::new_from_movie(movie, vec![])]))
- }
-
- async fn visit_music_video(&mut self, music_video: MusicVideo) -> Result > {
- Ok(Some(vec![SingleFormat::new_from_music_video(music_video)]))
- }
-
- async fn visit_concert(&mut self, concert: Concert) -> Result > {
- Ok(Some(vec![SingleFormat::new_from_concert(concert)]))
- }
-
- async fn finish(self, input: Vec) -> Result {
- let flatten_input: Self::T = input.into_iter().flatten().collect();
-
- let mut single_format_collection = SingleFormatCollection::new();
-
- let mut pre_sorted: BTreeMap = BTreeMap::new();
- for data in flatten_input {
- pre_sorted
- .entry(data.identifier.clone())
- .or_insert(vec![])
- .push(data)
- }
-
- let mut sorted: Vec<(String, Self::T)> = pre_sorted.into_iter().collect();
- sorted.sort_by(|(_, a), (_, b)| {
- self.season_sorting
- .iter()
- .position(|p| p == &a.first().unwrap().season_id)
- .unwrap()
- .cmp(
- &self
- .season_sorting
- .iter()
- .position(|p| p == &b.first().unwrap().season_id)
- .unwrap(),
- )
- });
-
- for (_, mut data) in sorted {
- data.sort_by(|a, b| {
- self.archive
- .audio
- .iter()
- .position(|p| p == &a.audio)
- .unwrap_or(usize::MAX)
- .cmp(
- &self
- .archive
- .audio
- .iter()
- .position(|p| p == &b.audio)
- .unwrap_or(usize::MAX),
- )
- });
- single_format_collection.add_single_formats(data)
- }
-
- Ok(single_format_collection)
- }
-}
-
-fn missing_locales<'a>(available: &[Locale], searched: &'a [Locale]) -> Vec<&'a Locale> {
- searched.iter().filter(|p| !available.contains(p)).collect()
-}
diff --git a/crunchy-cli-core/src/archive/mod.rs b/crunchy-cli-core/src/archive/mod.rs
index c3544a4..670d0c2 100644
--- a/crunchy-cli-core/src/archive/mod.rs
+++ b/crunchy-cli-core/src/archive/mod.rs
@@ -1,4 +1,3 @@
mod command;
-mod filter;
pub use command::Archive;
diff --git a/crunchy-cli-core/src/download/command.rs b/crunchy-cli-core/src/download/command.rs
index fcf069b..8e3794f 100644
--- a/crunchy-cli-core/src/download/command.rs
+++ b/crunchy-cli-core/src/download/command.rs
@@ -1,8 +1,7 @@
-use crate::download::filter::DownloadFilter;
use crate::utils::context::Context;
use crate::utils::download::{DownloadBuilder, DownloadFormat, DownloadFormatMetadata};
use crate::utils::ffmpeg::{FFmpegPreset, SOFTSUB_CONTAINERS};
-use crate::utils::filter::Filter;
+use crate::utils::filter::{Filter, FilterMediaScope};
use crate::utils::format::{Format, SingleFormat};
use crate::utils::locale::{resolve_locales, LanguageTagging};
use crate::utils::log::progress;
@@ -14,7 +13,7 @@ use anyhow::bail;
use anyhow::Result;
use crunchyroll_rs::media::Resolution;
use crunchyroll_rs::Locale;
-use log::{debug, warn};
+use log::{debug, error, warn};
use std::collections::HashMap;
use std::path::Path;
@@ -250,9 +249,53 @@ impl Execute for Download {
for (i, (media_collection, url_filter)) in parsed_urls.into_iter().enumerate() {
let progress_handler = progress!("Fetching series details");
- let single_format_collection = DownloadFilter::new(
+ let single_format_collection = Filter::new(
url_filter,
- self.clone(),
+ vec![self.audio.clone()],
+ self.subtitle.as_ref().map_or(vec![], |s| vec![s.clone()]),
+ |scope, locales| {
+ match scope {
+ FilterMediaScope::Series(series) => bail!("Series {} is not available with {} audio", series.title, locales[0]),
+ FilterMediaScope::Season(season) => {
+ error!("Season {} is not available with {} audio", season.season_number, locales[0]);
+ Ok(false)
+ }
+ FilterMediaScope::Episode(episodes) => {
+ if episodes.len() == 1 {
+ warn!("Episode {} of season {} is not available with {} audio", episodes[0].sequence_number, episodes[0].season_title, locales[0])
+ } else if episodes.len() == 2 {
+ warn!("Season {} is only available with {} audio from episode {} to {}", episodes[0].season_number, locales[0], episodes[0].sequence_number, episodes[1].sequence_number)
+ } else {
+ unimplemented!()
+ }
+ Ok(false)
+ }
+ }
+ },
+ |scope, locales| {
+ match scope {
+ FilterMediaScope::Series(series) => bail!("Series {} is not available with {} subtitles", series.title, locales[0]),
+ FilterMediaScope::Season(season) => {
+ warn!("Season {} is not available with {} subtitles", season.season_number, locales[0]);
+ Ok(false)
+ },
+ FilterMediaScope::Episode(episodes) => {
+ if episodes.len() == 1 {
+ warn!("Episode {} of season {} is not available with {} subtitles", episodes[0].sequence_number, episodes[0].season_title, locales[0])
+ } else if episodes.len() == 2 {
+ warn!("Season {} is only available with {} subtitles from episode {} to {}", episodes[0].season_number, locales[0], episodes[0].sequence_number, episodes[1].sequence_number)
+ } else {
+ unimplemented!()
+ }
+ Ok(false)
+ }
+ }
+ },
+ |season| {
+ warn!("Skipping premium episodes in season {season}");
+ Ok(())
+ },
+ Format::has_relative_fmt(&self.output),
!self.yes,
self.skip_specials,
ctx.crunchy.premium().await,
diff --git a/crunchy-cli-core/src/download/filter.rs b/crunchy-cli-core/src/download/filter.rs
deleted file mode 100644
index 1c62920..0000000
--- a/crunchy-cli-core/src/download/filter.rs
+++ /dev/null
@@ -1,307 +0,0 @@
-use crate::download::Download;
-use crate::utils::filter::Filter;
-use crate::utils::format::{Format, SingleFormat, SingleFormatCollection};
-use crate::utils::interactive_select::{check_for_duplicated_seasons, get_duplicated_seasons};
-use crate::utils::parse::{fract, UrlFilter};
-use anyhow::{bail, Result};
-use crunchyroll_rs::{Concert, Episode, Movie, MovieListing, MusicVideo, Season, Series};
-use log::{error, info, warn};
-use std::collections::HashMap;
-use std::ops::Not;
-
-pub(crate) struct DownloadFilter {
- url_filter: UrlFilter,
- download: Download,
- interactive_input: bool,
- skip_special: bool,
- season_episodes: HashMap>,
- season_subtitles_missing: Vec,
- seasons_with_premium: Option>,
- season_visited: bool,
-}
-
-impl DownloadFilter {
- pub(crate) fn new(
- url_filter: UrlFilter,
- download: Download,
- interactive_input: bool,
- skip_special: bool,
- is_premium: bool,
- ) -> Self {
- Self {
- url_filter,
- download,
- interactive_input,
- skip_special,
- season_episodes: HashMap::new(),
- season_subtitles_missing: vec![],
- seasons_with_premium: is_premium.not().then_some(vec![]),
- season_visited: false,
- }
- }
-}
-
-impl Filter for DownloadFilter {
- type T = SingleFormat;
- type Output = SingleFormatCollection;
-
- async fn visit_series(&mut self, series: Series) -> Result> {
- // `series.audio_locales` isn't always populated b/c of crunchyrolls api. so check if the
- // audio is matching only if the field is populated
- if !series.audio_locales.is_empty() && !series.audio_locales.contains(&self.download.audio)
- {
- error!(
- "Series {} is not available with {} audio",
- series.title, self.download.audio
- );
- return Ok(vec![]);
- }
-
- let mut seasons = vec![];
- for mut season in series.seasons().await? {
- if !self.url_filter.is_season_valid(season.season_number) {
- continue;
- }
-
- if !season
- .audio_locales
- .iter()
- .any(|l| l == &self.download.audio)
- {
- if season
- .available_versions()
- .await?
- .iter()
- .any(|l| l == &self.download.audio)
- {
- season = season
- .version(vec![self.download.audio.clone()])
- .await?
- .remove(0)
- } else {
- error!(
- "Season {} - '{}' is not available with {} audio",
- season.season_number,
- season.title,
- self.download.audio.clone(),
- );
- continue;
- }
- }
-
- seasons.push(season)
- }
-
- let duplicated_seasons = get_duplicated_seasons(&seasons);
- if !duplicated_seasons.is_empty() {
- if self.interactive_input {
- check_for_duplicated_seasons(&mut seasons);
- } else {
- info!(
- "Found duplicated seasons: {}",
- duplicated_seasons
- .iter()
- .map(|d| d.to_string())
- .collect::>()
- .join(", ")
- )
- }
- }
-
- Ok(seasons)
- }
-
- async fn visit_season(&mut self, season: Season) -> Result> {
- self.season_visited = true;
-
- let mut episodes = season.episodes().await?;
-
- if Format::has_relative_fmt(&self.download.output) {
- for episode in episodes.iter() {
- self.season_episodes
- .entry(episode.season_number)
- .or_default()
- .push(episode.clone())
- }
- }
-
- episodes.retain(|e| {
- self.url_filter
- .is_episode_valid(e.sequence_number, season.season_number)
- });
-
- Ok(episodes)
- }
-
- async fn visit_episode(&mut self, mut episode: Episode) -> Result> {
- if !self
- .url_filter
- .is_episode_valid(episode.sequence_number, episode.season_number)
- {
- return Ok(None);
- }
-
- // skip the episode if it's a special
- if self.skip_special
- && (episode.sequence_number == 0.0 || episode.sequence_number.fract() != 0.0)
- {
- return Ok(None);
- }
-
- // check if the audio locale is correct.
- // should only be incorrect if the console input was a episode url. otherwise
- // `DownloadFilter::visit_season` returns the correct episodes with matching audio
- if episode.audio_locale != self.download.audio {
- // check if any other version (same episode, other language) of this episode is available
- // with the requested audio. if not, return an error
- if !episode
- .available_versions()
- .await?
- .contains(&self.download.audio)
- {
- let error_message = format!(
- "Episode {} ({}) of {} season {} is not available with {} audio",
- episode.sequence_number,
- episode.title,
- episode.series_title,
- episode.season_number,
- self.download.audio
- );
- // sometimes a series randomly has episode in an other language. if this is the case,
- // only error if the input url was a episode url
- if self.season_visited {
- warn!("{}", error_message);
- return Ok(None);
- } else {
- bail!("{}", error_message)
- }
- }
- // overwrite the current episode with the other version episode
- episode = episode
- .version(vec![self.download.audio.clone()])
- .await?
- .remove(0)
- }
-
- // check if the subtitles are supported
- if let Some(subtitle_locale) = &self.download.subtitle {
- if !episode.subtitle_locales.contains(subtitle_locale) {
- // if the episode doesn't have the requested subtitles, print a error. to print this
- // error only once per season, it's checked if an error got printed before by looking
- // up if the season id is present in `self.season_subtitles_missing`. if not, print
- // the error and add the season id to `self.season_subtitles_missing`. if it is
- // present, skip the error printing
- if !self
- .season_subtitles_missing
- .contains(&episode.season_number)
- {
- self.season_subtitles_missing.push(episode.season_number);
- error!(
- "{} season {} is not available with {} subtitles",
- episode.series_title, episode.season_number, subtitle_locale
- );
- }
- return Ok(None);
- }
- }
-
- if self.seasons_with_premium.is_some() && episode.is_premium_only {
- if !self
- .seasons_with_premium
- .as_ref()
- .unwrap()
- .contains(&episode.season_number)
- {
- warn!(
- "Skipping premium episodes in season {}",
- episode.season_number
- );
- self.seasons_with_premium
- .as_mut()
- .unwrap()
- .push(episode.season_number)
- }
-
- return Ok(None);
- }
-
- let mut relative_episode_number = None;
- let mut relative_sequence_number = None;
- // get the relative episode number. only done if the output string has the pattern to include
- // the relative episode number as this requires some extra fetching
- if Format::has_relative_fmt(&self.download.output) {
- let season_eps = match self.season_episodes.get(&episode.season_number) {
- Some(eps) => eps,
- None => {
- self.season_episodes.insert(
- episode.season_number,
- episode.season().await?.episodes().await?,
- );
- self.season_episodes.get(&episode.season_number).unwrap()
- }
- };
- let mut non_integer_sequence_number_count = 0;
- for (i, ep) in season_eps.iter().enumerate() {
- if ep.sequence_number.fract() != 0.0 || ep.sequence_number == 0.0 {
- non_integer_sequence_number_count += 1;
- }
- if ep.id == episode.id {
- relative_episode_number = Some(i + 1);
- relative_sequence_number = Some(
- (i + 1 - non_integer_sequence_number_count) as f32
- + fract(ep.sequence_number),
- );
- break;
- }
- }
- if relative_episode_number.is_none() || relative_sequence_number.is_none() {
- warn!(
- "Failed to get relative episode number for episode {} ({}) of {} season {}",
- episode.sequence_number,
- episode.title,
- episode.series_title,
- episode.season_number,
- )
- }
- }
-
- Ok(Some(SingleFormat::new_from_episode(
- episode.clone(),
- self.download.subtitle.clone().map_or(vec![], |s| {
- if episode.subtitle_locales.contains(&s) {
- vec![s]
- } else {
- vec![]
- }
- }),
- relative_episode_number.map(|n| n as u32),
- relative_sequence_number,
- )))
- }
-
- async fn visit_movie_listing(&mut self, movie_listing: MovieListing) -> Result> {
- Ok(movie_listing.movies().await?)
- }
-
- async fn visit_movie(&mut self, movie: Movie) -> Result> {
- Ok(Some(SingleFormat::new_from_movie(movie, vec![])))
- }
-
- async fn visit_music_video(&mut self, music_video: MusicVideo) -> Result > {
- Ok(Some(SingleFormat::new_from_music_video(music_video)))
- }
-
- async fn visit_concert(&mut self, concert: Concert) -> Result > {
- Ok(Some(SingleFormat::new_from_concert(concert)))
- }
-
- async fn finish(self, input: Vec) -> Result {
- let mut single_format_collection = SingleFormatCollection::new();
-
- for data in input {
- single_format_collection.add_single_formats(vec![data])
- }
-
- Ok(single_format_collection)
- }
-}
diff --git a/crunchy-cli-core/src/download/mod.rs b/crunchy-cli-core/src/download/mod.rs
index 696872e..47ca304 100644
--- a/crunchy-cli-core/src/download/mod.rs
+++ b/crunchy-cli-core/src/download/mod.rs
@@ -1,4 +1,3 @@
mod command;
-mod filter;
pub use command::Download;
diff --git a/crunchy-cli-core/src/search/format.rs b/crunchy-cli-core/src/search/format.rs
index 10f4624..cf3c5bc 100644
--- a/crunchy-cli-core/src/search/format.rs
+++ b/crunchy-cli-core/src/search/format.rs
@@ -241,14 +241,6 @@ macro_rules! must_match_if_true {
};
}
-macro_rules! self_and_versions {
- ($var:expr => $audio:expr) => {{
- let mut items = vec![$var.clone()];
- items.extend($var.clone().version($audio).await?);
- items
- }};
-}
-
pub struct Format {
pattern: Vec<(Range, Scope, String)>,
pattern_count: HashMap,
@@ -421,7 +413,15 @@ impl Format {
};
let mut seasons = vec![];
for season in tmp_seasons {
- seasons.extend(self_and_versions!(season => self.filter_options.audio.clone()))
+ seasons.push(season.clone());
+ for version in season.versions {
+ if season.id == version.id {
+ continue;
+ }
+ if self.filter_options.audio.contains(&version.audio_locale) {
+ seasons.push(version.season().await?)
+ }
+ }
}
tree.extend(
self.filter_options
@@ -435,7 +435,15 @@ impl Format {
if !episode_empty || !stream_empty {
match &media_collection {
MediaCollection::Episode(episode) => {
- let episodes = self_and_versions!(episode => self.filter_options.audio.clone());
+ let mut episodes = vec![episode.clone()];
+ for version in &episode.versions {
+ if episode.id == version.id {
+ continue;
+ }
+ if self.filter_options.audio.contains(&version.audio_locale) {
+ episodes.push(version.episode().await?)
+ }
+ }
tree.push((
Season::default(),
episodes
diff --git a/crunchy-cli-core/src/utils/filter.rs b/crunchy-cli-core/src/utils/filter.rs
index 63fac9d..b95596e 100644
--- a/crunchy-cli-core/src/utils/filter.rs
+++ b/crunchy-cli-core/src/utils/filter.rs
@@ -1,24 +1,397 @@
+use crate::utils::format::{SingleFormat, SingleFormatCollection};
+use crate::utils::interactive_select::{check_for_duplicated_seasons, get_duplicated_seasons};
+use crate::utils::parse::{fract, UrlFilter};
use anyhow::Result;
use crunchyroll_rs::{
- Concert, Episode, MediaCollection, Movie, MovieListing, MusicVideo, Season, Series,
+ Concert, Episode, Locale, MediaCollection, Movie, MovieListing, MusicVideo, Season, Series,
};
+use log::{info, warn};
+use std::collections::{BTreeMap, HashMap};
+use std::ops::Not;
-pub trait Filter {
- type T: Send + Sized;
- type Output: Send + Sized;
+pub(crate) enum FilterMediaScope<'a> {
+ Series(&'a Series),
+ Season(&'a Season),
+ /// Always contains 1 or 2 episodes.
+ /// - 1: The episode's audio is completely missing
+ /// - 2: The requested audio is only available from first entry to last entry
+ Episode(Vec<&'a Episode>),
+}
- async fn visit_series(&mut self, series: Series) -> Result>;
- async fn visit_season(&mut self, season: Season) -> Result>;
- async fn visit_episode(&mut self, episode: Episode) -> Result>;
- async fn visit_movie_listing(&mut self, movie_listing: MovieListing) -> Result>;
- async fn visit_movie(&mut self, movie: Movie) -> Result>;
- async fn visit_music_video(&mut self, music_video: MusicVideo) -> Result >;
- async fn visit_concert(&mut self, concert: Concert) -> Result >;
+pub(crate) struct Filter {
+ url_filter: UrlFilter,
- async fn visit(mut self, media_collection: MediaCollection) -> Result
- where
- Self: Send + Sized,
- {
+ skip_specials: bool,
+ interactive_input: bool,
+
+ relative_episode_number: bool,
+
+ audio_locales: Vec,
+ subtitle_locales: Vec,
+
+ audios_missing: fn(FilterMediaScope, Vec<&Locale>) -> Result,
+ subtitles_missing: fn(FilterMediaScope, Vec<&Locale>) -> Result,
+ no_premium: fn(u32) -> Result<()>,
+
+ is_premium: bool,
+
+ series_visited: bool,
+ season_episodes: HashMap>,
+ season_with_premium: Option>,
+ season_sorting: Vec,
+}
+
+impl Filter {
+ #[allow(clippy::too_many_arguments)]
+ pub(crate) fn new(
+ url_filter: UrlFilter,
+ audio_locales: Vec,
+ subtitle_locales: Vec,
+ audios_missing: fn(FilterMediaScope, Vec<&Locale>) -> Result,
+ subtitles_missing: fn(FilterMediaScope, Vec<&Locale>) -> Result,
+ no_premium: fn(u32) -> Result<()>,
+ relative_episode_number: bool,
+ interactive_input: bool,
+ skip_specials: bool,
+ is_premium: bool,
+ ) -> Self {
+ Self {
+ url_filter,
+ audio_locales,
+ subtitle_locales,
+ relative_episode_number,
+ interactive_input,
+ audios_missing,
+ subtitles_missing,
+ no_premium,
+ is_premium,
+ series_visited: false,
+ season_episodes: HashMap::new(),
+ skip_specials,
+ season_with_premium: is_premium.not().then_some(vec![]),
+ season_sorting: vec![],
+ }
+ }
+
+ async fn visit_series(&mut self, series: Series) -> Result> {
+ // the audio locales field isn't always populated
+ if !series.audio_locales.is_empty() {
+ let missing_audios = missing_locales(&series.audio_locales, &self.audio_locales);
+ if !missing_audios.is_empty()
+ && !(self.audios_missing)(FilterMediaScope::Series(&series), missing_audios)?
+ {
+ return Ok(vec![]);
+ }
+ let missing_subtitles =
+ missing_locales(&series.subtitle_locales, &self.subtitle_locales);
+ if !missing_subtitles.is_empty()
+ && !(self.subtitles_missing)(FilterMediaScope::Series(&series), missing_subtitles)?
+ {
+ return Ok(vec![]);
+ }
+ }
+
+ let mut seasons = vec![];
+ for season in series.seasons().await? {
+ if !self.url_filter.is_season_valid(season.season_number) {
+ continue;
+ }
+ let missing_audios = missing_locales(
+ &season
+ .versions
+ .iter()
+ .map(|l| l.audio_locale.clone())
+ .collect::>(),
+ &self.audio_locales,
+ );
+ if !missing_audios.is_empty()
+ && !(self.audios_missing)(FilterMediaScope::Season(&season), missing_audios)?
+ {
+ return Ok(vec![]);
+ }
+ seasons.push(season)
+ }
+
+ let duplicated_seasons = get_duplicated_seasons(&seasons);
+ if !duplicated_seasons.is_empty() {
+ if self.interactive_input {
+ check_for_duplicated_seasons(&mut seasons)
+ } else {
+ info!(
+ "Found duplicated seasons: {}",
+ duplicated_seasons
+ .iter()
+ .map(|d| d.to_string())
+ .collect::>()
+ .join(", ")
+ )
+ }
+ }
+
+ self.series_visited = true;
+
+ Ok(seasons)
+ }
+
+ async fn visit_season(&mut self, season: Season) -> Result> {
+ if !self.url_filter.is_season_valid(season.season_number) {
+ return Ok(vec![]);
+ }
+
+ let mut seasons = vec![];
+ if self
+ .audio_locales
+ .iter()
+ .any(|l| season.audio_locales.contains(l))
+ {
+ seasons.push(season.clone())
+ }
+ for version in season.versions {
+ if season.id == version.id {
+ continue;
+ }
+ if self.audio_locales.contains(&version.audio_locale) {
+ seasons.push(version.season().await?)
+ }
+ }
+
+ let mut episodes = vec![];
+ for season in seasons {
+ self.season_sorting.push(season.id.clone());
+ let mut eps = season.episodes().await?;
+
+ // removes any episode that does not have the audio locale of the season. yes, this is
+ // the case sometimes
+ if season.audio_locales.len() < 2 {
+ let season_locale = season
+ .audio_locales
+ .first()
+ .cloned()
+ .unwrap_or(Locale::ja_JP);
+ eps.retain(|e| e.audio_locale == season_locale)
+ }
+
+ if eps.len() < season.number_of_episodes as usize
+ && !(self.audios_missing)(
+ FilterMediaScope::Episode(vec![eps.first().unwrap(), eps.last().unwrap()]),
+ vec![&eps.first().unwrap().audio_locale],
+ )?
+ {
+ return Ok(vec![]);
+ }
+
+ episodes.extend(eps)
+ }
+
+ if self.relative_episode_number {
+ for episode in &episodes {
+ self.season_episodes
+ .entry(episode.season_id.clone())
+ .or_default()
+ .push(episode.clone())
+ }
+ }
+
+ Ok(episodes)
+ }
+
+ async fn visit_episode(&mut self, episode: Episode) -> Result> {
+ if !self
+ .url_filter
+ .is_episode_valid(episode.sequence_number, episode.season_number)
+ {
+ return Ok(vec![]);
+ }
+
+ // skip the episode if it's a special
+ if self.skip_specials
+ && (episode.sequence_number == 0.0 || episode.sequence_number.fract() != 0.0)
+ {
+ return Ok(vec![]);
+ }
+
+ let mut episodes = vec![];
+ if !self.series_visited {
+ if self.audio_locales.contains(&episode.audio_locale) {
+ episodes.push(episode.clone())
+ }
+ for version in &episode.versions {
+ // `episode` is also a version of itself. the if block above already adds the
+ // episode if it matches the requested audio, so it doesn't need to be requested
+ // here again
+ if version.id == episode.id {
+ continue;
+ }
+ if self.audio_locales.contains(&version.audio_locale) {
+ episodes.push(version.episode().await?)
+ }
+ }
+
+ let audio_locales: Vec =
+ episodes.iter().map(|e| e.audio_locale.clone()).collect();
+ let missing_audios = missing_locales(&audio_locales, &self.audio_locales);
+ if !missing_audios.is_empty()
+ && !(self.audios_missing)(
+ FilterMediaScope::Episode(vec![&episode]),
+ missing_audios,
+ )?
+ {
+ return Ok(vec![]);
+ }
+
+ let mut subtitle_locales: Vec = episodes
+ .iter()
+ .flat_map(|e| e.subtitle_locales.clone())
+ .collect();
+ subtitle_locales.sort();
+ subtitle_locales.dedup();
+ let missing_subtitles = missing_locales(&subtitle_locales, &self.subtitle_locales);
+ if !missing_subtitles.is_empty()
+ && !(self.subtitles_missing)(
+ FilterMediaScope::Episode(vec![&episode]),
+ missing_subtitles,
+ )?
+ {
+ return Ok(vec![]);
+ }
+ } else {
+ episodes.push(episode.clone())
+ }
+
+ if let Some(seasons_with_premium) = &mut self.season_with_premium {
+ let episodes_len_before = episodes.len();
+ episodes.retain(|e| !e.is_premium_only && !self.is_premium);
+ if episodes_len_before < episodes.len()
+ && !seasons_with_premium.contains(&episode.season_number)
+ {
+ (self.no_premium)(episode.season_number)?;
+ seasons_with_premium.push(episode.season_number)
+ }
+
+ if episodes.is_empty() {
+ return Ok(vec![]);
+ }
+ }
+
+ let mut relative_episode_number = None;
+ let mut relative_sequence_number = None;
+ if self.relative_episode_number {
+ let season_eps = match self.season_episodes.get(&episode.season_id) {
+ Some(eps) => eps,
+ None => {
+ self.season_episodes.insert(
+ episode.season_id.clone(),
+ episode.season().await?.episodes().await?,
+ );
+ self.season_episodes.get(&episode.season_id).unwrap()
+ }
+ };
+ let mut non_integer_sequence_number_count = 0;
+ for (i, ep) in season_eps.iter().enumerate() {
+ if ep.sequence_number != 0.0 || ep.sequence_number.fract() == 0.0 {
+ non_integer_sequence_number_count += 1
+ }
+ if ep.id == episode.id {
+ relative_episode_number = Some(i + 1);
+ relative_sequence_number = Some(
+ (i + 1 - non_integer_sequence_number_count) as f32
+ + fract(ep.sequence_number),
+ );
+ break;
+ }
+ }
+ if relative_episode_number.is_none() || relative_sequence_number.is_none() {
+ warn!(
+ "Failed to get relative episode number for episode {} ({}) of {} season {}",
+ episode.sequence_number,
+ episode.title,
+ episode.series_title,
+ episode.season_number,
+ )
+ }
+ }
+
+ Ok(episodes
+ .into_iter()
+ .map(|e| {
+ SingleFormat::new_from_episode(
+ e.clone(),
+ e.subtitle_locales,
+ relative_episode_number.map(|n| n as u32),
+ relative_sequence_number,
+ )
+ })
+ .collect())
+ }
+
+ async fn visit_movie_listing(&mut self, movie_listing: MovieListing) -> Result> {
+ Ok(movie_listing.movies().await?)
+ }
+
+ async fn visit_movie(&mut self, movie: Movie) -> Result> {
+ Ok(vec![SingleFormat::new_from_movie(movie, vec![])])
+ }
+
+ async fn visit_music_video(&mut self, music_video: MusicVideo) -> Result> {
+ Ok(vec![SingleFormat::new_from_music_video(music_video)])
+ }
+
+ async fn visit_concert(&mut self, concert: Concert) -> Result> {
+ Ok(vec![SingleFormat::new_from_concert(concert)])
+ }
+
+ async fn finish(self, input: Vec>) -> Result {
+ let flatten_input: Vec = input.into_iter().flatten().collect();
+
+ let mut single_format_collection = SingleFormatCollection::new();
+
+ let mut pre_sorted: BTreeMap> = BTreeMap::new();
+ for data in flatten_input {
+ pre_sorted
+ .entry(data.identifier.clone())
+ .or_default()
+ .push(data)
+ }
+
+ let mut sorted: Vec<(String, Vec)> = pre_sorted.into_iter().collect();
+ sorted.sort_by(|(_, a), (_, b)| {
+ self.season_sorting
+ .iter()
+ .position(|p| p == &a.first().unwrap().season_id)
+ .unwrap()
+ .cmp(
+ &self
+ .season_sorting
+ .iter()
+ .position(|p| p == &b.first().unwrap().season_id)
+ .unwrap(),
+ )
+ });
+
+ for (_, mut data) in sorted {
+ data.sort_by(|a, b| {
+ self.audio_locales
+ .iter()
+ .position(|p| p == &a.audio)
+ .unwrap_or(usize::MAX)
+ .cmp(
+ &self
+ .audio_locales
+ .iter()
+ .position(|p| p == &b.audio)
+ .unwrap_or(usize::MAX),
+ )
+ });
+ single_format_collection.add_single_formats(data)
+ }
+
+ Ok(single_format_collection)
+ }
+
+ pub(crate) async fn visit(
+ mut self,
+ media_collection: MediaCollection,
+ ) -> Result {
let mut items = vec![media_collection];
let mut result = vec![];
@@ -42,9 +415,7 @@ pub trait Filter {
.collect::>(),
),
MediaCollection::Episode(episode) => {
- if let Some(t) = self.visit_episode(episode).await? {
- result.push(t)
- }
+ result.push(self.visit_episode(episode).await?)
}
MediaCollection::MovieListing(movie_listing) => new_items.extend(
self.visit_movie_listing(movie_listing)
@@ -53,20 +424,12 @@ pub trait Filter {
.map(|m| m.into())
.collect::>(),
),
- MediaCollection::Movie(movie) => {
- if let Some(t) = self.visit_movie(movie).await? {
- result.push(t)
- }
- }
+ MediaCollection::Movie(movie) => result.push(self.visit_movie(movie).await?),
MediaCollection::MusicVideo(music_video) => {
- if let Some(t) = self.visit_music_video(music_video).await? {
- result.push(t)
- }
+ result.push(self.visit_music_video(music_video).await?)
}
MediaCollection::Concert(concert) => {
- if let Some(t) = self.visit_concert(concert).await? {
- result.push(t)
- }
+ result.push(self.visit_concert(concert).await?)
}
}
}
@@ -76,8 +439,10 @@ pub trait Filter {
self.finish(result).await
}
+}
- async fn finish(self, input: Vec) -> Result;
+fn missing_locales<'a>(available: &[Locale], searched: &'a [Locale]) -> Vec<&'a Locale> {
+ searched.iter().filter(|p| !available.contains(p)).collect()
}
/// Remove all duplicates from a [`Vec`].
diff --git a/crunchy-cli-core/src/utils/format.rs b/crunchy-cli-core/src/utils/format.rs
index f0a002c..33ce261 100644
--- a/crunchy-cli-core/src/utils/format.rs
+++ b/crunchy-cli-core/src/utils/format.rs
@@ -12,6 +12,7 @@ use std::collections::BTreeMap;
use std::env;
use std::path::{Path, PathBuf};
+#[allow(dead_code)]
#[derive(Clone)]
pub struct SingleFormat {
pub identifier: String,
@@ -347,6 +348,7 @@ impl Iterator for SingleFormatCollectionIterator {
}
}
+#[allow(dead_code)]
#[derive(Clone)]
pub struct Format {
pub title: String,
From 8047680799d88521232986e83091b06a5253022b Mon Sep 17 00:00:00 2001
From: bytedream
Date: Wed, 19 Jun 2024 23:18:35 +0200
Subject: [PATCH 78/82] Add drm check
---
crunchy-cli-core/src/utils/video.rs | 5 +++++
1 file changed, 5 insertions(+)
diff --git a/crunchy-cli-core/src/utils/video.rs b/crunchy-cli-core/src/utils/video.rs
index 8b25791..a15296c 100644
--- a/crunchy-cli-core/src/utils/video.rs
+++ b/crunchy-cli-core/src/utils/video.rs
@@ -27,6 +27,11 @@ pub async fn stream_data_from_stream(
}
}
.unwrap();
+
+ if videos.iter().any(|v| v.drm.is_some()) || audios.iter().any(|v| v.drm.is_some()) {
+ bail!("Stream is DRM protected")
+ }
+
videos.sort_by(|a, b| a.bandwidth.cmp(&b.bandwidth).reverse());
audios.sort_by(|a, b| a.bandwidth.cmp(&b.bandwidth).reverse());
From 509683d23a5689dc958a79440227585c9d383c30 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Wed, 19 Jun 2024 23:38:57 +0200
Subject: [PATCH 79/82] Update dependencies and version
---
Cargo.lock | 12 ++++++------
Cargo.toml | 8 ++++----
crunchy-cli-core/Cargo.toml | 6 +++---
3 files changed, 13 insertions(+), 13 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index 7fdb3d9..d01a80c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -349,7 +349,7 @@ checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f"
[[package]]
name = "crunchy-cli"
-version = "3.6.6"
+version = "3.6.7"
dependencies = [
"chrono",
"clap",
@@ -362,7 +362,7 @@ dependencies = [
[[package]]
name = "crunchy-cli-core"
-version = "3.6.6"
+version = "3.6.7"
dependencies = [
"anyhow",
"async-speed-limit",
@@ -1125,8 +1125,8 @@ dependencies = [
[[package]]
name = "native-tls"
-version = "0.2.11"
-source = "git+https://github.com/crunchy-labs/rust-not-so-native-tls.git?rev=b7969a8#b7969a88210096e0570e29d42fb13533baf62aa6"
+version = "0.2.12"
+source = "git+https://github.com/crunchy-labs/rust-not-so-native-tls.git?rev=c7ac566#c7ac566559d441bbc3e5e5bd04fb7162c38d88b0"
dependencies = [
"libc",
"log",
@@ -1519,9 +1519,9 @@ checksum = "b833d8d034ea094b1ea68aa6d5c740e0d04bad9d16568d08ba6f76823a114316"
[[package]]
name = "rsubs-lib"
-version = "0.3.1"
+version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d01f7609f0b1bc4fe24b352e8d1792c7d71cc43aea797e14b87974cd009ab402"
+checksum = "8c9f50e3fbcbf1f0bd109954e2dd813d1715c7b4a92a7bf159a85dea49e9d863"
dependencies = [
"regex",
"serde",
diff --git a/Cargo.toml b/Cargo.toml
index f263e59..c1e28bb 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli"
authors = ["Crunchy Labs Maintainers"]
-version = "3.6.6"
+version = "3.6.7"
edition = "2021"
license = "MIT"
@@ -14,9 +14,9 @@ openssl-tls = ["dep:native-tls-crate", "native-tls-crate/openssl", "crunchy-cli-
openssl-tls-static = ["dep:native-tls-crate", "native-tls-crate/openssl", "crunchy-cli-core/openssl-tls-static"]
[dependencies]
-tokio = { version = "1.37", features = ["macros", "rt-multi-thread", "time"], default-features = false }
+tokio = { version = "1.38", features = ["macros", "rt-multi-thread", "time"], default-features = false }
-native-tls-crate = { package = "native-tls", version = "0.2.11", optional = true }
+native-tls-crate = { package = "native-tls", version = "0.2.12", optional = true }
crunchy-cli-core = { path = "./crunchy-cli-core" }
@@ -34,7 +34,7 @@ members = ["crunchy-cli-core"]
[patch.crates-io]
# fork of the `native-tls` crate which can use openssl as backend on every platform. this is done as `reqwest` only
# supports `rustls` and `native-tls` as tls backend
-native-tls = { git = "https://github.com/crunchy-labs/rust-not-so-native-tls.git", rev = "b7969a8" }
+native-tls = { git = "https://github.com/crunchy-labs/rust-not-so-native-tls.git", rev = "c7ac566" }
[profile.release]
strip = true
diff --git a/crunchy-cli-core/Cargo.toml b/crunchy-cli-core/Cargo.toml
index 5c7b901..399053f 100644
--- a/crunchy-cli-core/Cargo.toml
+++ b/crunchy-cli-core/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "crunchy-cli-core"
authors = ["Crunchy Labs Maintainers"]
-version = "3.6.6"
+version = "3.6.7"
edition = "2021"
license = "MIT"
@@ -30,7 +30,7 @@ log = { version = "0.4", features = ["std"] }
num_cpus = "1.16"
regex = "1.10"
reqwest = { version = "0.12", features = ["socks", "stream"] }
-rsubs-lib = "~0.3.1"
+rsubs-lib = "~0.3.2"
rusty-chromaprint = "0.2"
serde = "1.0"
serde_json = "1.0"
@@ -39,7 +39,7 @@ shlex = "1.3"
sys-locale = "0.3"
tempfile = "3.10"
time = "0.3"
-tokio = { version = "1.37", features = ["io-util", "macros", "net", "rt-multi-thread", "time"] }
+tokio = { version = "1.38", features = ["io-util", "macros", "net", "rt-multi-thread", "time"] }
tokio-util = "0.7"
tower-service = "0.3"
rustls-native-certs = { version = "0.7", optional = true }
From 756022b955633c73c2920091b3f02d37ab791004 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Thu, 20 Jun 2024 00:12:06 +0200
Subject: [PATCH 80/82] Fix panic when in anonymously
---
crunchy-cli-core/src/utils/filter.rs | 24 +++++++++++++++++-------
1 file changed, 17 insertions(+), 7 deletions(-)
diff --git a/crunchy-cli-core/src/utils/filter.rs b/crunchy-cli-core/src/utils/filter.rs
index b95596e..3388741 100644
--- a/crunchy-cli-core/src/utils/filter.rs
+++ b/crunchy-cli-core/src/utils/filter.rs
@@ -171,13 +171,23 @@ impl Filter {
eps.retain(|e| e.audio_locale == season_locale)
}
- if eps.len() < season.number_of_episodes as usize
- && !(self.audios_missing)(
- FilterMediaScope::Episode(vec![eps.first().unwrap(), eps.last().unwrap()]),
- vec![&eps.first().unwrap().audio_locale],
- )?
- {
- return Ok(vec![]);
+ #[allow(clippy::if_same_then_else)]
+ if eps.len() < season.number_of_episodes as usize {
+ if eps.is_empty()
+ && !(self.audios_missing)(
+ FilterMediaScope::Season(&season),
+ season.audio_locales.iter().collect(),
+ )?
+ {
+ return Ok(vec![]);
+ } else if !eps.is_empty()
+ && !(self.audios_missing)(
+ FilterMediaScope::Episode(vec![eps.first().unwrap(), eps.last().unwrap()]),
+ vec![&eps.first().unwrap().audio_locale],
+ )?
+ {
+ return Ok(vec![]);
+ }
}
episodes.extend(eps)
From 2cf9125de3f42052d3fb58f5c3f7325876837c75 Mon Sep 17 00:00:00 2001
From: bytedream
Date: Mon, 1 Jul 2024 16:37:53 +0200
Subject: [PATCH 81/82] Update README.md
---
README.md | 4 +---
1 file changed, 1 insertion(+), 3 deletions(-)
diff --git a/README.md b/README.md
index 45b8ea7..1ae2645 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,4 @@
-> ~~This project has been sunset as Crunchyroll moved to a DRM-only system. See [#362](https://github.com/crunchy-labs/crunchy-cli/issues/362).~~
->
-> Well there is one endpoint which still has DRM-free streams, I guess I still have a bit time until (finally) everything is DRM-only.
+# This project has been sunset as Crunchyroll moved to a DRM-only system. See [#362](https://github.com/crunchy-labs/crunchy-cli/issues/362).
# crunchy-cli
From 4332b1beef7007129578cc7e253c99c96b5f6e39 Mon Sep 17 00:00:00 2001
From: Simon <47527944+Frooastside@users.noreply.github.com>
Date: Mon, 1 Jul 2024 18:43:16 +0200
Subject: [PATCH 82/82] not add start time when syncing (#442)
* not add start time when syncing
* use itsoffset for all syncing related time shifts
---
crunchy-cli-core/src/utils/download.rs | 22 ++++++++--------------
1 file changed, 8 insertions(+), 14 deletions(-)
diff --git a/crunchy-cli-core/src/utils/download.rs b/crunchy-cli-core/src/utils/download.rs
index accefce..2e8f321 100644
--- a/crunchy-cli-core/src/utils/download.rs
+++ b/crunchy-cli-core/src/utils/download.rs
@@ -322,20 +322,14 @@ impl Downloader {
if let Some(offsets) = offsets {
let mut root_format_idx = 0;
- let mut root_format_length = 0;
+ let mut root_format_offset = u64::MAX;
+
for (i, format) in self.formats.iter().enumerate() {
let offset = offsets.get(&i).copied().unwrap_or_default();
- let format_len = format
- .video
- .0
- .segments()
- .iter()
- .map(|s| s.length.as_millis())
- .sum::() as u64
- - offset.num_milliseconds() as u64;
- if format_len > root_format_length {
+ let format_offset = offset.num_milliseconds() as u64;
+ if format_offset < root_format_offset {
root_format_idx = i;
- root_format_length = format_len;
+ root_format_offset = format_offset;
}
for _ in &format.audios {
@@ -567,7 +561,7 @@ impl Downloader {
for (i, meta) in videos.iter().enumerate() {
if let Some(start_time) = meta.start_time {
- input.extend(["-ss".to_string(), format_time_delta(&start_time)])
+ input.extend(["-itsoffset".to_string(), format_time_delta(&start_time)])
}
input.extend(["-i".to_string(), meta.path.to_string_lossy().to_string()]);
maps.extend(["-map".to_string(), i.to_string()]);
@@ -588,7 +582,7 @@ impl Downloader {
}
for (i, meta) in audios.iter().enumerate() {
if let Some(start_time) = meta.start_time {
- input.extend(["-ss".to_string(), format_time_delta(&start_time)])
+ input.extend(["-itsoffset".to_string(), format_time_delta(&start_time)])
}
input.extend(["-i".to_string(), meta.path.to_string_lossy().to_string()]);
maps.extend(["-map".to_string(), (i + videos.len()).to_string()]);
@@ -635,7 +629,7 @@ impl Downloader {
if container_supports_softsubs {
for (i, meta) in subtitles.iter().enumerate() {
if let Some(start_time) = meta.start_time {
- input.extend(["-ss".to_string(), format_time_delta(&start_time)])
+ input.extend(["-itsoffset".to_string(), format_time_delta(&start_time)])
}
input.extend(["-i".to_string(), meta.path.to_string_lossy().to_string()]);
maps.extend([