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 73% rename from .github/scripts/PKGBUILD.source rename to .github/workflow-resources/PKGBUILD.source index af6b8e1..4b14f5b 100644 --- a/.github/scripts/PKGBUILD.source +++ b/.github/workflow-resources/PKGBUILD.source @@ -12,14 +12,26 @@ 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) + +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" - cargo build --release + export CRUNCHY_CLI_GIT_HASH=$CI_GIT_HASH + cargo build --frozen --release } package() { diff --git a/.github/workflows/ci.yml b/.github/workflows/build.yml similarity index 65% rename from .github/workflows/ci.yml rename to .github/workflows/build.yml index aa70330..9248ca5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/build.yml @@ -1,9 +1,9 @@ -name: ci +name: build on: push: branches: - - master + - '*' pull_request: workflow_dispatch: @@ -22,7 +22,7 @@ jobs: uses: actions/checkout@v4 - name: Cargo cache - uses: actions/cache@v3 + uses: actions/cache@v4 with: path: | ~/.cargo/bin/ @@ -41,37 +41,51 @@ 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@v3 + uses: actions/upload-artifact@v4 with: name: crunchy-cli-linux-${{ matrix.arch }} path: ./target/${{ matrix.toolchain }}/release/crunchy-cli if-no-files-found: error - name: Upload manpages artifact - uses: actions/upload-artifact@v3 + if: ${{ matrix.arch == 'x86_64' }} # only upload the manpages once + uses: actions/upload-artifact@v4 with: name: manpages path: ./target/${{ matrix.toolchain }}/release/manpages if-no-files-found: error - name: Upload completions artifact - uses: actions/upload-artifact@v3 + if: ${{ matrix.arch == 'x86_64' }} # only upload the completions once + uses: actions/upload-artifact@v4 with: name: completions path: ./target/${{ matrix.toolchain }}/release/completions if-no-files-found: error build-mac: - runs-on: macos-latest + runs-on: ${{ matrix.os }} + strategy: + matrix: + # macos-13 uses x86_64, macos-14 aarch64 + # see https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners/about-github-hosted-runners#supported-runners-and-hardware-resources + include: + - os: macos-13 + arch: x86_64 + toolchain: x86_64-apple-darwin + - os: macos-14 + arch: aarch64 + toolchain: aarch64-apple-darwin steps: - name: Checkout uses: actions/checkout@v4 - name: Cargo cache - uses: actions/cache@v3 + if: ${{ matrix.os != 'macos-13' }} # when using cache, the 'Setup Rust' step fails for macos 13 + uses: actions/cache@v4 with: path: | ~/.cargo/bin/ @@ -87,13 +101,13 @@ jobs: toolchain: stable - name: Build - run: cargo build --release --target x86_64-apple-darwin + run: cargo build --locked --release --target ${{ matrix.toolchain }} - name: Upload binary artifact - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: - name: crunchy-cli-darwin-x86_64 - path: ./target/x86_64-apple-darwin/release/crunchy-cli + name: crunchy-cli-darwin-${{ matrix.arch }} + path: ./target/${{ matrix.toolchain }}/release/crunchy-cli if-no-files-found: error build-windows: @@ -103,7 +117,7 @@ jobs: uses: actions/checkout@v4 - name: Cargo cache - uses: actions/cache@v3 + uses: actions/cache@v4 with: path: | ~/.cargo/bin/ @@ -121,10 +135,10 @@ 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@v3 + uses: actions/upload-artifact@v4 with: name: crunchy-cli-windows-x86_64 path: ./target/x86_64-pc-windows-gnu/release/crunchy-cli.exe 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 diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 4a477b3..8f178ce 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/workflow-resources/PKGBUILD.source > PKGBUILD - name: Publish crunchy-cli to AUR uses: KSXGitHub/github-actions-deploy-aur@v2.7.0 @@ -57,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 diff --git a/Cargo.lock b/Cargo.lock index 24f8472..d01a80c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -17,22 +17,11 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" -[[package]] -name = "aes" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac1f845298e95f983ff1944b728ae08b8cebab80d684f0a832ed0fc74dfa27e2" -dependencies = [ - "cfg-if", - "cipher", - "cpufeatures", -] - [[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", ] @@ -54,47 +43,48 @@ dependencies = [ [[package]] name = "anstream" -version = "0.6.5" +version = "0.6.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d664a92ecae85fd0a7392615844904654d1d5f5514837f471ddef4a057aba1b6" +checksum = "418c75fa768af9c03be99d17643f93f79bbba589895012a80e3452a19ddda15b" dependencies = [ "anstyle", "anstyle-parse", "anstyle-query", "anstyle-wincon", "colorchoice", + "is_terminal_polyfill", "utf8parse", ] [[package]] name = "anstyle" -version = "1.0.4" +version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7079075b41f533b8c61d2a4d073c4676e1f8b249ff94a393b0595db304e0dd87" +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", @@ -102,9 +92,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.79" +version = "1.0.86" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "080e9890a082662b09c1ad45f567faeeb47f22b5fb23895fbe1e651e718e25ca" +checksum = "b3d1d046238990b9cf5bcde22a3fb3584ee5cf65fb2765f454ed428c7a0063da" [[package]] name = "async-speed-limit" @@ -120,9 +110,9 @@ dependencies = [ [[package]] name = "async-trait" -version = "0.1.77" +version = "0.1.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c980ee35e870bd1a4d2c8294d4c04d0499e67bca1e4b5cefcc693c2fa00caea9" +checksum = "c6fa2087f2753a7da8cc1c0dbfcf89579dd57458e36769de5ac750b4671737ca" dependencies = [ "proc-macro2", "quote", @@ -130,16 +120,22 @@ dependencies = [ ] [[package]] -name = "autocfg" -version = "1.1.0" +name = "atomic-waker" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0" [[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", @@ -152,9 +148,15 @@ dependencies = [ [[package]] name = "base64" -version = "0.21.6" +version = "0.21.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c79fed4cdb43e993fcdadc7e58a09fd0e3e649c4436fa11da71c9f1f3ee7feb9" +checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" [[package]] name = "base64-serde" @@ -162,7 +164,7 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba368df5de76a5bea49aaf0cf1b39ccfbbef176924d1ba5db3e4135216cbe3c7" dependencies = [ - "base64", + "base64 0.21.7", "serde", ] @@ -174,48 +176,27 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "327762f6e5a765692301e5bb513e0d9fef63be86bbc14528052b1cd3e6f03e07" - -[[package]] -name = "block-padding" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93" -dependencies = [ - "generic-array", -] +checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1" [[package]] name = "bumpalo" -version = "3.14.0" +version = "3.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f30e7476521f6f8af1a1c4c0b8cc94f0bee37d91763d0ca2665f299b6cd8aec" +checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c" [[package]] name = "bytes" -version = "1.5.0" +version = "1.6.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", -] +checksum = "514de17de45fdb8dc022b1a7975556c53c86f9f0aa5f534b98977b171857c2c9" [[package]] name = "cc" -version = "1.0.83" +version = "1.0.98" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1174fb0b6ec23863f8b971027804a42614e347eafb0a95bf0b12cdae21fc4d0" -dependencies = [ - "libc", -] +checksum = "41c270e7540d725e65ac7f1b212ac8ce349719624d7bcff99f8e2e488e8cf03f" [[package]] name = "cfg-if" @@ -224,10 +205,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] -name = "chrono" -version = "0.4.31" +name = "cfg_aliases" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f2c685bad3eb3d45a01354cedb7d5faa66194d1d58ba6e267a8de788f79db38" +checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e" + +[[package]] +name = "chrono" +version = "0.4.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a21f936df1771bf62b77f047b726c4625ff2e8aa607c01ec06e5a05bd8463401" dependencies = [ "android-tzdata", "iana-time-zone", @@ -235,24 +222,14 @@ dependencies = [ "num-traits", "serde", "wasm-bindgen", - "windows-targets 0.48.5", -] - -[[package]] -name = "cipher" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" -dependencies = [ - "crypto-common", - "inout", + "windows-targets 0.52.5", ] [[package]] name = "clap" -version = "4.4.14" +version = "4.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33e92c5c1a78c62968ec57dbc2440366a2d6e5a23faf829970ff1585dc6b18e2" +checksum = "90bc066a67923782aa8515dbaea16946c5bcc5addbd668bb80af688e53e548a0" dependencies = [ "clap_builder", "clap_derive", @@ -260,9 +237,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.4.14" +version = "4.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4323769dc8a61e2c39ad7dc26f6f2800524691a44d74fe3d1071a5c24db6370" +checksum = "ae129e2e766ae0ec03484e609954119f123cc1fe650337e155d03b022f24f7b4" dependencies = [ "anstream", "anstyle", @@ -272,18 +249,18 @@ dependencies = [ [[package]] name = "clap_complete" -version = "4.4.6" +version = "4.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97aeaa95557bd02f23fbb662f981670c3d20c5a26e69f7354b28f57092437fcd" +checksum = "dd79504325bf38b10165b02e89b4347300f855f273c4cb30c4a3209e6583275e" dependencies = [ "clap", ] [[package]] name = "clap_derive" -version = "4.4.7" +version = "4.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf9804afaaf59a91e75b022a30fb7229a7901f60c755489cc61c9b423b836442" +checksum = "528131438037fd55894f62d6e9f068b8f45ac57ffa77517819645d10aed04f64" dependencies = [ "heck", "proc-macro2", @@ -293,15 +270,15 @@ dependencies = [ [[package]] name = "clap_lex" -version = "0.6.0" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "702fc72eb24e5a1e48ce58027a675bc24edd52096d5397d4aea7c6dd9eca0bd1" +checksum = "98cc8fbded0c607b7ba9dd60cd98df59af97e84d24e49c8557331cfc26d301ce" [[package]] name = "clap_mangen" -version = "0.2.16" +version = "0.2.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10b5db60b3310cdb376fbeb8826e875a38080d0c61bdec0a91a3da8338948736" +checksum = "e1dd95b5ebb5c1c54581dd6346f3ed6a79a3eef95dd372fc2ac13d535535300e" dependencies = [ "clap", "roff", @@ -309,28 +286,28 @@ 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" -version = "0.15.7" +version = "0.15.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c926e00cc70edefdc64d3a5ff31cc65bb97a3460097762bd23afb4d8145fccf8" +checksum = "0e1f83fc076bd6dd27517eacdf25fef6c4dfe5f1d7448bafaaf3a26f13b5e4eb" dependencies = [ "encode_unicode", "lazy_static", "libc", "unicode-width", - "windows-sys 0.45.0", + "windows-sys 0.52.0", ] [[package]] name = "cookie" -version = "0.16.2" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e859cd57d0710d9e06c381b550c06e76992472a8c6d527aecd2fc673dcc231fb" +checksum = "7efb37c3e1ccb1ff97164ad95ac1606e8ccd35b3fa0a7d99a304c7f4a428cc24" dependencies = [ "percent-encoding", "time", @@ -339,12 +316,12 @@ dependencies = [ [[package]] name = "cookie_store" -version = "0.16.2" +version = "0.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d606d0fba62e13cf04db20536c05cb7f13673c161cb47a47a82b9b9e7d3f1daa" +checksum = "387461abbc748185c3a6e1673d826918b450b87ff22639429c694619a83b6cf6" dependencies = [ "cookie", - "idna 0.2.3", + "idna 0.3.0", "log", "publicsuffix", "serde", @@ -370,18 +347,9 @@ 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.2.2" +version = "3.6.7" dependencies = [ "chrono", "clap", @@ -394,7 +362,7 @@ dependencies = [ [[package]] name = "crunchy-cli-core" -version = "3.2.2" +version = "3.6.7" dependencies = [ "anyhow", "async-speed-limit", @@ -415,13 +383,16 @@ dependencies = [ "num_cpus", "regex", "reqwest", + "rsubs-lib", "rustls-native-certs", + "rusty-chromaprint", "serde", "serde_json", "serde_plain", "shlex", "sys-locale", "tempfile", + "time", "tokio", "tokio-util", "tower-service", @@ -429,19 +400,17 @@ dependencies = [ [[package]] name = "crunchyroll-rs" -version = "0.8.2" +version = "0.11.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "828ff3c0f11de8f8afda7dc3bd24e206e1b13cee6abfd87856123305864681d2" +checksum = "d6e38c223aecf65c9c9bec50764beea5dc70b6c97cd7f767bf6860f2fc8e0a07" dependencies = [ - "aes", "async-trait", - "cbc", "chrono", "crunchyroll-rs-internal", "dash-mpd", "futures-util", + "jsonwebtoken", "lazy_static", - "m3u8-rs", "regex", "reqwest", "rustls", @@ -451,35 +420,26 @@ dependencies = [ "smart-default", "tokio", "tower-service", - "webpki-roots 0.26.0", + "uuid", + "webpki-roots", ] [[package]] name = "crunchyroll-rs-internal" -version = "0.8.2" +version = "0.11.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7051a39e25a19ef0aa753e7da179787a3db0fb8a01977a7e22cd288f7ff0e27" +checksum = "144a38040a21aaa456741a9f6749354527bb68ad3bb14210e0bbc40fbd95186c" 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.2" +version = "3.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b467862cc8610ca6fc9a1532d7777cee0804e678ab45410897b9396495994a0b" +checksum = "672465ae37dc1bc6380a6547a8883d5dd397b0f1faaad4f265726cc7042a5345" dependencies = [ "nix", "windows-sys 0.52.0", @@ -487,9 +447,9 @@ dependencies = [ [[package]] name = "darling" -version = "0.20.3" +version = "0.20.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0209d94da627ab5605dcccf08bb18afa5009cfbef48d8a8b7d7bdbc79be25c5e" +checksum = "83b2eb4d90d12bdda5ed17de686c2acb4c57914f8f921b8da7e112b5a36f3fe1" dependencies = [ "darling_core", "darling_macro", @@ -497,9 +457,9 @@ dependencies = [ [[package]] name = "darling_core" -version = "0.20.3" +version = "0.20.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "177e3443818124b357d8e76f53be906d60937f0d3a90773a664fa63fa253e621" +checksum = "622687fe0bac72a04e5599029151f5796111b90f1baaa9b544d807a5e31cd120" dependencies = [ "fnv", "ident_case", @@ -511,9 +471,9 @@ dependencies = [ [[package]] name = "darling_macro" -version = "0.20.3" +version = "0.20.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "836a9bbc7ad63342d6d6e7b815ccab164bc77a2d95d84bc3117a8c0d5c98e2d5" +checksum = "733cabb43482b1a1b53eee8583c2b9e8684d592215ea83efd305dd31bc2f0178" dependencies = [ "darling_core", "quote", @@ -522,12 +482,13 @@ dependencies = [ [[package]] name = "dash-mpd" -version = "0.14.7" +version = "0.16.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cf94350e05e27c941b8cfc06bffeec3afcac11f42df289378ddf43e192d2e15" +checksum = "4618a5e165bf47b084963611bcf1d568c681f52d8a237e8862a0cd8c546ba255" dependencies = [ - "base64", + "base64 0.22.1", "base64-serde", + "bytes", "chrono", "fs-err", "iso8601", @@ -539,7 +500,6 @@ dependencies = [ "serde_path_to_error", "serde_with", "thiserror", - "tokio", "tracing", "url", "xattr", @@ -601,9 +561,9 @@ dependencies = [ [[package]] name = "either" -version = "1.9.0" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07" +checksum = "3dca9240753cf90908d7e4aac30f630662b02aebaa1b58a3cadabdb23385b58b" [[package]] name = "encode_unicode" @@ -613,9 +573,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", ] @@ -628,9 +588,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", @@ -638,9 +598,9 @@ dependencies = [ [[package]] name = "fastrand" -version = "2.0.1" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5" +checksum = "9fc0510504f03c51ada170672ac806f1f105a88aa97a5281117e1ddc3368e51a" [[package]] name = "fnv" @@ -737,9 +697,9 @@ checksum = "38d84fa142264698cdce1a9f9172cf383a0c82de1bddcf3092901442c4097004" [[package]] name = "futures-timer" -version = "3.0.2" +version = "3.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e64b03909df88034c26dc1547e8970b91f98bdb65165d6a4e9110d94263dbb2c" +checksum = "f288b0a4f20f9a56b5d1da57e2227c661b7b16168e2f72365f57b63326e29b24" [[package]] name = "futures-util" @@ -758,25 +718,17 @@ 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" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "190092ea657667030ac6a35e305e62fc4dd69fd98ac98631e5d3a2b1575a12b5" +checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" dependencies = [ "cfg-if", + "js-sys", "libc", "wasi", + "wasm-bindgen", ] [[package]] @@ -787,17 +739,17 @@ checksum = "4271d37baee1b8c7e4b708028c57d816cf9d2434acb33a549475f78c181f6253" [[package]] name = "h2" -version = "0.3.22" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d6250322ef6e60f93f9a2162799302cd6f68f79f6e5d85c8c16f14d1d958178" +checksum = "fa82e28a107a8cc405f0839610bdc9b15f1e25ec7d696aa5cf173edbcb1486ab" dependencies = [ + "atomic-waker", "bytes", "fnv", "futures-core", "futures-sink", - "futures-util", "http", - "indexmap 2.1.0", + "indexmap 2.2.6", "slab", "tokio", "tokio-util", @@ -812,21 +764,21 @@ 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" -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" -version = "0.3.3" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d77f7ec81a6d05a3abb01ab6eb7590f6083d08449fe5a1c8b1e620283546ccb7" +checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" [[package]] name = "hex" @@ -836,9 +788,9 @@ checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" [[package]] name = "http" -version = "0.2.11" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8947b1a6fad4393052c7ba1f4cd97bed3e953a95c79c92ad9b051a04611d9fbb" +checksum = "21b9ddb458710bc376481b842f5da65cdf31522de232c1ca8146abce2a358258" dependencies = [ "bytes", "fnv", @@ -847,12 +799,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", ] @@ -862,68 +826,84 @@ 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.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf96e135eb83a2a8ddf766e426a841d8ddd7449d5f00d34ea02b41d2f19eef80" +checksum = "fe575dd17d0862a9a33781c8c4696a55c320909004a67a00fb286ba8b1bc496d" 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]] name = "iana-time-zone" -version = "0.1.59" +version = "0.1.60" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6a67363e2aa4443928ce15e57ebae94fd8949958fd1223c4cfc0cd473ad7539" +checksum = "e7ffbb5a1b541ea2561f8c41c087286cc091e21e556a4f09a8f6cbf17b69b141" dependencies = [ "android_system_properties", "core-foundation-sys", @@ -948,17 +928,6 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" -[[package]] -name = "idna" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "418a0a6fab821475f634efe3ccc45c013f742efe03d853e8d3355d5cb850ecf8" -dependencies = [ - "matches", - "unicode-bidi", - "unicode-normalization", -] - [[package]] name = "idna" version = "0.3.0" @@ -992,20 +961,20 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.1.0" +version = "2.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d530e1a18b1cb4c484e6e34556a0d948706958449fca0cab753d649f2bce3d1f" +checksum = "168fb715dda47215e360912c096649d23d58bf392ac62f73919e831745e40f26" dependencies = [ "equivalent", - "hashbrown 0.14.3", + "hashbrown 0.14.5", "serde", ] [[package]] name = "indicatif" -version = "0.17.7" +version = "0.17.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb28741c9db9a713d93deb3bb9515c20788cef5815265bee4980e87bde7e0f25" +checksum = "763a5a8f45087d6bcea4222e7b72c291a054edf80e4ef6efd2a4979878c7bea3" dependencies = [ "console", "instant", @@ -1014,21 +983,11 @@ 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" +version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" +checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222" dependencies = [ "cfg-if", ] @@ -1039,6 +998,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" @@ -1050,19 +1015,32 @@ 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" -version = "0.3.66" +version = "0.3.69" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cee9c64da59eae3b50095c18d3e74f8b73c0b86d2792824ff01bbce68ba229ca" +checksum = "29c15563dc2726973df627357ce0c9ddddbea194836909d655df6a75d2cf296d" dependencies = [ "wasm-bindgen", ] +[[package]] +name = "jsonwebtoken" +version = "9.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ae10193d25051e74945f1ea2d0b42e03cc3b890f7e4cc5faa44997d808193f" +dependencies = [ + "base64 0.21.7", + "js-sys", + "ring", + "serde", + "serde_json", +] + [[package]] name = "lazy_static" version = "1.4.0" @@ -1071,54 +1049,37 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" [[package]] name = "libc" -version = "0.2.152" +version = "0.2.155" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13e3bf6590cbc649f4d1a3eefc9d5d6eb746f5200ffb04e5e142700b8faa56e7" +checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c" [[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.1", + "bitflags 2.5.0", "libc", - "redox_syscall", ] [[package]] name = "linux-raw-sys" -version = "0.4.12" +version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4cd1a83af159aa67994778be9070f0ae1bd732942279cabb14f86f986a21456" +checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" [[package]] name = "log" -version = "0.4.20" +version = "0.4.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f" - -[[package]] -name = "m3u8-rs" -version = "5.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c1d7ba86f7ea62f17f4310c55e93244619ddc7dadfc7e565de1967e4e41e6e7" -dependencies = [ - "chrono", - "nom", -] - -[[package]] -name = "matches" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2532096657941c2fea9c289d370a250971c689d4f143798ff67113ec042024a5" +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" @@ -1126,6 +1087,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" @@ -1134,18 +1105,18 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" [[package]] name = "miniz_oxide" -version = "0.7.1" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7810e0be55b428ada41041c41f32c9f1a42817901b4ccf45fa3d4b6561e74c7" +checksum = "87dfd01fe195c66b572b37921ad8803d010623c0aca821bea2302239d155cdae" dependencies = [ "adler", ] [[package]] name = "mio" -version = "0.8.10" +version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f3d0b296e374a4e6f3c7b0a1f5a51d748a0d34c85e7dc48fc3fa9a87657fe09" +checksum = "a4a650543ca06a924e8b371db273b2756685faae30f8487da1b56505a8f78b0c" dependencies = [ "libc", "wasi", @@ -1154,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=fdba246#fdba246a79986607cbdf573733445498bb6da2a9" +version = "0.2.12" +source = "git+https://github.com/crunchy-labs/rust-not-so-native-tls.git?rev=c7ac566#c7ac566559d441bbc3e5e5bd04fb7162c38d88b0" dependencies = [ "libc", "log", @@ -1170,12 +1141,13 @@ dependencies = [ [[package]] name = "nix" -version = "0.27.1" +version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2eb04e9c688eff1c89d72b407f168cf79bb9e867a9d3323ed6c01519eb9cc053" +checksum = "ab2156c4fce2f8df6c499cc1c763e4394b7482525bf2a9701c9d79d215f519e4" dependencies = [ - "bitflags 2.4.1", + "bitflags 2.5.0", "cfg-if", + "cfg_aliases", "libc", ] @@ -1190,10 +1162,34 @@ dependencies = [ ] [[package]] -name = "num-traits" -version = "0.2.17" +name = "num-complex" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39e3200413f237f41ab11ad6d161bc7239c84dcb631773ccd7de3dfe4b5c267c" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +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.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", ] @@ -1231,11 +1227,11 @@ checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" [[package]] name = "openssl" -version = "0.10.62" +version = "0.10.64" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8cde4d2d9200ad5909f8dac647e29482e07c3a35de8a13fce7c9c7747ad9f671" +checksum = "95a0481286a310808298130d22dd1fef0fa571e05a8f44ec801801e84b216b1f" dependencies = [ - "bitflags 2.4.1", + "bitflags 2.5.0", "cfg-if", "foreign-types", "libc", @@ -1263,18 +1259,18 @@ checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" [[package]] name = "openssl-src" -version = "300.2.1+3.2.0" +version = "300.3.0+3.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fe476c29791a5ca0d1273c697e96085bbabbbea2ef7afd5617e78a4b40332d3" +checksum = "eba8804a1c5765b18c4b3f907e6897ebabeedebc9830e1a0046c4a4cf44663e1" dependencies = [ "cc", ] [[package]] name = "openssl-sys" -version = "0.9.98" +version = "0.9.102" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1665caf8ab2dc9aef43d1c0023bd904633a6a05cb30b0ad59bec2ae986e57a7" +checksum = "c597637d56fbc83893a35eb0dd04b2b8e7a50c91e64e9493e398b5df4fb45fa2" dependencies = [ "cc", "libc", @@ -1296,10 +1292,30 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" [[package]] -name = "pin-project-lite" -version = "0.2.13" +name = "pin-project" +version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8afb450f006bf6385ca15ef45d71d2288452bc3683ce2e2cacc0d18e4be60b58" +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.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bda66fc9667c18cb2758a2ac84d1167245054bcf85d5d1aaa6923f45801bdd02" [[package]] name = "pin-utils" @@ -1309,9 +1325,9 @@ checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" [[package]] name = "pkg-config" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69d3587f8a9e599cc7ec2c00e331f71c4e69a5f9a4b8a6efd5b07466b9736f9a" +checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec" [[package]] name = "portable-atomic" @@ -1326,10 +1342,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" [[package]] -name = "proc-macro2" -version = "1.0.76" +name = "primal-check" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95fc56cda0b5c3325f5fbbd7ff9fda9e02bb00bb3dac51252d2f1bfa1cb8cc8c" +checksum = "9df7f93fd637f083201473dab4fee2db4c429d32e55e3299980ab3957ab916a0" +dependencies = [ + "num-integer", +] + +[[package]] +name = "proc-macro2" +version = "1.0.83" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b33eb56c327dec362a9e55b3ad14f9d2f0904fb5a5b03b513ab5465399e9f43" dependencies = [ "unicode-ident", ] @@ -1362,27 +1387,27 @@ 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", ] [[package]] -name = "redox_syscall" -version = "0.4.1" +name = "realfft" +version = "3.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" +checksum = "953d9f7e5cdd80963547b456251296efc2626ed4e3cbf36c869d9564e0220571" dependencies = [ - "bitflags 1.3.2", + "rustfft", ] [[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", @@ -1391,9 +1416,9 @@ dependencies = [ [[package]] name = "regex" -version = "1.10.2" +version = "1.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "380b951a9c5e80ddfd6136919eef32310721aa4aacd4889a8d39124b026ab343" +checksum = "c117dbdfde9c8308975b6a18d71f3f385c89461f7b3fb054288ecf2a2058ba4c" dependencies = [ "aho-corasick", "memchr", @@ -1403,9 +1428,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.3" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f804c7828047e88b2d32e2d7fe5a105da8ee3264f01902f796c8e067dc2483f" +checksum = "86b83b8b9847f9bf95ef68afb0b8e6cdb80f498442f5179a29fad448fcc1eaea" dependencies = [ "aho-corasick", "memchr", @@ -1414,17 +1439,17 @@ 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" -version = "0.11.23" +version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37b1ae8d9ac08420c66222fb9096fc5de435c3c48542bc5336c51892cffafb41" +checksum = "566cafdd92868e0939d3fb961bd0dc25fcfaaed179291093b3d43e6b3150ea10" dependencies = [ - "base64", + "base64 0.22.1", "bytes", "cookie", "cookie_store", @@ -1434,22 +1459,27 @@ dependencies = [ "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", + "rustls-pki-types", "serde", "serde_json", "serde_urlencoded", + "sync_wrapper", "system-configuration", "tokio", "tokio-native-tls", @@ -1462,22 +1492,23 @@ dependencies = [ "wasm-bindgen-futures", "wasm-streams", "web-sys", - "webpki-roots 0.25.3", + "webpki-roots", "winreg", ] [[package]] name = "ring" -version = "0.17.7" +version = "0.17.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "688c63d65483050968b2a8937f7995f443e27041a0f7700aa59b0822aedebb74" +checksum = "c17fa4cb658e3583423e915b9f3acc01cceaee1860e33d59ebae66adc3a2dc0d" dependencies = [ "cc", + "cfg-if", "getrandom", "libc", "spin", "untrusted", - "windows-sys 0.48.0", + "windows-sys 0.52.0", ] [[package]] @@ -1487,18 +1518,56 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b833d8d034ea094b1ea68aa6d5c740e0d04bad9d16568d08ba6f76823a114316" [[package]] -name = "rustc-demangle" -version = "0.1.23" +name = "rsubs-lib" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76" +checksum = "8c9f50e3fbcbf1f0bd109954e2dd813d1715c7b4a92a7bf159a85dea49e9d863" +dependencies = [ + "regex", + "serde", + "time", +] + +[[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.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" + +[[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.28" +version = "0.38.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72e572a5e8ca657d7366229cdde4bd14c4eb5499a9573d4d366fe1b599daa316" +checksum = "70dc5ec042f7a43c4a73241207cecc9873a06d45debb38b329f8541d85c2730f" dependencies = [ - "bitflags 2.4.1", + "bitflags 2.5.0", "errno", "libc", "linux-raw-sys", @@ -1507,58 +1576,73 @@ dependencies = [ [[package]] name = "rustls" -version = "0.21.10" +version = "0.22.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9d5a6813c0759e4609cd494e8e725babae6a2ca7b62a5536a13daaec6fcb7ba" +checksum = "bf4ef73721ac7bcd79b2b315da7779d8fc09718c6b3d2d1b2d94850eb8c18432" dependencies = [ "log", "ring", + "rustls-pki-types", "rustls-webpki", - "sct", + "subtle", + "zeroize", ] [[package]] name = "rustls-native-certs" -version = "0.6.3" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9aace74cb666635c918e9c12bc0d348266037aa8eb599b5cba565709a8dff00" +checksum = "8f1fb85efa936c42c6d5fc28d2629bb51e4b2f4b8a5211e297d599cc5a093792" dependencies = [ "openssl-probe", "rustls-pemfile", + "rustls-pki-types", "schannel", "security-framework", ] [[package]] name = "rustls-pemfile" -version = "1.0.4" +version = "2.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c74cae0a4cf6ccbbf5f359f08efdf8ee7e1dc532573bf0db71968cb56b1448c" +checksum = "29993a25686778eb88d4189742cd713c9bce943bc54251a33509dc63cbacf73d" dependencies = [ - "base64", + "base64 0.22.1", + "rustls-pki-types", ] [[package]] name = "rustls-pki-types" -version = "1.1.0" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e9d979b3ce68192e42760c7810125eb6cf2ea10efae545a156063e61f314e2a" +checksum = "976295e77ce332211c0d24d92c0e83e50f5c5f046d11082cea19f3df13a3562d" [[package]] name = "rustls-webpki" -version = "0.101.7" +version = "0.102.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b6275d1ee7a1cd780b64aca7726599a1dbc893b1e64144529e55c3c2f745765" +checksum = "ff448f7e92e913c4b7d4c6d8e4540a1724b319b4152b8aef6d4cf8339712b33e" dependencies = [ "ring", + "rustls-pki-types", "untrusted", ] [[package]] -name = "ryu" -version = "1.0.16" +name = "rusty-chromaprint" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f98d2aa92eebf49b69786be48e4477826b256916e84a57ff2a4f21923b48eb4c" +checksum = "1755646867c36ecb391776deaa0b557a76d3badf20c142de7282630c34b20440" +dependencies = [ + "rubato", + "rustfft", +] + +[[package]] +name = "ryu" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" [[package]] name = "schannel" @@ -1569,23 +1653,13 @@ 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" +version = "2.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05b64fb303737d99b81884b2c63433e9ae28abebe5eb5045dcdd175dc2ecf4de" +checksum = "c627723fd09706bacdb5cf41499e95098555af3c3c29d014dc3c458ef6be11c0" dependencies = [ - "bitflags 1.3.2", + "bitflags 2.5.0", "core-foundation", "core-foundation-sys", "libc", @@ -1594,9 +1668,9 @@ dependencies = [ [[package]] name = "security-framework-sys" -version = "2.9.1" +version = "2.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e932934257d3b408ed8f30db49d85ea163bfe74961f017f405b025af298f0c7a" +checksum = "317936bbbd05227752583946b9e66d7ce3b489f84e11a94a510b4437fef407d7" dependencies = [ "core-foundation-sys", "libc", @@ -1604,18 +1678,18 @@ dependencies = [ [[package]] name = "serde" -version = "1.0.195" +version = "1.0.202" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63261df402c67811e9ac6def069e4786148c4563f4b50fd4bf30aa370d626b02" +checksum = "226b61a0d411b2ba5ff6d7f73a476ac4f8bb900373459cd00fab8512828ba395" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.195" +version = "1.0.202" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46fe8f8603d81ba86327b23a2e9cdf49e1255fb94a4c5f297f6ee0547178ea2c" +checksum = "6048858004bcff69094cd972ed40a32500f153bd3be9f716b2eed2e8217c4838" dependencies = [ "proc-macro2", "quote", @@ -1624,9 +1698,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.111" +version = "1.0.117" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "176e46fa42316f18edd598015a5166857fc835ec732f5215eac6b7bdbf0a84f4" +checksum = "455182ea6142b14f93f4bc5320a2b31c1f266b66a4a5c858b013302a5d8cbfc3" dependencies = [ "itoa", "ryu", @@ -1635,9 +1709,9 @@ dependencies = [ [[package]] name = "serde_path_to_error" -version = "0.1.15" +version = "0.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebd154a240de39fdebcf5775d2675c204d7c13cf39a4c697be6493c8e734337c" +checksum = "af99884400da37c88f5e9146b7f1fd0fbcae8f6eec4e9da38b67d05486f814a6" dependencies = [ "itoa", "serde", @@ -1666,16 +1740,17 @@ dependencies = [ [[package]] name = "serde_with" -version = "3.4.0" +version = "3.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64cd236ccc1b7a29e7e2739f27c0b2dd199804abc4290e32f59f3b68d6405c23" +checksum = "0ad483d2ab0149d5a5ebcd9972a3852711e0153d863bf5a5d0391d28883c4a20" dependencies = [ - "base64", + "base64 0.22.1", "chrono", "hex", "indexmap 1.9.3", - "indexmap 2.1.0", + "indexmap 2.2.6", "serde", + "serde_derive", "serde_json", "serde_with_macros", "time", @@ -1683,9 +1758,9 @@ dependencies = [ [[package]] name = "serde_with_macros" -version = "3.4.0" +version = "3.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93634eb5f75a2323b16de4748022ac4297f9e76b6dced2be287a099f41b5e788" +checksum = "65569b702f41443e8bc8bbb1c5779bd0450bbe723b56198980e80ec45780bce2" dependencies = [ "darling", "proc-macro2", @@ -1701,9 +1776,9 @@ checksum = "24188a676b6ae68c3b2cb3a01be17fbf7240ce009799bb56d5b1409051e78fde" [[package]] name = "shlex" -version = "1.2.0" +version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7cee0529a6d40f580e7a5e6c495c8fbfe21b7b52795ed4bb5e62cdf92bc6380" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" [[package]] name = "slab" @@ -1714,6 +1789,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" @@ -1727,12 +1808,12 @@ dependencies = [ [[package]] name = "socket2" -version = "0.5.5" +version = "0.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b5fac59a5cb5dd637972e5fca70daf0523c9067fcdc4842f053dae04a18f8e9" +checksum = "ce305eb0b4296696835b71df73eb912e0f1ffd2556a501fcede6e0c50349191c" dependencies = [ "libc", - "windows-sys 0.48.0", + "windows-sys 0.52.0", ] [[package]] @@ -1742,22 +1823,40 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" [[package]] -name = "strsim" -version = "0.10.0" +name = "strength_reduce" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" +checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[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.48" +version = "2.0.65" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f3531638e407dfc0814761abb7c00a5b54992b849452a0646b7f65c9f770f3f" +checksum = "d2863d96a84c6439701d7a38f9de935ec562c8832cc55d1dde0f513b52fad106" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] +[[package]] +name = "sync_wrapper" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160" + [[package]] name = "sys-locale" version = "0.3.1" @@ -1790,31 +1889,30 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.9.0" +version = "3.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01ce4141aa927a6d1bd34a041795abd0db1cccba5d5f24b009f694bdf3a1f3fa" +checksum = "85b77fafb263dd9d05cbeac119526425676db3784113aa9295c88498cbf8bff1" dependencies = [ "cfg-if", "fastrand", - "redox_syscall", "rustix", "windows-sys 0.52.0", ] [[package]] name = "thiserror" -version = "1.0.56" +version = "1.0.61" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d54378c645627613241d077a3a79db965db602882668f9136ac42af9ecb730ad" +checksum = "c546c80d6be4bc6a00c0f01730c08df82eaa7a7a61f11d656526506112cc1709" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.56" +version = "1.0.61" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa0faa943b50f3db30a20aa7e265dbc66076993efed8463e8de414e5d06d3471" +checksum = "46c3384250002a6d5af4d114f2845d37b57521033f30d5c3f46c4d70e1197533" dependencies = [ "proc-macro2", "quote", @@ -1823,12 +1921,13 @@ dependencies = [ [[package]] name = "time" -version = "0.3.31" +version = "0.3.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f657ba42c3f86e7680e53c8cd3af8abbe56b5491790b46e22e19c0d57463583e" +checksum = "5dfd88e563464686c916c7e46e623e520ddc6d79fa6641390f2e3fa86e83e885" dependencies = [ "deranged", "itoa", + "num-conv", "powerfmt", "serde", "time-core", @@ -1843,10 +1942,11 @@ checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" [[package]] name = "time-macros" -version = "0.2.16" +version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26197e33420244aeb70c3e8c78376ca46571bc4e701e4791c2cd9f57dcb3a43f" +checksum = "3f252a68540fde3a3877aeea552b832b40ab9a69e318efd078774a01ddee1ccf" dependencies = [ + "num-conv", "time-core", ] @@ -1867,9 +1967,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.35.1" +version = "1.38.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c89b4efa943be685f629b149f53829423f8f5531ea21249408e8e2f8671ec104" +checksum = "ba4f4a02a7a80d6f274636f0aa95c7e383b912d41fe721a31f29e29698585a4a" dependencies = [ "backtrace", "bytes", @@ -1884,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", @@ -1905,11 +2005,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", ] @@ -1927,18 +2028,39 @@ 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", +] + +[[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" @@ -1951,6 +2073,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", @@ -1976,6 +2099,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" @@ -1983,16 +2116,19 @@ 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" -version = "0.3.14" +version = "0.3.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f2528f27a9eb2b21e69c95319b30bd0efd85d09c379741b0f78ea1d86be2416" +checksum = "08f95100a766bf4f8f28f90d77e0a5461bbdb219042e7679bebe79004fed8d75" [[package]] name = "unicode-ident" @@ -2002,18 +2138,18 @@ checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" [[package]] name = "unicode-normalization" -version = "0.1.22" +version = "0.1.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c5713f0fc4b5db668a2ac63cdb7bb4469d8c9fed047b1d0292cc7b0ce2ba921" +checksum = "a56d1686db2308d901306f92a263857ef59ea39678a5458e7cb17f01415101f5" dependencies = [ "tinyvec", ] [[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" @@ -2038,6 +2174,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" @@ -2067,9 +2212,9 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasm-bindgen" -version = "0.2.89" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ed0d4f68a3015cc185aff4db9506a015f4b96f95303897bfa23f846db54064e" +checksum = "4be2531df63900aeb2bca0daaaddec08491ee64ceecbee5076636a3b026795a8" dependencies = [ "cfg-if", "wasm-bindgen-macro", @@ -2077,9 +2222,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.89" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b56f625e64f3a1084ded111c4d5f477df9f8c92df113852fa5a374dbda78826" +checksum = "614d787b966d3989fa7bb98a654e369c762374fd3213d212cfc0251257e747da" dependencies = [ "bumpalo", "log", @@ -2092,9 +2237,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.39" +version = "0.4.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac36a15a220124ac510204aec1c3e5db8a22ab06fd6706d881dc6149f8ed9a12" +checksum = "76bc14366121efc8dbb487ab05bcc9d346b3b5ec0eaa76e46594cabbe51762c0" dependencies = [ "cfg-if", "js-sys", @@ -2104,9 +2249,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.89" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0162dbf37223cd2afce98f3d0785506dcb8d266223983e4b5b525859e6e182b2" +checksum = "a1f8823de937b71b9460c0c34e25f3da88250760bec0ebac694b49997550d726" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -2114,9 +2259,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.89" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0eb82fcb7930ae6219a7ecfd55b217f5f0893484b7a13022ebb2b2bf20b5283" +checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" dependencies = [ "proc-macro2", "quote", @@ -2127,15 +2272,15 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.89" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ab9b36309365056cd639da3134bf87fa8f3d86008abf99e612384a6eecd459f" +checksum = "af190c94f2773fdb3729c55b007a722abb5384da03bc0986df4c289bf5567e96" [[package]] name = "wasm-streams" -version = "0.3.0" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4609d447824375f43e1ffbc051b50ad8f4b3ae8219680c94452ea05eb240ac7" +checksum = "b65dc4c90b63b118468cf747d8bf3566c1913ef60be765b5730ead9e0a3ba129" dependencies = [ "futures-util", "js-sys", @@ -2146,9 +2291,9 @@ dependencies = [ [[package]] name = "web-sys" -version = "0.3.66" +version = "0.3.69" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50c24a44ec86bb68fbecd1b3efed7e85ea5621b39b35ef2766b66cd984f8010f" +checksum = "77afa9a11836342370f4817622a2f0f418b134426d91a82dfb48f532d2ec13ef" dependencies = [ "js-sys", "wasm-bindgen", @@ -2156,15 +2301,9 @@ dependencies = [ [[package]] name = "webpki-roots" -version = "0.25.3" +version = "0.26.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1778a42e8b3b90bff8d0f5032bf22250792889a5cdc752aa0020c84abe3aaf10" - -[[package]] -name = "webpki-roots" -version = "0.26.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0de2cfda980f21be5a7ed2eadb3e6fe074d56022bea2cdeb1a62eb220fc04188" +checksum = "b3de34ae270483955a94f4b21bdaaeb83d508bb84a01435f393818edb0012009" dependencies = [ "rustls-pki-types", ] @@ -2197,16 +2336,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" dependencies = [ - "windows-targets 0.52.0", -] - -[[package]] -name = "windows-sys" -version = "0.45.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" -dependencies = [ - "windows-targets 0.42.2", + "windows-targets 0.52.5", ] [[package]] @@ -2224,22 +2354,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets 0.52.0", -] - -[[package]] -name = "windows-targets" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" -dependencies = [ - "windows_aarch64_gnullvm 0.42.2", - "windows_aarch64_msvc 0.42.2", - "windows_i686_gnu 0.42.2", - "windows_i686_msvc 0.42.2", - "windows_x86_64_gnu 0.42.2", - "windows_x86_64_gnullvm 0.42.2", - "windows_x86_64_msvc 0.42.2", + "windows-targets 0.52.5", ] [[package]] @@ -2259,25 +2374,20 @@ dependencies = [ [[package]] name = "windows-targets" -version = "0.52.0" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a18201040b24831fbb9e4eb208f8892e1f50a37feb53cc7ff887feb8f50e7cd" +checksum = "6f0713a46559409d202e70e28227288446bf7841d3211583a4b53e3f6d96e7eb" dependencies = [ - "windows_aarch64_gnullvm 0.52.0", - "windows_aarch64_msvc 0.52.0", - "windows_i686_gnu 0.52.0", - "windows_i686_msvc 0.52.0", - "windows_x86_64_gnu 0.52.0", - "windows_x86_64_gnullvm 0.52.0", - "windows_x86_64_msvc 0.52.0", + "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]] -name = "windows_aarch64_gnullvm" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" - [[package]] name = "windows_aarch64_gnullvm" version = "0.48.5" @@ -2286,15 +2396,9 @@ checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" [[package]] name = "windows_aarch64_gnullvm" -version = "0.52.0" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb7764e35d4db8a7921e09562a0304bf2f93e0a51bfccee0bd0bb0b666b015ea" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" +checksum = "7088eed71e8b8dda258ecc8bac5fb1153c5cffaf2578fc8ff5d61e23578d3263" [[package]] name = "windows_aarch64_msvc" @@ -2304,15 +2408,9 @@ checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" [[package]] name = "windows_aarch64_msvc" -version = "0.52.0" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbaa0368d4f1d2aaefc55b6fcfee13f41544ddf36801e793edbbfd7d7df075ef" - -[[package]] -name = "windows_i686_gnu" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" +checksum = "9985fd1504e250c615ca5f281c3f7a6da76213ebd5ccc9561496568a2752afb6" [[package]] name = "windows_i686_gnu" @@ -2322,15 +2420,15 @@ checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" [[package]] name = "windows_i686_gnu" -version = "0.52.0" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a28637cb1fa3560a16915793afb20081aba2c92ee8af57b4d5f28e4b3e7df313" +checksum = "88ba073cf16d5372720ec942a8ccbf61626074c6d4dd2e745299726ce8b89670" [[package]] -name = "windows_i686_msvc" -version = "0.42.2" +name = "windows_i686_gnullvm" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" +checksum = "87f4261229030a858f36b459e748ae97545d6f1ec60e5e0d6a3d32e0dc232ee9" [[package]] name = "windows_i686_msvc" @@ -2340,15 +2438,9 @@ checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" [[package]] name = "windows_i686_msvc" -version = "0.52.0" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffe5e8e31046ce6230cc7215707b816e339ff4d4d67c65dffa206fd0f7aa7b9a" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" +checksum = "db3c2bf3d13d5b658be73463284eaf12830ac9a26a90c717b7f771dfe97487bf" [[package]] name = "windows_x86_64_gnu" @@ -2358,15 +2450,9 @@ checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" [[package]] name = "windows_x86_64_gnu" -version = "0.52.0" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d6fa32db2bc4a2f5abeacf2b69f7992cd09dca97498da74a151a3132c26befd" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" +checksum = "4e4246f76bdeff09eb48875a0fd3e2af6aada79d409d33011886d3e1581517d9" [[package]] name = "windows_x86_64_gnullvm" @@ -2376,15 +2462,9 @@ checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" [[package]] name = "windows_x86_64_gnullvm" -version = "0.52.0" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a657e1e9d3f514745a572a6846d3c7aa7dbe1658c056ed9c3344c4109a6949e" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" +checksum = "852298e482cd67c356ddd9570386e2862b5673c85bd5f88df9ab6802b334c596" [[package]] name = "windows_x86_64_msvc" @@ -2394,15 +2474,15 @@ checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" [[package]] name = "windows_x86_64_msvc" -version = "0.52.0" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dff9641d1cd4be8d1a070daf9e3773c5f67e78b4d9d42263020c057706765c04" +checksum = "bec47e5bfd1bff0eeaf6d8b485cc1074891a197ab4225d504cb7a1ab88b02bf0" [[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", @@ -2410,11 +2490,17 @@ dependencies = [ [[package]] name = "xattr" -version = "1.2.0" +version = "1.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "914566e6413e7fa959cc394fb30e563ba80f3541fbd40816d4c05a0fc3f2a0f1" +checksum = "8da84f1a25939b27f6820d92aed108f83ff920fdf11a7b19366c27c4cda81d4f" dependencies = [ "libc", "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/Cargo.toml b/Cargo.toml index ee56886..c1e28bb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "crunchy-cli" authors = ["Crunchy Labs Maintainers"] -version = "3.2.2" +version = "3.6.7" edition = "2021" license = "MIT" @@ -13,21 +13,17 @@ native-tls = ["crunchy-cli-core/native-tls"] openssl-tls = ["dep:native-tls-crate", "native-tls-crate/openssl", "crunchy-cli-core/openssl-tls"] openssl-tls-static = ["dep:native-tls-crate", "native-tls-crate/openssl", "crunchy-cli-core/openssl-tls-static"] -# deprecated -openssl = ["openssl-tls"] -openssl-static = ["openssl-tls-static"] - [dependencies] -tokio = { version = "1.35", 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" } [build-dependencies] chrono = "0.4" -clap = { version = "4.4", features = ["string"] } -clap_complete = "4.4" +clap = { version = "4.5", features = ["string"] } +clap_complete = "4.5" clap_mangen = "0.2" crunchy-cli-core = { path = "./crunchy-cli-core" } @@ -38,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 = "fdba246" } +native-tls = { git = "https://github.com/crunchy-labs/rust-not-so-native-tls.git", rev = "c7ac566" } [profile.release] strip = true diff --git a/README.md b/README.md index be97bec..1ae2645 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). @@ -18,8 +20,8 @@ Discord - - CI + + Build

@@ -112,23 +114,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 - - 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 +- Stay Anonymous Login without an account (you won't be able to access premium content): @@ -140,7 +132,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. @@ -148,9 +140,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). @@ -159,7 +151,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. @@ -168,7 +162,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. @@ -180,10 +174,12 @@ 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. + You are also able to set in which part of the cli a proxy should be used. + Instead of a normal url you can also use: `:` (only proxies api requests), `:` (only proxies download traffic), `:` (proxies api requests through the first url and download traffic through the second url). ```shell $ crunchy-cli --proxy socks5://127.0.0.1:8080 @@ -191,7 +187,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. @@ -202,7 +198,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). @@ -218,11 +214,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 @@ -241,7 +235,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. @@ -252,7 +246,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. @@ -263,7 +257,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. @@ -273,17 +267,25 @@ 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. ```shell - $ crunchy-cli download --output-specials -o "Special EP - {title}" https://www.crunchyroll.com/watch/GY8D975JY/veldoras-journal + $ crunchy-cli download --output-specials "Special EP - {title}" https://www.crunchyroll.com/watch/GY8D975JY/veldoras-journal ``` Default is the template, set by the `-o` / `--output` flag. See the [Template Options section](#output-template-options) below for more options. -- Resolution +- 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...). + + ```shell + $ crunchy-cli download --universal-output -o https://www.crunchyroll.com/watch/G7PU4XD48/tales-veldoras-journal-2 + ``` + +- Resolution The resolution for videos can be set via the `-r` / `--resolution` flag. @@ -293,17 +295,26 @@ The `download` command lets you download episodes with a specific audio language Default is `best`. -- FFmpeg Preset +- 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. + + ```shell + $ crunchy-cli download --language-tagging ietf https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome + ``` + +- 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`. If you need more specific ffmpeg customizations you could either convert the output file manually or use ffmpeg output arguments as value for this flag. ```shell - $ crunchy-cli downlaod --ffmpeg-preset av1-lossless https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome + $ 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`. @@ -311,7 +322,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. @@ -319,7 +330,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. @@ -327,7 +338,16 @@ 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] ``` -- Yes +- 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. + + ```shell + $ crunchy-cli download --include-chapters https://www.crunchyroll.com/watch/G0DUND0K2/the-journeys-end + ``` + +- 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. @@ -338,7 +358,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. @@ -346,7 +366,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. @@ -374,7 +394,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. @@ -384,7 +404,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. @@ -394,7 +414,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. @@ -405,18 +425,26 @@ 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. ```shell - $ crunchy-cli archive --output-specials -o "Special EP - {title}" https://www.crunchyroll.com/watch/GY8D975JY/veldoras-journal + $ crunchy-cli archive --output-specials "Special EP - {title}" https://www.crunchyroll.com/watch/GY8D975JY/veldoras-journal ``` Default is the template, set by the `-o` / `--output` flag. See the [Template Options section](#output-template-options) below for more options. -- Resolution +- 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...). + + ```shell + $ crunchy-cli archive --universal-output -o https://www.crunchyroll.com/watch/G7PU4XD48/tales-veldoras-journal-2 + ``` + +- Resolution The resolution for videos can be set via the `-r` / `--resolution` flag. @@ -426,13 +454,13 @@ The `archive` command lets you download episodes with multiple audios and subtit Default is `best`. -- Merge behavior +- 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. - 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 @@ -441,7 +469,48 @@ The `archive` command lets you download episodes with multiple audios and subtit Default is `auto`. -- FFmpeg Preset +- 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-time-tolerance` flag that only downloads one video if the length difference is in the given range. + + ```shell + $ crunchy-cli archive -m auto --merge-time-tolerance 100 https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx + ``` + + Default are `200` milliseconds. + +- 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 `--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 + + 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. + + ```shell + $ crunchy-cli archive --language-tagging ietf https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx + ``` + +- 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`. @@ -451,7 +520,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`. @@ -459,7 +528,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**. @@ -469,7 +538,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. @@ -477,7 +546,17 @@ 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 ``` -- Skip existing +- 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. + This flag only works if `--merge` is set to `audio` because chapters cannot be mapped to a specific video steam. + + ```shell + $ crunchy-cli archive --include-chapters https://www.crunchyroll.com/watch/G0DUND0K2/the-journeys-end + ``` + +- 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. @@ -485,7 +564,17 @@ 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 specials +- 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. + This behavior can be changed by the `--skip-existing-method` flag. Valid options are `audio` and `subtitle` (if the file already exists but the audio/subtitle are less from what should be downloaded, the episode gets downloaded and the file overwritten). + + ```shell + $ crunchy-cli archive --skip-existing-method audio --skip-existing-method video https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx + ``` + +- Skip specials If you doesn't want to download special episodes, use the `--skip-specials` flag to skip the download of them. @@ -493,7 +582,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. @@ -504,7 +593,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. @@ -517,6 +606,10 @@ The `archive` command lets you download episodes with multiple audios and subtit ### Search +The `search` command is a powerful tool to query the Crunchyroll library. +It behaves like the regular search on the website but is able to further process the results and return everything it can find, from the series title down to the raw stream url. +_Using this command with the `--anonymous` flag or a non-premium account may return incomplete results._ + **Supported urls/input** - Single episode (with [episode filtering](#episode-filtering)) @@ -534,7 +627,7 @@ The `archive` command lets you download episodes with multiple audios and subtit **Options** -- Audio +- Audio Set the audio language to search via the `--audio` flag. Can be used multiple times. @@ -544,7 +637,7 @@ The `archive` command lets you download episodes with multiple audios and subtit 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. diff --git a/build.rs b/build.rs index 5b464c4..313cb6d 100644 --- a/build.rs +++ b/build.rs @@ -19,13 +19,6 @@ fn main() -> std::io::Result<()> { println!("cargo:warning=Multiple tls backends are activated (through the '*-tls' features). Consider to activate only one as it is not possible to change the backend during runtime. The active backend for this build will be '{}'.", active_tls_backend) } - if cfg!(feature = "openssl") { - println!("cargo:warning=The 'openssl' feature is deprecated and will be removed in a future version. Use the 'openssl-tls' feature instead.") - } - if cfg!(feature = "openssl-static") { - println!("cargo:warning=The 'openssl-static' feature is deprecated and will be removed in a future version. Use the 'openssl-tls-static' feature instead.") - } - // note that we're using an anti-pattern here / violate the rust conventions. build script are // not supposed to write outside of 'OUT_DIR'. to have the generated files in the build "root" // (the same directory where the output binary lives) is much simpler than in 'OUT_DIR' since diff --git a/crunchy-cli-core/Cargo.toml b/crunchy-cli-core/Cargo.toml index 510e000..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.2.2" +version = "3.6.7" edition = "2021" license = "MIT" @@ -14,35 +14,38 @@ openssl-tls-static = ["reqwest/native-tls", "reqwest/native-tls-alpn", "reqwest/ [dependencies] anyhow = "1.0" async-speed-limit = "0.4" -clap = { version = "4.4", features = ["derive", "string"] } +clap = { version = "4.5", features = ["derive", "string"] } chrono = "0.4" -crunchyroll-rs = { version = "0.8.2", features = ["dash-stream", "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" 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", features = ["socks", "stream"] } +rsubs-lib = "~0.3.2" +rusty-chromaprint = "0.2" serde = "1.0" serde_json = "1.0" serde_plain = "1.0" -shlex = "1.2" +shlex = "1.3" sys-locale = "0.3" -tempfile = "3.9" -tokio = { version = "1.35", features = ["io-util", "macros", "net", "rt-multi-thread", "time"] } +tempfile = "3.10" +time = "0.3" +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.6", optional = true } +rustls-native-certs = { version = "0.7", optional = true } [target.'cfg(not(target_os = "windows"))'.dependencies] -nix = { version = "0.27", features = ["fs"] } +nix = { version = "0.28", features = ["fs"] } [build-dependencies] chrono = "0.4" 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={}", diff --git a/crunchy-cli-core/src/archive/command.rs b/crunchy-cli-core/src/archive/command.rs index 17f21a1..0d1b3a4 100644 --- a/crunchy-cli-core/src/archive/command.rs +++ b/crunchy-cli-core/src/archive/command.rs @@ -1,14 +1,15 @@ -use crate::archive::filter::ArchiveFilter; use crate::utils::context::Context; -use crate::utils::download::{DownloadBuilder, DownloadFormat, MergeBehavior}; +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; +use crate::utils::locale::{all_locale_in_locales, 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; @@ -16,8 +17,12 @@ use chrono::Duration; use crunchyroll_rs::media::{Resolution, Subtitle}; use crunchyroll_rs::Locale; use log::{debug, warn}; -use std::collections::HashMap; -use std::path::PathBuf; +use regex::Regex; +use std::fmt::{Display, Formatter}; +use std::iter::zip; +use std::ops::Sub; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; #[derive(Clone, Debug, clap::Parser)] #[clap(about = "Archive a video")] @@ -26,15 +31,19 @@ pub struct Archive { #[arg(help = format!("Audio languages. Can be used multiple times. \ Available languages are: {}", Locale::all().into_iter().map(|l| l.to_string()).collect::>().join(", ")))] #[arg(long_help = format!("Audio languages. Can be used multiple times. \ - Available languages are:\n {}", Locale::all().into_iter().map(|l| format!("{:<6} → {}", l.to_string(), l.to_human_readable())).collect::>().join("\n ")))] + Available languages are:\n {}\nIETF tagged language codes for the shown available locales can be used too", Locale::all().into_iter().map(|l| format!("{:<6} → {}", l.to_string(), l.to_human_readable())).collect::>().join("\n ")))] #[arg(short, long, default_values_t = vec![Locale::ja_JP, crate::utils::locale::system_locale()])] pub(crate) audio: Vec, + #[arg(skip)] + output_audio_locales: Vec, #[arg(help = format!("Subtitle languages. Can be used multiple times. \ Available languages are: {}", Locale::all().into_iter().map(|l| l.to_string()).collect::>().join(", ")))] #[arg(long_help = format!("Subtitle languages. Can be used multiple times. \ - Available languages are: {}", Locale::all().into_iter().map(|l| l.to_string()).collect::>().join(", ")))] + Available languages are: {}\nIETF tagged language codes for the shown available locales can be used too", Locale::all().into_iter().map(|l| l.to_string()).collect::>().join(", ")))] #[arg(short, long, default_values_t = Locale::all())] pub(crate) subtitle: Vec, + #[arg(skip)] + output_subtitle_locales: Vec, #[arg(help = "Name of the output file")] #[arg(long_help = "Name of the output file. \ @@ -64,6 +73,11 @@ pub struct Archive { #[arg(long)] pub(crate) output_specials: Option, + #[arg(help = "Sanitize the output file for use with all operating systems. \ + This option only affects template options and not static characters.")] + #[arg(long, default_value_t = false)] + pub(crate) universal_output: bool, + #[arg(help = "Video resolution")] #[arg(long_help = "The video resolution. \ Can either be specified via the pixels (e.g. 1920x1080), the abbreviation for pixels (e.g. 1080p) or 'common-use' words (e.g. best). \ @@ -75,16 +89,43 @@ 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' 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 = "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) 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) merge_sync_precision: u32, + + #[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')" + )] + #[arg(long)] + #[arg(value_parser = LanguageTagging::parse)] + pub(crate) language_tagging: Option, #[arg(help = format!("Presets for converting the video to a specific coding format. \ Available presets: \n {}", FFmpegPreset::available_matches_human_readable().join("\n ")))] @@ -113,10 +154,35 @@ pub struct Archive { #[arg(help = "Include fonts in the downloaded file")] #[arg(long)] pub(crate) include_fonts: bool, + #[arg( + help = "Includes chapters (e.g. intro, credits, ...). Only works if `--merge` is set to 'audio'" + )] + #[arg( + long_help = "Includes chapters (e.g. intro, credits, ...). . Only works if `--merge` is set to 'audio'. \ + Because chapters are essentially only special timeframes in episodes like the intro, most of the video timeline isn't covered by a chapter. + These \"gaps\" are filled with an 'Episode' chapter because many video players are ignore those gaps and just assume that a chapter ends when the next chapter start is reached, even if a specific end-time is set. + Also chapters aren't always available, so in this case, just a big 'Episode' chapter from start to end will be created" + )] + #[arg(long, default_value_t = false)] + pub(crate) include_chapters: bool, - #[arg(help = "Skip files which are already existing")] + #[arg(help = "Omit closed caption subtitles in the downloaded file")] + #[arg(long, default_value_t = false)] + pub(crate) no_closed_caption: bool, + + #[arg(help = "Skip files which are already existing by their name")] #[arg(long, default_value_t = false)] pub(crate) skip_existing: bool, + #[arg( + help = "Only works in combination with `--skip-existing`. Sets the method how already existing files should be skipped. Valid methods are 'audio' and 'subtitle'" + )] + #[arg(long_help = "Only works in combination with `--skip-existing`. \ + By default, already existing files are determined by their name and the download of the corresponding episode is skipped. \ + With this flag you can modify this behavior. \ + Valid options are 'audio' and 'subtitle' (if the file already exists but the audio/subtitle are less from what should be downloaded, the episode gets downloaded and the file overwritten).")] + #[arg(long, default_values_t = SkipExistingMethod::default())] + #[arg(value_parser = SkipExistingMethod::parse)] + pub(crate) skip_existing_method: Vec, #[arg(help = "Skip special episodes")] #[arg(long, default_value_t = false)] pub(crate) skip_specials: bool, @@ -160,22 +226,48 @@ impl Execute for Archive { } } - if self.output.contains("{resolution}") - || self - .output_specials - .as_ref() - .map_or(false, |os| os.contains("{resolution}")) + if self.include_chapters + && !matches!(self.merge, MergeBehavior::Sync) + && !matches!(self.merge, MergeBehavior::Audio) { - warn!("The '{{resolution}}' format option is deprecated and will be removed in a future version. Please use '{{width}}' and '{{height}}' instead") + 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()); + if let Some(language_tagging) = &self.language_tagging { + self.audio = resolve_locales(&self.audio); + self.subtitle = resolve_locales(&self.subtitle); + self.output_audio_locales = language_tagging.convert_locales(&self.audio); + self.output_subtitle_locales = language_tagging.convert_locales(&self.subtitle); + } else { + self.output_audio_locales = self + .audio + .clone() + .into_iter() + .map(|l| l.to_string()) + .collect(); + self.output_subtitle_locales = self + .subtitle + .clone() + .into_iter() + .map(|l| l.to_string()) + .collect(); + } + Ok(()) } 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() { @@ -191,10 +283,55 @@ 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 = Filter::new( + url_filter, + 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, + ) + .visit(media_collection) + .await?; if single_format_collection.is_empty() { progress_handler.stop(format!("Skipping url {} (no matching videos found)", i + 1)); @@ -204,15 +341,31 @@ impl Execute for Archive { single_format_collection.full_visual_output(); - let download_builder = DownloadBuilder::new(ctx.crunchy.client()) - .default_subtitle(self.default_subtitle.clone()) - .download_fonts(self.include_fonts) - .ffmpeg_preset(self.ffmpeg_preset.clone().unwrap_or_default()) - .ffmpeg_threads(self.ffmpeg_threads) - .output_format(Some("matroska".to_string())) - .audio_sort(Some(self.audio.clone())) - .subtitle_sort(Some(self.subtitle.clone())) - .threads(self.threads); + let download_builder = + DownloadBuilder::new(ctx.client.clone(), ctx.rate_limiter.clone()) + .default_subtitle(self.default_subtitle.clone()) + .download_fonts(self.include_fonts) + .ffmpeg_preset(self.ffmpeg_preset.clone().unwrap_or_default()) + .ffmpeg_threads(self.ffmpeg_threads) + .output_format(Some("matroska".to_string())) + .audio_sort(Some(self.audio.clone())) + .subtitle_sort(Some(self.subtitle.clone())) + .no_closed_caption(self.no_closed_caption) + .merge_sync_tolerance(match self.merge { + MergeBehavior::Sync => Some(self.merge_sync_tolerance), + _ => None, + }) + .merge_sync_precision(match self.merge { + MergeBehavior::Sync => Some(self.merge_sync_precision), + _ => None, + }) + .threads(self.threads) + .audio_locale_output_map( + zip(self.audio.clone(), self.output_audio_locales.clone()).collect(), + ) + .subtitle_locale_output_map( + zip(self.subtitle.clone(), self.output_subtitle_locales.clone()).collect(), + ); for single_formats in single_format_collection.into_iter() { let (download_formats, mut format) = get_format(&self, &single_formats).await?; @@ -227,18 +380,74 @@ impl Execute for Archive { self.output_specials .as_ref() .map_or((&self.output).into(), |so| so.into()), + self.universal_output, + self.language_tagging.as_ref(), ) } else { - format.format_path((&self.output).into()) + format.format_path( + (&self.output).into(), + self.universal_output, + self.language_tagging.as_ref(), + ) }; - let (path, changed) = free_file(formatted_path.clone()); + let (mut path, changed) = free_file(formatted_path.clone()); if changed && self.skip_existing { - debug!( - "Skipping already existing file '{}'", - formatted_path.to_string_lossy() - ); - continue; + let mut skip = true; + + if !self.skip_existing_method.is_empty() { + if let Some((audio_locales, subtitle_locales)) = + get_video_streams(&formatted_path)? + { + let method_audio = self + .skip_existing_method + .contains(&SkipExistingMethod::Audio); + let method_subtitle = self + .skip_existing_method + .contains(&SkipExistingMethod::Subtitle); + + let audio_differ = if method_audio { + format + .locales + .iter() + .any(|(a, _)| !audio_locales.contains(a)) + } else { + false + }; + let subtitle_differ = if method_subtitle { + format + .locales + .clone() + .into_iter() + .flat_map(|(a, mut s)| { + // remove the closed caption if the flag is given to omit + // closed captions + if self.no_closed_caption && a != Locale::ja_JP { + s.retain(|l| l != &a) + } + s + }) + .any(|l| !subtitle_locales.contains(&l)) + } else { + false + }; + + if (method_audio && audio_differ) + || (method_subtitle && subtitle_differ) + { + skip = false; + path.clone_from(&formatted_path) + } + } + } + + if skip { + debug!( + "Skipping already existing file '{}'", + formatted_path.to_string_lossy() + ); + continue; + } } format.locales.sort_by(|(a, _), (b, _)| { @@ -266,6 +475,36 @@ impl Execute for Archive { } } +#[derive(Clone, Debug, Eq, PartialEq)] +pub(crate) enum SkipExistingMethod { + Audio, + Subtitle, +} + +impl Display for SkipExistingMethod { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + let value = match self { + SkipExistingMethod::Audio => "audio", + SkipExistingMethod::Subtitle => "subtitle", + }; + write!(f, "{}", value) + } +} + +impl SkipExistingMethod { + fn parse(s: &str) -> Result { + match s.to_lowercase().as_str() { + "audio" => Ok(Self::Audio), + "subtitle" => Ok(Self::Subtitle), + _ => Err(format!("invalid skip existing method '{}'", s)), + } + } + + fn default<'a>() -> &'a [Self] { + &[] + } +} + async fn get_format( archive: &Archive, single_formats: &Vec, @@ -276,7 +515,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!( @@ -300,24 +539,29 @@ async fn get_format( let subtitles: Vec<(Subtitle, bool)> = archive .subtitle .iter() - .filter_map(|s| { - stream - .subtitles - .get(s) - .cloned() - // the subtitle is probably not cc if the audio is japanese or more than one - // subtitle exists for this stream - .map(|l| { - ( - l, - single_format.audio == Locale::ja_JP || stream.subtitles.len() > 1, - ) - }) + .flat_map(|s| { + 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 }) .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![]; @@ -329,6 +573,7 @@ async fn get_format( video: (video, single_format.audio.clone()), audios: vec![(audio, single_format.audio.clone())], subtitles, + metadata: DownloadFormatMetadata { skip_events: None }, }) } } @@ -347,28 +592,62 @@ async fn get_format( .iter() .flat_map(|(_, _, _, subtitles)| subtitles.clone()) .collect(), + metadata: DownloadFormatMetadata { + skip_events: if archive.include_chapters { + format_pairs.first().unwrap().0.skip_events().await? + } else { + None + }, + }, }), - MergeBehavior::Auto => { - let mut d_formats: HashMap = HashMap::new(); + MergeBehavior::Auto | MergeBehavior::Sync => { + let mut d_formats: Vec<(Duration, DownloadFormat)> = vec![]; for (single_format, video, audio, subtitles) in format_pairs { - if let Some(d_format) = d_formats.get_mut(&single_format.duration) { - d_format.audios.push((audio, single_format.audio.clone())); - d_format.subtitles.extend(subtitles) - } else { - d_formats.insert( - single_format.duration, - DownloadFormat { - video: (video, single_format.audio.clone()), - audios: vec![(audio, single_format.audio.clone())], - subtitles, - }, - ); - } + let closest_format = d_formats.iter_mut().min_by(|(x, _), (y, _)| { + x.sub(single_format.duration) + .abs() + .cmp(&y.sub(single_format.duration).abs()) + }); + + match closest_format { + Some(closest_format) + if closest_format + .0 + .sub(single_format.duration) + .abs() + .num_milliseconds() + < archive.merge_time_tolerance.into() => + { + // If less than `audio_error` apart, use same audio. + closest_format + .1 + .audios + .push((audio, single_format.audio.clone())); + closest_format.1.subtitles.extend(subtitles); + } + _ => { + d_formats.push(( + single_format.duration, + DownloadFormat { + video: (video, single_format.audio.clone()), + audios: vec![(audio, single_format.audio.clone())], + subtitles, + metadata: DownloadFormatMetadata { + skip_events: if archive.include_chapters { + single_format.skip_events().await? + } else { + None + }, + }, + }, + )); + } + }; } - for d_format in d_formats.into_values() { - download_formats.push(d_format) + for (_, d_format) in d_formats.into_iter() { + download_formats.push(d_format); } } } @@ -378,3 +657,36 @@ async fn get_format( Format::from_single_formats(single_format_to_format_pairs), )) } + +fn get_video_streams(path: &Path) -> Result, Vec)>> { + let video_streams = + Regex::new(r"(?m)Stream\s#\d+:\d+\((?P.+)\):\s(?P(Audio|Subtitle))") + .unwrap(); + + let ffmpeg = Command::new("ffmpeg") + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .arg("-hide_banner") + .args(["-i", &path.to_string_lossy()]) + .output()?; + let ffmpeg_output = String::from_utf8(ffmpeg.stderr)?; + + let mut audio = vec![]; + let mut subtitle = vec![]; + for cap in video_streams.captures_iter(&ffmpeg_output) { + let locale = cap.name("language").unwrap().as_str(); + let type_ = cap.name("type").unwrap().as_str(); + + match type_ { + "Audio" => audio.push(Locale::from(locale.to_string())), + "Subtitle" => subtitle.push(Locale::from(locale.to_string())), + _ => unreachable!(), + } + } + + if audio.is_empty() && subtitle.is_empty() { + Ok(None) + } else { + Ok(Some((audio, subtitle))) + } +} diff --git a/crunchy-cli-core/src/archive/filter.rs b/crunchy-cli-core/src/archive/filter.rs deleted file mode 100644 index 2a47738..0000000 --- a/crunchy-cli-core/src/archive/filter.rs +++ /dev/null @@ -1,437 +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}; - -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, - season_sorting: Vec, - visited: Visited, -} - -impl ArchiveFilter { - pub(crate) fn new( - url_filter: UrlFilter, - archive: Archive, - interactive_input: bool, - skip_special: bool, - ) -> Self { - Self { - url_filter, - archive, - interactive_input, - skip_special, - season_episodes: HashMap::new(), - season_subtitles_missing: 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 - .get(0) - .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())) - } - - 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 30fea44..8e3794f 100644 --- a/crunchy-cli-core/src/download/command.rs +++ b/crunchy-cli-core/src/download/command.rs @@ -1,19 +1,20 @@ -use crate::download::filter::DownloadFilter; use crate::utils::context::Context; -use crate::utils::download::{DownloadBuilder, DownloadFormat}; +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; 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; 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; #[derive(Clone, Debug, clap::Parser)] @@ -23,14 +24,18 @@ pub struct Download { #[arg(help = format!("Audio language. Can only be used if the provided url(s) point to a series. \ Available languages are: {}", Locale::all().into_iter().map(|l| l.to_string()).collect::>().join(", ")))] #[arg(long_help = format!("Audio language. Can only be used if the provided url(s) point to a series. \ - Available languages are:\n {}", Locale::all().into_iter().map(|l| format!("{:<6} → {}", l.to_string(), l.to_human_readable())).collect::>().join("\n ")))] + Available languages are:\n {}\nIETF tagged language codes for the shown available locales can be used too", Locale::all().into_iter().map(|l| format!("{:<6} → {}", l.to_string(), l.to_human_readable())).collect::>().join("\n ")))] #[arg(short, long, default_value_t = crate::utils::locale::system_locale())] pub(crate) audio: Locale, + #[arg(skip)] + output_audio_locale: String, #[arg(help = format!("Subtitle language. Available languages are: {}", Locale::all().into_iter().map(|l| l.to_string()).collect::>().join(", ")))] #[arg(long_help = format!("Subtitle language. If set, the subtitle will be burned into the video and cannot be disabled. \ - Available languages are: {}", Locale::all().into_iter().map(|l| l.to_string()).collect::>().join(", ")))] + Available languages are: {}\nIETF tagged language codes for the shown available locales can be used too", Locale::all().into_iter().map(|l| l.to_string()).collect::>().join(", ")))] #[arg(short, long)] pub(crate) subtitle: Option, + #[arg(skip)] + output_subtitle_locale: String, #[arg(help = "Name of the output file")] #[arg(long_help = "Name of the output file. \ @@ -60,6 +65,11 @@ pub struct Download { #[arg(long)] pub(crate) output_specials: Option, + #[arg(help = "Sanitize the output file for use with all operating systems. \ + This option only affects template options and not static characters.")] + #[arg(long, default_value_t = false)] + pub(crate) universal_output: bool, + #[arg(help = "Video resolution")] #[arg(long_help = "The video resolution. \ Can either be specified via the pixels (e.g. 1920x1080), the abbreviation for pixels (e.g. 1080p) or 'common-use' words (e.g. best). \ @@ -70,6 +80,18 @@ pub struct Download { #[arg(value_parser = crate::utils::clap::clap_parse_resolution)] pub(crate) resolution: Resolution, + #[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( + 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(value_parser = LanguageTagging::parse)] + pub(crate) language_tagging: Option, + #[arg(help = format!("Presets for converting the video to a specific coding format. \ Available presets: \n {}", FFmpegPreset::available_matches_human_readable().join("\n ")))] #[arg(long_help = format!("Presets for converting the video to a specific coding format. \ @@ -89,13 +111,21 @@ pub struct Download { #[arg(long)] pub(crate) ffmpeg_threads: Option, - #[arg(help = "Skip files which are already existing")] + #[arg(help = "Skip files which are already existing by their name")] #[arg(long, default_value_t = false)] pub(crate) skip_existing: bool, #[arg(help = "Skip special episodes")] #[arg(long, default_value_t = false)] pub(crate) skip_specials: bool, + #[arg(help = "Includes chapters (e.g. intro, credits, ...)")] + #[arg(long_help = "Includes chapters (e.g. intro, credits, ...). \ + Because chapters are essentially only special timeframes in episodes like the intro, most of the video timeline isn't covered by a chapter. + These \"gaps\" are filled with an 'Episode' chapter because many video players are ignore those gaps and just assume that a chapter ends when the next chapter start is reached, even if a specific end-time is set. + Also chapters aren't always available, so in this case, just a big 'Episode' chapter from start to end will be created")] + #[arg(long, default_value_t = false)] + pub(crate) include_chapters: bool, + #[arg(help = "Skip any interactive input")] #[arg(short, long, default_value_t = false)] pub(crate) yes: bool, @@ -156,19 +186,35 @@ impl Execute for Download { } } - if self.output.contains("{resolution}") - || self - .output_specials + if let Some(language_tagging) = &self.language_tagging { + self.audio = resolve_locales(&[self.audio.clone()]).remove(0); + self.subtitle = self + .subtitle .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") + .map(|s| resolve_locales(&[s.clone()]).remove(0)); + self.output_audio_locale = language_tagging.for_locale(&self.audio); + self.output_subtitle_locale = self + .subtitle + .as_ref() + .map(|s| language_tagging.for_locale(s)) + .unwrap_or_default() + } else { + self.output_audio_locale = self.audio.to_string(); + self.output_subtitle_locale = self + .subtitle + .as_ref() + .map(|s| s.to_string()) + .unwrap_or_default(); } Ok(()) } 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( @@ -203,10 +249,59 @@ 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 = Filter::new( + url_filter, + 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, + ) + .visit(media_collection) + .await?; if single_format_collection.is_empty() { progress_handler.stop(format!("Skipping url {} (no matching videos found)", i + 1)); @@ -216,17 +311,27 @@ impl Execute for Download { single_format_collection.full_visual_output(); - let download_builder = DownloadBuilder::new(ctx.crunchy.client()) - .default_subtitle(self.subtitle.clone()) - .force_hardsub(self.force_hardsub) - .output_format(if is_special_file(&self.output) || self.output == "-" { - Some("mpegts".to_string()) - } else { - None - }) - .ffmpeg_preset(self.ffmpeg_preset.clone().unwrap_or_default()) - .ffmpeg_threads(self.ffmpeg_threads) - .threads(self.threads); + let download_builder = + DownloadBuilder::new(ctx.client.clone(), ctx.rate_limiter.clone()) + .default_subtitle(self.subtitle.clone()) + .force_hardsub(self.force_hardsub) + .output_format(if is_special_file(&self.output) || self.output == "-" { + Some("mpegts".to_string()) + } else { + None + }) + .ffmpeg_preset(self.ffmpeg_preset.clone().unwrap_or_default()) + .ffmpeg_threads(self.ffmpeg_threads) + .threads(self.threads) + .audio_locale_output_map(HashMap::from([( + self.audio.clone(), + self.output_audio_locale.clone(), + )])) + .subtitle_locale_output_map( + self.subtitle.as_ref().map_or(HashMap::new(), |s| { + HashMap::from([(s.clone(), self.output_subtitle_locale.clone())]) + }), + ); for mut single_formats in single_format_collection.into_iter() { // the vec contains always only one item @@ -253,9 +358,15 @@ impl Execute for Download { self.output_specials .as_ref() .map_or((&self.output).into(), |so| so.into()), + self.universal_output, + self.language_tagging.as_ref(), ) } else { - format.format_path((&self.output).into()) + format.format_path( + (&self.output).into(), + self.universal_output, + self.language_tagging.as_ref(), + ) }; let (path, changed) = free_file(formatted_path.clone()); @@ -283,7 +394,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 { @@ -316,7 +427,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() + 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 }; @@ -327,9 +451,16 @@ 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 { + skip_events: if download.include_chapters { + single_format.skip_events().await? + } else { + None + }, + }, }; let mut format = Format::from_single_formats(vec![( single_format.clone(), @@ -337,7 +468,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, )] }), )]); @@ -346,5 +477,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/download/filter.rs b/crunchy-cli-core/src/download/filter.rs deleted file mode 100644 index 5076a33..0000000 --- a/crunchy-cli-core/src/download/filter.rs +++ /dev/null @@ -1,283 +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; - -pub(crate) struct DownloadFilter { - url_filter: UrlFilter, - download: Download, - interactive_input: bool, - skip_special: bool, - season_episodes: HashMap>, - season_subtitles_missing: Vec, - season_visited: bool, -} - -impl DownloadFilter { - pub(crate) fn new( - url_filter: UrlFilter, - download: Download, - interactive_input: bool, - skip_special: bool, - ) -> Self { - Self { - url_filter, - download, - interactive_input, - skip_special, - season_episodes: HashMap::new(), - season_subtitles_missing: 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); - } - } - - 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/lib.rs b/crunchy-cli-core/src/lib.rs index f1d659a..1c180e8 100644 --- a/crunchy-cli-core/src/lib.rs +++ b/crunchy-cli-core/src/lib.rs @@ -8,7 +8,7 @@ use crunchyroll_rs::crunchyroll::CrunchyrollBuilder; use crunchyroll_rs::error::Error; use crunchyroll_rs::{Crunchyroll, Locale}; use log::{debug, error, warn, LevelFilter}; -use reqwest::Proxy; +use reqwest::{Client, Proxy}; use std::{env, fs}; mod archive; @@ -36,7 +36,7 @@ trait Execute { #[clap(name = "crunchy-cli")] pub struct Cli { #[clap(flatten)] - verbosity: Option, + verbosity: Verbosity, #[arg( help = "Overwrite the language in which results are returned. Default is your system language" @@ -44,9 +44,12 @@ pub struct Cli { #[arg(global = true, long)] lang: Option, - #[arg(help = "Enable experimental fixes which may resolve some unexpected errors")] + #[arg( + help = "Enable experimental fixes which may resolve some unexpected errors. Generally not recommended as this flag may crash the program completely" + )] #[arg( long_help = "Enable experimental fixes which may resolve some unexpected errors. \ + It is not recommended to use this this flag regularly, it might cause unexpected errors which may crash the program completely. \ If everything works as intended this option isn't needed, but sometimes Crunchyroll mislabels \ the audio of a series/season or episode or returns a wrong season number. This is when using this option might help to solve the issue" )] @@ -58,9 +61,10 @@ pub struct Cli { #[arg(help = "Use a proxy to route all traffic through")] #[arg(long_help = "Use a proxy to route all traffic through. \ - Make sure that the 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")] - #[arg(global = true, long, value_parser = crate::utils::clap::clap_parse_proxy)] - proxy: Option, + Make sure that the 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. \ + Besides specifying a simple url, you also can partially control where a proxy should be used: ':' only proxies api requests, ':' only proxies download traffic, ':' proxies api requests through the first url and download traffic through the second url")] + #[arg(global = true, long, value_parser = crate::utils::clap::clap_parse_proxies)] + proxy: Option<(Option, Option)>, #[arg(help = "Use custom user agent")] #[arg(global = true, long)] @@ -113,16 +117,16 @@ struct Verbosity { quiet: bool, } -pub async fn cli_entrypoint() { - let mut cli: Cli = Cli::parse(); +pub async fn main(args: &[String]) { + let mut cli: Cli = Cli::parse_from(args); - if let Some(verbosity) = &cli.verbosity { - if verbosity.verbose as u8 + verbosity.quiet as u8 > 1 { + if cli.verbosity.verbose || cli.verbosity.quiet { + if cli.verbosity.verbose && cli.verbosity.quiet { eprintln!("Output cannot be verbose ('-v') and quiet ('-q') at the same time"); std::process::exit(1) - } else if verbosity.verbose { + } else if cli.verbosity.verbose { CliLogger::init(LevelFilter::Debug).unwrap() - } else if verbosity.quiet { + } else if cli.verbosity.quiet { CliLogger::init(LevelFilter::Error).unwrap() } } else { @@ -134,14 +138,14 @@ pub async fn cli_entrypoint() { match &mut cli.command { Command::Archive(archive) => { // prevent interactive select to be shown when output should be quiet - if cli.verbosity.is_some() && cli.verbosity.as_ref().unwrap().quiet { + if cli.verbosity.quiet { archive.yes = true; } pre_check_executor(archive).await } Command::Download(download) => { // prevent interactive select to be shown when output should be quiet - if cli.verbosity.is_some() && cli.verbosity.as_ref().unwrap().quiet { + if cli.verbosity.quiet { download.yes = true; } pre_check_executor(download).await @@ -180,16 +184,29 @@ pub async fn cli_entrypoint() { .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" + } + ) + } } } } @@ -221,8 +238,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) @@ -235,11 +250,37 @@ async fn execute_executor(executor: impl Execute, ctx: Context) { } async fn create_ctx(cli: &mut Cli) -> Result { - let crunchy = crunchyroll_session(cli).await?; - Ok(Context { crunchy }) + let crunchy_client = reqwest_client( + cli.proxy.as_ref().and_then(|p| p.0.clone()), + cli.user_agent.clone(), + ); + let internal_client = reqwest_client( + cli.proxy.as_ref().and_then(|p| p.1.clone()), + cli.user_agent.clone(), + ); + + let crunchy = crunchyroll_session( + cli, + crunchy_client.clone(), + cli.speed_limit + .map(|l| RateLimiterService::new(l, crunchy_client)), + ) + .await?; + + Ok(Context { + crunchy, + client: internal_client.clone(), + rate_limiter: cli + .speed_limit + .map(|l| RateLimiterService::new(l, internal_client)), + }) } -async fn crunchyroll_session(cli: &mut Cli) -> Result { +async fn crunchyroll_session( + cli: &mut Cli, + client: Client, + rate_limiter: Option, +) -> Result { let supported_langs = vec![ Locale::ar_ME, Locale::de_DE, @@ -273,33 +314,6 @@ async fn crunchyroll_session(cli: &mut Cli) -> Result { lang }; - let client = { - let mut builder = CrunchyrollBuilder::predefined_client_builder(); - if let Some(p) = &cli.proxy { - builder = builder.proxy(p.clone()) - } - if let Some(ua) = &cli.user_agent { - builder = builder.user_agent(ua) - } - - #[cfg(any(feature = "openssl-tls", feature = "openssl-tls-static"))] - let client = { - let mut builder = builder.use_native_tls().tls_built_in_root_certs(false); - - for certificate in rustls_native_certs::load_native_certs().unwrap() { - builder = builder.add_root_certificate( - reqwest::Certificate::from_der(certificate.0.as_slice()).unwrap(), - ) - } - - builder.build().unwrap() - }; - #[cfg(not(any(feature = "openssl-tls", feature = "openssl-tls-static")))] - let client = builder.build().unwrap(); - - client - }; - let mut builder = Crunchyroll::builder() .locale(locale) .client(client.clone()) @@ -308,13 +322,12 @@ async fn crunchyroll_session(cli: &mut Cli) -> Result { if let Command::Download(download) = &cli.command { builder = builder.preferred_audio_locale(download.audio.clone()) } - if let Some(speed_limit) = cli.speed_limit { - builder = builder.middleware(RateLimiterService::new(speed_limit, client)); + if let Some(rate_limiter) = rate_limiter { + 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 { @@ -324,18 +337,28 @@ async fn crunchyroll_session(cli: &mut Cli) -> Result { 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" => return Ok(builder.login_with_etp_rt(token).await?), + "etp_rt" => bail!("The stored login method (etp-rt) isn't supported anymore. Please login again using your credentials"), _ => (), } } 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 { @@ -344,8 +367,6 @@ async fn crunchyroll_session(cli: &mut Cli) -> Result { } 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 { @@ -356,3 +377,29 @@ async fn crunchyroll_session(cli: &mut Cli) -> Result { Ok(crunchy) } + +fn reqwest_client(proxy: Option, user_agent: Option) -> Client { + let mut builder = CrunchyrollBuilder::predefined_client_builder(); + if let Some(p) = proxy { + builder = builder.proxy(p) + } + if let Some(ua) = user_agent { + builder = builder.user_agent(ua) + } + + #[cfg(any(feature = "openssl-tls", feature = "openssl-tls-static"))] + let client = { + let mut builder = builder.use_native_tls().tls_built_in_root_certs(false); + + for certificate in rustls_native_certs::load_native_certs().unwrap() { + builder = + builder.add_root_certificate(reqwest::Certificate::from_der(&certificate).unwrap()) + } + + builder.build().unwrap() + }; + #[cfg(not(any(feature = "openssl-tls", feature = "openssl-tls-static")))] + let client = builder.build().unwrap(); + + client +} 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, diff --git a/crunchy-cli-core/src/search/command.rs b/crunchy-cli-core/src/search/command.rs index c357ab4..8032bed 100644 --- a/crunchy-cli-core/src/search/command.rs +++ b/crunchy-cli-core/src/search/command.rs @@ -7,6 +7,8 @@ use anyhow::{bail, Result}; 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")] @@ -86,13 +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.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.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, @@ -102,6 +107,14 @@ pub struct Search { impl Execute for Search { async fn execute(self, ctx: Context) -> Result<()> { + if !ctx.crunchy.premium().await { + 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], @@ -140,13 +153,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 156bd95..cf3c5bc 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 { @@ -163,37 +165,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: false, } } } @@ -213,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, @@ -224,6 +225,7 @@ enum Scope { Concert, Stream, Subtitle, + Account, } macro_rules! must_match_if_true { @@ -239,23 +241,20 @@ 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, 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(); @@ -282,6 +281,7 @@ impl Format { Scope::Concert => FormatConcert Scope::Stream => FormatStream Scope::Subtitle => FormatSubtitle + Scope::Account => FormatAccount ); for capture in scope_regex.captures_iter(&input) { @@ -299,6 +299,7 @@ impl Format { "concert" => Scope::Concert, "stream" => Scope::Stream, "subtitle" => Scope::Subtitle, + "account" => Scope::Account, _ => bail!("'{}.{}' is not a valid keyword", scope, field), }; @@ -324,6 +325,7 @@ impl Format { pattern_count, input, filter_options, + crunchyroll, }) } @@ -338,6 +340,7 @@ impl Format { Scope::Episode, Scope::Stream, Scope::Subtitle, + Scope::Account, ])?; self.parse_series(media_collection).await @@ -348,17 +351,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 } @@ -371,6 +385,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![]; @@ -398,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 @@ -412,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 @@ -441,7 +472,9 @@ impl Format { if !stream_empty { for (_, episodes) in tree.iter_mut() { for (episode, streams) in episodes { - streams.push(episode.stream().await?) + let stream = episode.stream_maybe_without_drm().await?; + stream.clone().invalidate().await?; + streams.push(stream) } } } else { @@ -453,6 +486,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)); @@ -464,6 +502,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), @@ -510,7 +549,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 +587,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 +609,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/clap.rs b/crunchy-cli-core/src/utils/clap.rs index 37a34d3..35de71f 100644 --- a/crunchy-cli-core/src/utils/clap.rs +++ b/crunchy-cli-core/src/utils/clap.rs @@ -1,13 +1,46 @@ use crate::utils::parse::parse_resolution; use crunchyroll_rs::media::Resolution; +use regex::Regex; use reqwest::Proxy; pub fn clap_parse_resolution(s: &str) -> Result { parse_resolution(s.to_string()).map_err(|e| e.to_string()) } -pub fn clap_parse_proxy(s: &str) -> Result { - Proxy::all(s).map_err(|e| e.to_string()) +pub fn clap_parse_proxies(s: &str) -> Result<(Option, Option), String> { + let double_proxy_regex = + Regex::new(r"^(?P(https?|socks5h?)://.+):(?P(https?|socks5h?)://.+)$") + .unwrap(); + + if let Some(capture) = double_proxy_regex.captures(s) { + // checks if the input is formatted like 'https://example.com:socks5://examples.com' and + // splits the string into 2 separate proxies at the middle colon + + let first = capture.name("first").unwrap().as_str(); + let second = capture.name("second").unwrap().as_str(); + Ok(( + Some(Proxy::all(first).map_err(|e| format!("first proxy: {e}"))?), + Some(Proxy::all(second).map_err(|e| format!("second proxy: {e}"))?), + )) + } else if s.starts_with(':') { + // checks if the input is formatted like ':https://example.com' and returns a proxy on the + // second tuple position + Ok(( + None, + Some(Proxy::all(s.trim_start_matches(':')).map_err(|e| e.to_string())?), + )) + } else if s.ends_with(':') { + // checks if the input is formatted like 'https://example.com:' and returns a proxy on the + // first tuple position + Ok(( + Some(Proxy::all(s.trim_end_matches(':')).map_err(|e| e.to_string())?), + None, + )) + } else { + // returns the same proxy for both tuple positions + let proxy = Proxy::all(s).map_err(|e| e.to_string())?; + Ok((Some(proxy.clone()), Some(proxy))) + } } pub fn clap_parse_speed_limit(s: &str) -> Result { diff --git a/crunchy-cli-core/src/utils/context.rs b/crunchy-cli-core/src/utils/context.rs index f8df024..693174d 100644 --- a/crunchy-cli-core/src/utils/context.rs +++ b/crunchy-cli-core/src/utils/context.rs @@ -1,5 +1,9 @@ +use crate::utils::rate_limit::RateLimiterService; use crunchyroll_rs::Crunchyroll; +use reqwest::Client; pub struct Context { pub crunchy: Crunchyroll, + pub client: Client, + pub rate_limiter: Option, } diff --git a/crunchy-cli-core/src/utils/download.rs b/crunchy-cli-core/src/utils/download.rs index 1b99c30..2e8f321 100644 --- a/crunchy-cli-core/src/utils/download.rs +++ b/crunchy-cli-core/src/utils/download.rs @@ -1,37 +1,45 @@ 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, tempfile}; +use crate::utils::rate_limit::RateLimiterService; +use crate::utils::sync::{sync_audios, SyncAudio}; use anyhow::{bail, Result}; -use chrono::NaiveTime; -use crunchyroll_rs::media::{Subtitle, VariantData, VariantSegment}; +use chrono::{NaiveTime, TimeDelta}; +use crunchyroll_rs::media::{SkipEvents, SkipEventsEvent, StreamData, StreamSegment, Subtitle}; use crunchyroll_rs::Locale; 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; +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::str::FromStr; 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; use tokio::sync::Mutex; use tokio::task::JoinSet; use tokio_util::sync::CancellationToken; +use tower_service::Service; #[derive(Clone, Debug)] pub enum MergeBehavior { Video, Audio, Auto, + Sync, } impl MergeBehavior { @@ -40,6 +48,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)), }) } @@ -48,6 +57,7 @@ impl MergeBehavior { #[derive(Clone, derive_setters::Setters)] pub struct DownloadBuilder { client: Client, + rate_limiter: Option, ffmpeg_preset: FFmpegPreset, default_subtitle: Option, output_format: Option, @@ -55,14 +65,20 @@ pub struct DownloadBuilder { subtitle_sort: Option>, force_hardsub: bool, download_fonts: bool, + no_closed_caption: bool, + merge_sync_tolerance: Option, + merge_sync_precision: Option, threads: usize, ffmpeg_threads: Option, + audio_locale_output_map: HashMap, + subtitle_locale_output_map: HashMap, } impl DownloadBuilder { - pub fn new(client: Client) -> DownloadBuilder { + pub fn new(client: Client, rate_limiter: Option) -> DownloadBuilder { Self { client, + rate_limiter, ffmpeg_preset: FFmpegPreset::default(), default_subtitle: None, output_format: None, @@ -70,14 +86,20 @@ impl DownloadBuilder { subtitle_sort: None, force_hardsub: false, download_fonts: false, + no_closed_caption: false, + merge_sync_tolerance: None, + merge_sync_precision: None, threads: num_cpus::get(), ffmpeg_threads: None, + audio_locale_output_map: HashMap::new(), + subtitle_locale_output_map: HashMap::new(), } } pub fn build(self) -> Downloader { Downloader { client: self.client, + rate_limiter: self.rate_limiter, ffmpeg_preset: self.ffmpeg_preset, default_subtitle: self.default_subtitle, output_format: self.output_format, @@ -86,29 +108,57 @@ impl DownloadBuilder { force_hardsub: self.force_hardsub, download_fonts: self.download_fonts, + no_closed_caption: self.no_closed_caption, + + merge_sync_tolerance: self.merge_sync_tolerance, + merge_sync_precision: self.merge_sync_precision, download_threads: self.threads, ffmpeg_threads: self.ffmpeg_threads, formats: vec![], + + audio_locale_output_map: self.audio_locale_output_map, + subtitle_locale_output_map: self.subtitle_locale_output_map, } } } -struct FFmpegMeta { +struct FFmpegVideoMeta { path: TempPath, - language: Locale, - title: String, + length: TimeDelta, + start_time: Option, +} + +struct FFmpegAudioMeta { + path: TempPath, + locale: Locale, + start_time: Option, + video_idx: usize, +} + +struct FFmpegSubtitleMeta { + path: TempPath, + locale: Locale, + cc: bool, + start_time: Option, + video_idx: usize, } 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, +} + +pub struct DownloadFormatMetadata { + pub skip_events: Option, } pub struct Downloader { client: Client, + rate_limiter: Option, ffmpeg_preset: FFmpegPreset, default_subtitle: Option, @@ -118,11 +168,18 @@ pub struct Downloader { force_hardsub: bool, download_fonts: bool, + no_closed_caption: bool, + + merge_sync_tolerance: Option, + merge_sync_precision: Option, download_threads: usize, ffmpeg_threads: Option, formats: Vec, + + audio_locale_output_map: HashMap, + subtitle_locale_output_map: HashMap, } impl Downloader { @@ -177,13 +234,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 } @@ -191,11 +248,17 @@ 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![]; let mut fonts = vec![]; - let mut max_frames = 0f64; + let mut chapters = None; + let mut max_len = TimeDelta::min_value(); + let mut max_frames = 0; let fmt_space = self .formats .iter() @@ -207,105 +270,233 @@ impl Downloader { .max() .unwrap(); + // downloads all audios 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 + for (stream_data, locale) in &format.audios { + let path = self .download_audio( - variant_data, + stream_data, format!("{:<1$}", format!("Downloading {} audio", locale), fmt_space), ) .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) - }, + raw_audios.push(SyncAudio { + format_id: i, + path, + locale: locale.clone(), + sample_rate: stream_data.sampling_rate().unwrap(), + video_idx: i, }) } - 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(), - ) - .unwrap() - .tick_strings(&["—", "\\", "|", "/", ""]), - ) - .with_finish(ProgressFinish::Abandon); - progress_spinner.enable_steady_tick(Duration::from_millis(100)); - Some(progress_spinner) - } else { - None - }; + } - let (len, fps) = get_video_stats(&video_path)?; - let frames = len.signed_duration_since(NaiveTime::MIN).num_seconds() as f64 * fps; - if frames > max_frames { - max_frames = frames; - } - for (subtitle, not_cc) in format.subtitles.iter() { - 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) - } + 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.merge_sync_tolerance.unwrap(), + self.merge_sync_precision.unwrap(), + )?; + drop(_progress_handler); - 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, + 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()) + - 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, so the application was skipped"); + offsets = None; + offset_pre_checked = true } } - 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(offsets) = offsets { + let mut root_format_idx = 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_offset = offset.num_milliseconds() as u64; + if format_offset < root_format_offset { + root_format_idx = i; + root_format_offset = format_offset; + } + + for _ in &format.audios { + if let Some(offset) = &offsets.get(&i) { + audio_offsets.insert(i, **offset); + } + } + for _ in &format.subtitles { + if let Some(offset) = &offsets.get(&i) { + subtitle_offsets.insert(i, **offset); + } + } + } + + 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).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") + } + } + } + + // 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 + 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.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 + } + + videos.push(FFmpegVideoMeta { + path, + length: len, + start_time: video_offset, + }) + } + + 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 + ) + .as_str(), + ) + .unwrap() + .tick_strings(&["—", "\\", "|", "/", ""]), + ) + .with_finish(ProgressFinish::Abandon); + progress_spinner.enable_steady_tick(Duration::from_millis(100)); + Some(progress_spinner) + } else { + None + }; + + for (j, (subtitle, cc)) in format.subtitles.iter().enumerate() { + if *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 *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, + cc.then_some(" (cc)").unwrap_or_default(), + ); + subtitles.push(FFmpegSubtitleMeta { + path, + locale: subtitle.locale.clone(), + cc: *cc, + start_time: subtitle_offsets.get(&j).cloned(), + video_idx: i, + }) + } + } + + for format in self.formats.iter() { + if let Some(skip_events) = &format.metadata.skip_events { + let (file, path) = tempfile(".chapter")?.into_parts(); + chapters = Some(( + (file, path), + [ + skip_events.recap.as_ref().map(|e| ("Recap", e)), + skip_events.intro.as_ref().map(|e| ("Intro", e)), + skip_events.credits.as_ref().map(|e| ("Credits", e)), + skip_events.preview.as_ref().map(|e| ("Preview", e)), + ] + .into_iter() + .flatten() + .collect::>(), + )); + } } if self.download_fonts @@ -369,26 +560,55 @@ impl Downloader { let mut metadata = vec![]; for (i, meta) in videos.iter().enumerate() { + if let Some(start_time) = meta.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()]); 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(["-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()]); metadata.extend([ format!("-metadata:s:a:{}", i), - format!("language={}", meta.language), + format!( + "language={}", + self.audio_locale_output_map + .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(), + meta.video_idx + 1 + ) + } + ), ]); } @@ -408,6 +628,9 @@ impl Downloader { if container_supports_softsubs { for (i, meta) in subtitles.iter().enumerate() { + if let Some(start_time) = meta.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(), @@ -415,15 +638,43 @@ impl Downloader { ]); metadata.extend([ format!("-metadata:s:s:{}", i), - format!("language={}", meta.language), + format!( + "language={}", + self.subtitle_locale_output_map + .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_human_readable(); + if meta.cc { + title += " (CC)" + } + if videos.len() > 1 { + title += &format!(" [Video: #{}]", meta.video_idx + 1) + } + title + }), ]); } } + if let Some(((file, path), chapters)) = chapters.as_mut() { + write_ffmpeg_chapters(file, max_len, chapters)?; + input.extend(["-i".to_string(), path.to_string_lossy().to_string()]); + maps.extend([ + "-map_metadata".to_string(), + (videos.len() + + audios.len() + + container_supports_softsubs + .then_some(subtitles.len()) + .unwrap_or_default()) + .to_string(), + ]) + } + let preset_custom = matches!(self.ffmpeg_preset, FFmpegPreset::Custom(_)); let (input_presets, mut output_presets) = self.ffmpeg_preset.into_input_output_args(); let fifo = temp_named_pipe()?; @@ -432,7 +683,7 @@ impl Downloader { "-y".to_string(), "-hide_banner".to_string(), "-vstats_file".to_string(), - fifo.name(), + fifo.path().to_string_lossy().to_string(), ]; command_args.extend(input_presets); command_args.extend(input); @@ -447,10 +698,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([ @@ -474,7 +722,7 @@ impl Downloader { output_presets.remove(i - remove_count); remove_count += 1; } - last = s.clone(); + last.clone_from(s); } output_presets.extend([ @@ -509,7 +757,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), @@ -521,9 +769,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; } @@ -552,7 +798,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)? } } @@ -570,7 +816,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, @@ -584,27 +830,24 @@ impl Downloader { bail!("{}", String::from_utf8_lossy(result.stderr.as_slice())) } ffmpeg_progress_cancel.cancel(); - Ok(ffmpeg_progress.await??) + ffmpeg_progress.await? } async fn check_free_space( &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_stream_data_file_size(stream_data, &segments); } let tmp_stat = fs2::statvfs(temp_directory()).unwrap(); @@ -652,27 +895,24 @@ impl Downloader { async fn download_video( &self, - variant_data: &VariantData, + 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, variant_data) + self.download_segments(&mut file, message, stream_data, max_segments) .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, None) .await?; Ok(path) @@ -681,16 +921,47 @@ impl Downloader { async fn download_subtitle( &self, subtitle: Subtitle, - max_length: NaiveTime, + 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))?, + "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 + // (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 at most as long as `max_length` + // (https://github.com/crunchy-labs/crunchy-cli/issues/32) + for i in (0..ass.events.len()).rev() { + 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].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("ScaledBorderAndShadow".to_string(), "yes".to_string()); + let tempfile = tempfile(".ass")?; - let (mut file, path) = tempfile.into_parts(); + let path = tempfile.into_temp_path(); - let mut buf = vec![]; - subtitle.write_to(&mut buf).await?; - fix_subtitles(&mut buf, max_length); - - file.write_all(buf.as_slice())?; + fs::write(&path, ass.to_string())?; Ok(path) } @@ -717,7 +988,7 @@ impl Downloader { .await? .bytes() .await?; - fs::write(&file, font.to_vec())?; + fs::write(&file, font)?; Ok(Some((file, false))) } @@ -726,15 +997,21 @@ impl Downloader { &self, writer: &mut impl Write, message: String, - variant_data: &VariantData, + stream_data: &StreamData, + max_segments: Option, ) -> Result<()> { - let segments = variant_data.segments().await?; + 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(variant_data, &segments); + let estimated_file_size = estimate_stream_data_file_size(stream_data, &segments); let progress = ProgressBar::new(estimated_file_size) .with_style( @@ -751,8 +1028,8 @@ impl Downloader { None }; - let cpus = self.download_threads; - let mut segs: Vec> = Vec::with_capacity(cpus); + let cpus = self.download_threads.min(segments.len()); + let mut segs: Vec> = Vec::with_capacity(cpus); for _ in 0..cpus { segs.push(vec![]) } @@ -766,6 +1043,8 @@ impl Downloader { for num in 0..cpus { let thread_sender = sender.clone(); let thread_segments = segs.remove(0); + let thread_client = self.client.clone(); + let mut thread_rate_limiter = self.rate_limiter.clone(); let thread_count = count.clone(); join_set.spawn(async move { let after_download_sender = thread_sender.clone(); @@ -777,23 +1056,34 @@ impl Downloader { for (i, segment) in thread_segments.into_iter().enumerate() { let mut retry_count = 0; let buf = loop { - let mut buf = vec![]; - match segment.write_to(&mut buf).await { - Ok(_) => break buf, - Err(e) => { - if retry_count == 5 { - bail!("Max retry count reached ({}), multiple errors occurred while receiving segment {}: {}", retry_count, num + (i * cpus), e) - } - debug!("Failed to download segment {} ({}). Retrying, {} out of 5 retries left", num + (i * cpus), e, 5 - retry_count) + let request = thread_client + .get(&segment.url) + .timeout(Duration::from_secs(60)); + let response = if let Some(rate_limiter) = &mut thread_rate_limiter { + rate_limiter.call(request.build()?).await.map_err(anyhow::Error::new) + } else { + request.send().await.map_err(anyhow::Error::new) + }; + + let err = match response { + Ok(r) => match r.bytes().await { + Ok(b) => break b.to_vec(), + Err(e) => anyhow::Error::new(e) } + Err(e) => e, + }; + + if retry_count == 5 { + bail!("Max retry count reached ({}), multiple errors occurred while receiving segment {}: {}", retry_count, num + (i * cpus), err) } + debug!("Failed to download segment {} ({}). Retrying, {} out of 5 retries left", num + (i * cpus), err, 5 - retry_count); retry_count += 1; }; 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, @@ -833,7 +1123,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; @@ -882,12 +1172,12 @@ 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_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